From necmettin.begiter at gmail.com Sun Feb 4 04:01:50 2007 From: necmettin.begiter at gmail.com (Necmettin Begiter) Date: Sun, 4 Feb 2007 11:01:50 +0200 Subject: Definitions of editor and IDE? In-Reply-To: <20070203224824.0CC7C1E400A@bag.python.org> References: <20070203224824.0CC7C1E400A@bag.python.org> Message-ID: <200702041101.51017.necmettin.begiter@gmail.com> 04 ?ub 2007 Paz 00:48 tarihinde, Dick Moores ?unlar? yazm??t?: > Are there generally accepted definitions of "editor" and "IDE". Is there a > clear-cut distinction between them? I've been looking at the lists of each > at python.org, < http://wiki.python.org/moin/PythonEditors>? and < > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments>. Many > programs are on both lists: Komodo, Eclipse, jedit, SPE, Wing IDE, UliPad, > etc. > > Dick Moores Can't give definitions, but here is the difference: if you use an editor, you will have to run your script or program from outside the editor; if you use an IDE, you will press a key or key combination in the IDE (say F9 or F5) and your program/script will run... From horpner at yahoo.com Mon Feb 5 08:22:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 5 Feb 2007 14:22:39 +0100 Subject: confused about resizing array in Python References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: On 2007-02-04, Marc 'BlackJack' Rintsch wrote: >> How about the traditional programming languages like C, Pascal >> or C++? > > For a start they don't have a built in list type. C and Pascal > don't even have one in the standard library. C++ has STL > vectors and if you, the programmer, decide to store pointers in > it instead of structures or objects then you have something > like Python's list type. You need to store some form of smart pointer (rather than a bare pointer) in C++ standard containers in order to avoid heart, head and stomach aches. A reference counted pointer type will come fairly close to Python semantics. -- Neil Cerutti Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent Paul Collier From deets at nospam.web.de Mon Feb 5 12:23:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Feb 2007 18:23:46 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: <52p7h2F1pg9igU1@mid.uni-berlin.de> Gosi wrote: > On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: >> Gosi wrote: >> > It is quite easy to call J from Python >> >> http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... >> >> What is J, and why should we care? >> >> Diez > > J is in many ways similar to Python. > > J has very many advanced operations. What exactly do you call "similar to python" when the following is a program written in it? Compared to that, even Perl is a wonder of readability... m =: >@(0&{) v =: >@(1&{) h =: >@(2&{) qu =: >@(3&{) z =: i. at 0: ret =: |.@}: init =: z;z;z;i. f1m =: (m,{. at qu);v;h;}. at qu f5m =: (z;(v,{:@m);h;qu,ret at m) @ (f1m^:5) f1h =: (z;z;(h,{:@v);(qu,ret at v)) @ (f5m^:12) f12h =: (z;z;z;qu,ret at h,{:@h) @ (f1h^:12) perm =: qu @ f12h @ init ord =: *./ @ (#&>"_) @ C. days =: -: @ ord @ perm http://www.jsoftware.com/jwiki/Essays/The_Ball_Clock_Problem Diez From adamgarstang at googlemail.com Wed Feb 28 15:47:55 2007 From: adamgarstang at googlemail.com (Adam) Date: 28 Feb 2007 12:47:55 -0800 Subject: New to Tkinter GUI building Message-ID: <1172695675.279652.98920@a75g2000cwd.googlegroups.com> Hey, I'm pretty new to programming. Been trying to learn using Python. The code I'm struggling with is for my GUI. I'm am having trouble getting this to display the way I want with the grid manager. Can anybody tell me what I am doing wrong? I hope you can tell what look I'm trying to achieve from the code as its hard to explain. I think my main questions are: 1. How can I get the Window to be sized the way I want it? 2. How can I get the Scrollbars to fill the side of the text box instead of being small? (like .pack(fill= tk.Y) ######Code####### #file/path finder #indentation value 4 import os,glob import Tkinter as tk # Class to create the Application and UI class Theapp: def __init__(self): # Create GUI parts. Will allign later with grid self.top = tk.Tk() self.mainWindow = tk.Frame(self.top, width=700, height=400) self.labAll = tk.Label(self.mainWindow, text="All Files/ Folders:") self.labVi = tk.Label(self.mainWindow, text="Violating Files/ Folders:") #Create a sub-frame containing textbox and scrollbar for All files scanned display self.allTxtf = tk.Frame(self.mainWindow, width=699, height=164) self.scrlr1 = tk.Scrollbar(self.allTxtf) self.txtBoxall = tk.Text(self.allTxtf, wrap=tk.CHAR, yscrollcommand=self.scrlr1.set) self.scrlr1.config(command = self.txtBoxall.yview) #Create another sub-frame containing textbox and scrollbar for the Violating files display self.viTxtf = tk.Frame(self.mainWindow, width=699, height=164) self.scrlr2 = tk.Scrollbar(self.viTxtf) self. txtBoxvi = tk.Text(self.viTxtf, wrap=tk.CHAR, yscrollcommand=self.scrlr2.set) self.scrlr2.config(command = self.txtBoxvi.yview) #Create another sub-frame to contain the controls self.ctrlFrame = tk.Frame(self.mainWindow, width=699, height=72) self.labDir = tk.Label(self.ctrlFrame, text="Dir:") self.entDir = tk.Entry(self.ctrlFrame) self.labChar = tk.Label(self.ctrlFrame, text="Char. Limit:") self.entChar = tk.Entry(self.ctrlFrame) self.btFind = tk.Button(self.ctrlFrame, text="Scan", command = self.fillboxes) self.btExit = tk.Button(self.ctrlFrame, text="Exit", command = self.quitEvent) #Use tkinter's grid geometry manager to allign and display the GUI self.mainWindow.grid() #Frist allign the 3 main frames self.labAll.grid(row=0) self.allTxtf.grid(row=1) self.labVi.grid(row=2) self.viTxtf.grid(row=3) self.ctrlFrame.grid(row=4) #Now allign the content of allTxtf self.txtBoxall.grid(row=0, column=0) self.scrlr1.grid(row=0, column=1) #Now allign the content for viTxtf self.txtBoxvi.grid(row=0, column=0) self.scrlr2.grid(row=0, column=1) #Now allign the content for ctrlFrame self.labDir.grid(row=0, column=0, sticky=tk.E) self.entDir.grid(row=0, column=1) self.labChar.grid(row=0, column=2, sticky=tk.E) self.entChar.grid(row=0, column=3) self.btFind.grid(row=0, column=4) self.btExit.grid(row=0,column=5) def findallfiles(self, base): pass def fillboxes(self): pass def quitEvent(self): raise SystemExit app = Theapp() app.mainWindow.mainloop() ######End Code####### I have only posted the code relevant to the GUI. TIA Adam From python at hope.cz Thu Feb 8 11:28:25 2007 From: python at hope.cz (Johny) Date: 8 Feb 2007 08:28:25 -0800 Subject: Strings in Python Message-ID: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> Playing a little more with strings, I found out that string.find function provides the position of the first occurance of the substring in the string. Is there a way how to find out all substring's position ? To explain more, let's suppose mystring='12341' import string >>> string.find(mystring ,'1') 0 But I need to find the possition the other '1' in mystring too. Is it possible? Or must I use regex? Thanks for help L From grflanagan at yahoo.co.uk Thu Feb 15 08:47:14 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 15 Feb 2007 05:47:14 -0800 Subject: basic jython question In-Reply-To: References: <1171543539.339651.319480@m58g2000cwm.googlegroups.com> Message-ID: <1171547234.910049.144010@a34g2000cwb.googlegroups.com> On Feb 15, 1:53 pm, "Richard Brodie" wrote: > "Gerard Flanagan" wrote in message > > news:1171543539.339651.319480 at m58g2000cwm.googlegroups.com... > > > I have a 'logger' module which is essentially just a facade over the > > 'logging' standard module. Can this be called from jython, and how is > > this acheived? This is a colleague's question but I have no knowledge > > of jython or java, and I can't install them at present in order to > > figure it out. > > Since the CPython module is heavily influenced by the native Java logging > framework (and/or log4j), I would have thought that it would be easier > to create a Jython wrapper for those. Ok, thanks. I'll suggest that. Gerard From kay.schluehr at gmx.net Thu Feb 8 02:03:35 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 7 Feb 2007 23:03:35 -0800 Subject: Does the world need another v0.1 python compiler? In-Reply-To: References: Message-ID: <1170918215.074099.262930@p10g2000cwp.googlegroups.com> On 8 Feb., 17:00, John Nagle wrote: > Grant Olson wrote: > > The basic approach I took was compiling to bytecode, and then > > transliterating python bytecode to x86 asm. And it is working a little bit. > > An interesting option might be to generate the byte code used by > the SpiderMonkey engine in Mozilla. That's used to handle both > Javascript in Firefox and ActionScript in Flash. It has a just-in-time > compiler, so you get x86 machine code when you need it. > And the run time engine is tiny; there's a copy inside Flash, which is > only 2MB. > > That could be a way to get a faster Python without bringing excess > baggage. > > John Nagle This code generation for an arbitrary backend sounds more like an appropriate task for PyPy. I think Grant's or anyone elses compiler could be a viable tool for augmenting the CPython interpreter in particular in the presence of optional type annotations in Py3K. From paul at eventuallyanyway.com Sat Feb 10 14:07:46 2007 From: paul at eventuallyanyway.com (Paul Hummer) Date: Sat, 10 Feb 2007 19:07:46 +0000 Subject: wxPython libraries never detected In-Reply-To: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> Message-ID: <45CE1802.6020105@eventuallyanyway.com> d.lidell at gmail.com wrote: > Hi, I recently started coding with Python and I've been trying for the > past hour or so to determine why, every time I "import wx" (or compile > another piece of code that imports wx), Python can never find the > libraries. > > I'm running Ubuntu Edgy 6.10, and, as per http://www.wxpython.org/download.php#sources, > updated sources.list with the sources and installed python-wxgtk2.8, > python-wxtools and wx2.8-i18n. I compiled the latest Python (as of > writing), 2.5, from source. > > For example, SPE tells me that I "need to install at least wxPython v. > 2.5.4.1 to run SPE" and any code that relies on "import wx" reports > "ImportError: No module named wx". However, "whereis wx" on the > command line reports "wx: /usr/lib/wx /usr/local/lib/wx /usr/include/ > wx". What could be wrong here? I can't figure out why wx isn't being > detected. > > Many thanks. > > Doing a `whereis wx` won't tell you about the python library installation. I'm using Ubuntu Edgy, with Python 2.4 installed (from apt), and wx-2.6. I can find the libraries in /usr/lib/python2.4/wx-2.6-gtk-unicode/ Check to see if you have wx installed in /usr/lib/python2.5 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Thu Feb 22 19:15:57 2007 From: sjmachin at lexicon.net (John Machin) Date: 22 Feb 2007 16:15:57 -0800 Subject: How to covert ASCII to integer in Python? In-Reply-To: References: Message-ID: <1172189757.487956.192130@l53g2000cwa.googlegroups.com> On Feb 23, 5:23 am, "John" wrote: > I just found ord(c), which convert ascii to integer. ord('\xff') -> 255 ord(unichr(666)) -> 666 What ascii? What is stopping you from reading the documentation section on built- in functions (http://docs.python.org/lib/built-in-funcs.html)? That way, you might find an answer to whatever your question really is, without wasting time (yours and that of others trying to guess). > > Anybody know what the reverse is? > > "John" wrote in message > > news:erkknl$6d4p$1 at netnews.upenn.edu... > > > Is there any built in function that converts ASCII to integer or vice > versa > > in Python? > > > Thanks! From gagsl-py at yahoo.com.ar Fri Feb 16 05:37:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 07:37:45 -0300 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 07:11:36 -0300, exhuma.twn escribi?: > Hi all, > > Supposing you have two separate processes running on the same box, > what approach would you suggest to communicate between those two > processes. > > Let me list the ones I know of: > > * Sockets > Advantage: Supported per se in nearly every programming language > without even the need to install additional packages > Disadvantage: Lot's of code to write, and it's kind of silly to > communicate via TCP/IP if the processes run on the same machine. Not so much code, really. (And I would expect that making a connection to "localhost" actually does *not* go down up to the network card hardware layer, but I don't know for real if this is the case or not). > * Webservices > Advantage: Relatively easy to use, can work across different > languages > Disadvantage: Even more overhead on the TCP/IP side that simple > sockets, as really bulky SOAP messages need to be passed around. You could use XMLRPC, wich is a lot simpler (but less powerful). > * CORBA -- similar to webservices but more complicated to code. I would stay away as far as I could. > * Shared memory > I don't know much about this subject. You forget the most basic one, stdio redirection. Easy, available on almost any language, but limited to just a pair of processes. You can add queues and messages. > Supposing both processes are written in Python, is there any other way > to achieve this? To me, shared memory sound the most suited approach. > But as said, I am still fuzzy in this area. Where can I find more > information on this subject? Pyro appears to be a good alternative (altough I've never used it yet). -- Gabriel Genellina From gagsl-py at yahoo.com.ar Mon Feb 19 20:50:25 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 22:50:25 -0300 Subject: Checking for EOF in stream References: <12tkgeh32duee72@corp.supernews.com> <45DA45C3.2000707@gentlemail.com> Message-ID: En Mon, 19 Feb 2007 21:50:11 -0300, GiBo escribi?: > Grant Edwards wrote: >> On 2007-02-19, GiBo wrote: >>> >>> Classic situation - I have to process an input stream of unknown length >>> until a I reach its end (EOF, End Of File). How do I check for EOF? The >>> input stream can be anything from opened file through sys.stdin to a >>> network socket. And it's binary and potentially huge (gigabytes), thus >>> "for line in stream.readlines()" isn't really a way to go. >>> >>> For now I have roughly: >>> >>> stream = sys.stdin >>> while True: >>> data = stream.read(1024) >> if len(data) == 0: >> break #EOF >>> process_data(data) > > Right, not a big difference though. Isn't there a cleaner / more > intuitive way? Like using some wrapper objects around the streams or > something? Read the documentation... For a true file object: read([size]) ... An empty string is returned when EOF is encountered immediately. All the other "file-like" objects (like StringIO, socket.makefile, etc) maintain this behavior. So this is the way to check for EOF. If you don't like how it was spelled, try this: if data=="": break If your data is made of lines of text, you can use the file as its own iterator, yielding lines: for line in stream: process_line(line) -- Gabriel Genellina From aspineux at gmail.com Fri Feb 2 08:25:00 2007 From: aspineux at gmail.com (aspineux) Date: 2 Feb 2007 05:25:00 -0800 Subject: asyncore DoS vulnerability In-Reply-To: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> Message-ID: <1170422700.309941.203320@a34g2000cwb.googlegroups.com> Did you take a look for "too many file descriptors in select()" on google. On 1 f?v, 20:18, "billie" wrote: > Hi all. I've just terminated a server application using asyncore / > asynchat frameworks. > I wrote a test script that performs a lot of connections to the server > app and I discovered that asyncore (or better, select()) can manage > only a limited number of file descriptors (aka simultaneous > connections). I thing this is the system that limit the number of open sockets or select() list > When this number is reached select() raises an error but asyncore > doesn't handle this exception (a crash occurs). This is not a CRASH, It looks an exception with a "Traceback", this is the normal way python report problems, nothing wrong with that. You can handle it with a try: except: > If you want to try this I pasted two scripts below: a server and a > client. > On my Windows XP system server.py the crash occurs when 512 > simultaneous connections are reached. 512 is probably a fixed limit into XP, win2k3 or win2k server will accept more. Maybe It's possible to increase this value somewhere in the registry. If not this is how microsoft justify the difference between server and workstation products :-) > Here's the traceback: > > Traceback (most recent call last): > File "C:\Documents and Settings\root\Desktop\test.py", line 31, in ? > asyncore.loop(timeout=1) > File "C:\Python24\lib\asyncore.py", line 192, in loop > poll_fun(timeout, map) > File "C:\Python24\lib\asyncore.py", line 122, in poll > r, w, e = select.select(r, w, e, timeout) > ValueError: too many file descriptors in select() > > Why does this exception isn't handled inside asyncore.py? To do what ? To raise a custom asyncore error ? You can can probably run over this limit by starting multiple of your server process (not thread, process) . > > ---------------------------------------------------- > # server.py > import asyncore, socket > > class server(asyncore.dispatcher): > """The base class for the backend.""" > > def __init__(self): > asyncore.dispatcher.__init__(self) > self.create_socket(socket.AF_INET, socket.SOCK_STREAM) > self.bind(('', 8080)) > self.listen(5) > > def handle_accept(self): > sock_obj, addr = self.accept() > handler(sock_obj) > > class handler(asyncore.dispatcher): > > def __init__(self, sock_obj): > asyncore.dispatcher.__init__(self, sock=sock_obj) > > def handle_write(self): > pass > > def handle_read(self): > pass > > server() > asyncore.loop(timeout=1) > > ----------------------------------------------------- > > # client.py > import socket, threading, os > > def client(): > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > try: > s.connect(("127.0.0.1", 8080)) > except: > print x > os._exit(0) > while 1: > s.recv(1024) > > x = 0 > while 1: > x +=1 > threading.Thread(target=client).start() > print x From bobmon at gmail.com Sat Feb 24 18:18:16 2007 From: bobmon at gmail.com (bobmon) Date: 24 Feb 2007 15:18:16 -0800 Subject: Newbie question: Install Tkinter with Python2.5 In-Reply-To: <45de03c6$0$8891$9b622d9e@news.freenet.de> References: <45de03c6$0$8891$9b622d9e@news.freenet.de> Message-ID: <1172359096.030769.146660@p10g2000cwp.googlegroups.com> > how can I install Tkinter with Python2.5? I can install Python2.5 > (tarball) in the usual way but there is no Tkinter? What's wrong? I'm trying to build Python 2.5 under FC6, and had similar problems (plus others). I had to do "yum install" 'tcl-devel.i386' and 'tk- devel.i386' to get the tcl portion to work. HTH. From gagsl-py at yahoo.com.ar Tue Feb 13 00:40:06 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 02:40:06 -0300 Subject: how to compare... References: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> Message-ID: En Tue, 13 Feb 2007 01:03:07 -0300, jairodsl escribi?: > I have two list, they are, S1=['A','B','C','D','E'], and > S2=['F','G','H','I','J'], but i have to compare both in this way: > > A vs J > A vs I, B vs J > A vs H, B vs I, C vs J > A vs G, B vs H, C vs I, D vs J > A vs F, B vs G, C vs H, D vs I, E vs J > B vs F, C vs G, D vs H, E vs I > C vs F, D vs G, E vs H > D vs F, E vs G > E vs F And what to do after comparing each pair? Anyway, this would be one general approach: First, forget about the lists. Use numbers instead of letters (0 to 4), and try to generate the pairs of numbers needed. Once your program can generate the right number pairs, use those numbers as indexes into the lists. -- Gabriel Genellina From lorenzo.viscanti at gmail.com Tue Feb 6 06:30:42 2007 From: lorenzo.viscanti at gmail.com (Lorenzo) Date: 6 Feb 2007 03:30:42 -0800 Subject: XMLRPC Server In-Reply-To: <52r41eF1p17pqU1@mid.uni-berlin.de> References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> <52r41eF1p17pqU1@mid.uni-berlin.de> Message-ID: <1170761442.053280.194910@k78g2000cwa.googlegroups.com> Unfortunately I have to use Apache. The server implementation will be very easy, so I'm also considering more efficient solutions than python lv On Feb 6, 11:36 am, "Diez B. Roggisch" wrote: > visca... at gmail.com wrote: > > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > > It's not too difficult to configure everything, but I would like to > > tune it in order to receive up to 2000 calls per minute without any > > problems. Do Pthon CGIs use threading? > > I need to make it very efficient, but I haven't found much information > > about Python CGI optimization. > > The called function will update a table in a mysql db. I will use > > triggers to export data from the table updated by the xmlrpc server to > > other tables used by the backend application. > > You might consider using the twisted application server framework instead, > and totally ditch the CGI, and even the apache. > > http://twistedmatrix.com/ > > http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py > > Diez From silovana.vjeverica at com.gmail Sat Feb 3 11:21:15 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Sat, 3 Feb 2007 17:21:15 +0100 Subject: Jython Message-ID: Hi Why this doesn't work: def go(): for line in open("bobo.txt", "r"): print line go() python FileReader.py: everything ok jython FileReader.py: Traceback (innermost last): File "FileReader.py", line 6 File "FileReader.py", line 3 AttributeError: __getitem__ -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" From deets at nospam.web.de Mon Feb 26 16:46:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Feb 2007 22:46:43 +0100 Subject: Walk thru each subdirectory from a top directory In-Reply-To: <1172525300.450438.57080@8g2000cwh.googlegroups.com> References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> Message-ID: <54h2qrF20oavvU1@mid.uni-berlin.de> silverburgh.meryl at gmail.com schrieb: > i am trying to use python to walk thru each subdirectory from a top > directory. Here is my script: > > savedPagesDirectory = "/home/meryl/saved_pages/data" > > dir=open(savedPagesDirectory, 'r') > > for file in dir: > if (isdir(file)): > # get the full path of the file > fileName = savedPagesDirectory + file + 'index.html' > print fileName > > $ ./scripts/regressionTest.py > Traceback (most recent call last): > File "./scripts/regressionTest.py", line 12, in ? > dir=open(savedPagesDirectory, 'r') > IOError: [Errno 21] Is a directory > > But I get the above error: > > Can you please tell me what did I do wrong? You can't open a directory. Use the function os.walk to do what you want. Diez From Bulkan at gmail.com Wed Feb 21 00:26:18 2007 From: Bulkan at gmail.com (placid) Date: 20 Feb 2007 21:26:18 -0800 Subject: getting a thread out of sleep In-Reply-To: <1172035303.424370.20140@t69g2000cwt.googlegroups.com> References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> Message-ID: <1172035578.410747.319890@j27g2000cwj.googlegroups.com> On Feb 21, 4:21 pm, "placid" wrote: > On Feb 21, 4:12 pm, mark wrote: > > > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > On Feb 21, 3:08 pm, mark wrote: > > > > Right now I have a thread that sleeps for sometime and check if an > > > > event has happened and go back to sleep. Now instead I want the thread > > > > to sleep until the event has occured process the event and go back to sleep > > > > > class eventhndler(threading.Thread): > > > > def __init__(self): > > > > threading.Thread.__init__(self) > > > > def run(self): > > > > while True: > > > > time.sleep(SLEEPTIME) > > > > ''''do event stuff''' > > > > The way i would do this is by using an threading.Event ( > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > class eventhandler(threading.Thread): > > > def __init__(self): > > > threading.Thread.__init__(self) > > > self.event = threading.Event() > > > def run: > > > while True: > > > # block until some event happens > > > self.event.wait() > > > """ do stuff here """ > > > self.event.clear() > > > > > > > the way to use this is to get the main/separate thread to set() the > > > event object. > > > Can you give an example of how to get the main threead to set teh event object? > > this is exactly what i wanted to do! > > thanks a lot! > > mark > > To set the event object > > > > if __name__ == "__main__": > evtHandlerThread = eventhandler() > evtHandler.start() > > # do something here # > evtHandler.event.set() > > # do more stuff here # > evtHandler.event.set() > > > > Hope thats what your looking for. > > Cheers oops I've miss-typed the thread variable name the following should work if __name__ == "__main__": evtHandlerThread = eventhandler() evtHandlerThread.start() # do something here # evtHandlerThread.event.set() # do more stuff here # evtHandlerThread.event.set() From __peter__ at web.de Mon Feb 19 13:03:11 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 19:03:11 +0100 Subject: Declare a variable global References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> <1171907496.269876.295200@p10g2000cwp.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > On Feb 19, 11:09 am, Jean-Paul Calderone wrote: >> On 19 Feb 2007 09:04:19 -0800, "ying... at gmail.com" >> wrote: >> >> >Hi, >> >> >I have the following code: >> >> >colorIndex = 0; >> >> >def test(): >> > print colorIndex; >> >> >This won't work. >> >> Are you sure? >> >> exarkun at charm:~$ cat foo.py >> colorIndex = 0 >> >> def test(): >> print colorIndex >> >> test() >> exarkun at charm:~$ python foo.py >> 0 >> exarkun at charm:~$ >> >> The global keyword lets you rebind a variable from the module scope. It >> doesn't have much to do with accessing the current value of a variable. >> >> Jean-Paul > > Thanks. Then I don't understand why I get this error in line 98: > > Traceback (most recent call last): > File "./gensvg.py", line 109, in ? > outdata, minX, minY, maxX, maxY = getText(data); > File "./gensvg.py", line 98, in getText > print colorIndex; > UnboundLocalError: local variable 'colorIndex' referenced before > assignment When there is an assignment python assumes that the variable is in the local scope (unless you explicitly declare it as global): >>> v = 42 >>> def f(): ... print v ... >>> f() 42 >>> def g(): ... print v ... v = "won't get here anyway" ... >>> g() Traceback (most recent call last): File "", line 1, in File "", line 2, in g UnboundLocalError: local variable 'v' referenced before assignment >>> def h(): ... global v ... print v ... v = "for all the world to see" ... >>> h() 42 >>> v 'for all the world to see' Peter From stefan.behnel-n05pAM at web.de Sun Feb 25 07:35:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 25 Feb 2007 13:35:06 +0100 Subject: HTML Parsing In-Reply-To: <1171182045.946209.15730@l53g2000cwa.googlegroups.com> References: <1171148863.807386.310960@h3g2000cwc.googlegroups.com> <1171182045.946209.15730@l53g2000cwa.googlegroups.com> Message-ID: <45E1827A.7040409@web.de> John Machin wrote: > One can even use ElementTree, if the HTML is well-formed. See below. > However if it is as ill-formed as the sample (4th "td" element not > closed; I've omitted it below), then the OP would be better off > sticking with Beautiful Soup :-) Or (as we were talking about the best of both worlds already) use lxml's HTML parser, which is also capable of parsing pretty disgusting HTML-like tag soup. Stefan From mail at microcorp.co.za Sat Feb 17 04:09:56 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 17 Feb 2007 11:09:56 +0200 Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com><1171592265.316602.234820@s48g2000cws.googlegroups.com><1171612923.145381.220960@p10g2000cwp.googlegroups.com> Message-ID: <026901c7527c$be7e0260$03000080@hendrik> "Sch?le Daniel" wrote: > > > {:} for empty dict and {} for empty set don't look too much atrocious > > to me. > > this looks consistent to me I disagree. What would be consistent would be to follow the pattern, and use a different set of delimiters. Python uses () for tuples, [] for lists, {} for dictionaries. To be consistent, sets need something else, so you can see at a glance what you are dealing with. About all that is left is <>, ugly as it is. The other way is the start of the slippery slide into alphabet soup. - Hendrik From __peter__ at web.de Thu Feb 15 12:58:30 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 15 Feb 2007 18:58:30 +0100 Subject: re.search making no match == 0 References: Message-ID: Lance Hoffmeyer wrote: > I have a search: > > VAR = re.search("PROVEN.*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" , pcpT9, re.S > ).group(1) #.split()[1] > > that does not match (sometimes it will and sometimes it will not match) > > Traceback (most recent call last): > File "P:\Burke\TRACKERS\Ortho-McNeil\Automation\Wave3\test.py", line 53, > in ? > VAR = re.search("PROVEN.*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" , pcpT9, > re.S ).group(1) #.split()[1] > AttributeError: 'NoneType' object has no attribute 'group' > > > Is there a way in python to make this "non" match equal a value (say, > "0")? match = re.search(...) if match: value = match.group(1) else: value = default Wrap that into a function and you can use it inside a list comprehension. > This one line is actually a series of searches > > Reasons = ["EFFICACY","EFFECTIVE","WORKS > QUICKLY","PROVEN","SAFETY","LITTLE","WELL"," BETTER","SAMPLES"] # > Reasons(29) > VAR = [re.search(r"%s.*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" % i, pcpT9, > re.S ).group(1) for i in Reasons ] #.split()[1] > > and one of the items in the array may or may not be present. How about a slightly different approach (untested): r = re.compile(r"(%s).*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" % "|".join(reasons), re.S) groups = dict(m.groups() for m in r.finditer(pcpT9)) VAR = [groups.get(reason, "0") for reason in reasons] I recommend that you don't create the VAR list and use groups directly. If you are using Python 2.5 you can replace the builtin dict with a collections.defaultdict. Peter From bdesth.quelquechose at free.quelquepart.fr Sun Feb 18 13:34:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 18 Feb 2007 19:34:16 +0100 Subject: function & class In-Reply-To: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> References: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> Message-ID: <45d894ac$0$30651$426a74cc@news.free.fr> jupiter a ?crit : > hi friends, > > I have a program like > > some variable definations > > a function ( arg1, agr2): > do something with arg1 & arg2 > return a list > > if condition > do this function(arg1,arg2) > else > if condition > do this function > else > do this > > > My problem is I want to use threading and I might need to pass values > between function and classes. which classes ? I see no class statement in your above pseudo-code. > I am not sure how this can be done. I > have read about classes and I know they are like function Hmm. While technically, yes, Python classes are "callable" just like functions are, this is mostly an implementation detail (or at least you can consider it as such for now). Now from a conceptual POV, functions and classes are quite different beasts. > however does > not return anything where as function does. Where did you get such "knowledge", if I may ask ? Looks like you need a better source of informations !-) > If I define class and then > function in this class how do I access this function ????? Classes are used to define and create ('instanciate' in OO jargon) objects. Usually, one first creates an object, then calls methods on this object: class Greeter(object): def __init__(self, name, saywhat=None): self.name = name if self.saywhat is None: self.saywhat = "Hello %(who)s, greetings from %(name)s" else: self.saywhat = saywhat def greet(self, who): return self.saywhat % dict(name=self.name, who=who) bruno = Greeter('Bruno') print bruno.greet('Jupiter') > I am not sure and confused about classes and functions as how to go > about them is there any simple way to understand difference between > them Read a tutorial on OO ? Here's one: http://pytut.infogami.com/node11-baseline.html > and when to use what and how to pass data/reference pointer > between them ? In Python, everything you can name, pass to a function or return from a function is an object. > @nil > Pythonist > From eric.pederson at gmail.com Fri Feb 23 10:44:30 2007 From: eric.pederson at gmail.com (Eric Pederson) Date: Fri, 23 Feb 2007 07:44:30 -0800 Subject: Convert to binary and convert back to strings In-Reply-To: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <45DF0BDE.6090403@gmail.com> Harlin Seritt wrote: >Hi... > >I would like to take a string like 'supercalifragilisticexpialidocius' >and write it to a file in binary forms -- this way a user cannot read >the string in case they were try to open in something like ascii text >editor. I'd also like to be able to read the binary formed data back >into string format so that it shows the original value. Is there any >way to do this in Python? > >Thanks! > >Harlin > > > To my mind, the more sensible job you do at programming this the worse off you are, unless you use strong encryption. There are nearly infinite approaches, so the random approach you use will be part of the "security" of the obfuscation. OK, I am not really taking this so seriously, but it is a fun question (Python makes these minor things fun). Is there anyway to do this in Python? You bet, so many ways... here's another: s="""I would like to take a string like 'supercalifragilisticexpialidocius' and write it to a file in binary forms -- this way a user cannot read the string in case they were try to open in something like ascii text editor. I'd also like to be able to read the binary formed data back into string format so that it shows the original value. Is there any way to do this in Python?""" s0=s+"$" s2="0 ".join([str(ord(c)) for c in s]) s1="".join([chr(int(i[:-1])) for i in s2.split(" ")[:-1]])+chr(int(s2[-1]))[:-1] def codeMe(s): s0=s+"$" return "0 ".join([str(ord(c)) for c in s0]) def uncodeMe(s): return "".join([chr(int(i[:-1])) for i in s.split(" ")[:-1]])+chr(int(s[-1]))[:-1] def testit(s): s2=codeMe(s) s1=uncodeMe(s2) strings={"original":s, "obfuscated":s2, "decoded":s1} for k in strings.keys(): print k,": ","\n",strings[k], "\n\n" testit(s) ------------- the obfuscated looks like this: 730 320 1190 1110 1170 1080 1000 320 1080 1050 1070 1010 320 1160 1110 320 1160 970 1070 1010 320 970 320 1150 1160 1140 1050 1100 1030 320 1080 1050 1070 1010 320 390 1150 1170 1120 1010 1140 990 970 1080 1050 1020 1140 970 1030 1050 1080 1050 1150 1160 1050 990 1010 1200 1120 1050 970 1080 1050 1000 1110 990 1050 1170 1150 390 100 970 1100 1000 320 1190 1140 1050 1160 1010 320 1050 1160 320 1160 1110 320 970 320 1020 1050 1080 1010 320 1050 1100 320 980 1050 1100 970 1140 1210 320 1020 1110 1140 1090 1150 320 450 450 320 1160 1040 1050 1150 320 1190 970 1210 320 970 320 1170 1150 1010 1140 320 990 970 1100 1100 1110 1160 320 1140 1010 970 1000 100 1160 1040 1010 320 1150 1160 1140 1050 1100 1030 320 1050 1100 320 990 970 1150 1010 320 1160 1040 1010 1210 320 1190 1010 1140 1010 320 1160 1140 1210 320 1160 1110 320 1110 1120 1010 1100 320 1050 1100 320 1150 1110 1090 1010 1160 1040 1050 1100 1030 320 1080 1050 1070 1010 320 970 1150 990 1050 1050 320 1160 1010 1200 1160 100 1010 1000 1050 1160 1110 1140 460 320 730 390 1000 320 970 1080 1150 1110 320 1080 1050 1070 1010 320 1160 1110 320 980 1010 320 970 980 1080 1010 320 1160 1110 320 1140 1010 970 1000 320 1160 1040 1010 320 980 1050 1100 970 1140 1210 320 1020 1110 1140 1090 1010 1000 320 1000 970 1160 970 320 980 970 990 1070 100 1050 1100 1160 1110 320 1150 1160 1140 1050 1100 1030 320 1020 1110 1140 1090 970 1160 320 1150 1110 320 1160 1040 970 1160 320 1050 1160 320 1150 1040 1110 1190 1150 320 1160 1040 1010 320 1110 1140 1050 1030 1050 1100 970 1080 320 1180 970 1080 1170 1010 460 320 730 1150 320 1160 1040 1010 1140 1010 320 970 1100 1210 100 1190 970 1210 320 1160 1110 320 1000 1110 320 1160 1040 1050 1150 320 1050 1100 320 800 1210 1160 1040 1110 1100 630 36 Of course some overly curious application user may note the pattern of "0" endings, strip those off, concatenate the numbers, and try several conversions on them, at which point they may figure this out- and contact you to gloat that they have hacked the file. That's when you recruit them onto your development team and give them some real work. :-) Have fun EP From kylotan at gmail.com Tue Feb 6 11:46:29 2007 From: kylotan at gmail.com (Ben Sizer) Date: 6 Feb 2007 08:46:29 -0800 Subject: when will python 2.5 take in mainstream? In-Reply-To: References: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> Message-ID: <1170780389.535028.60400@j27g2000cwj.googlegroups.com> On Feb 6, 3:35 pm, a... at pythoncraft.com (Aahz) wrote: > Ben Sizer wrote: > > >It would be great if someone could invest some time in trying to fix > >this problem. I don't think I know of any other languages that require > >recompilation of libraries for every minor version increase. > > How do you define "minor version increase"? If you look at the > progression from 2.0 through 2.5, it's pretty clear that each version > doesn't particularly fit "minor version increase" even though each one > only increments by 0.1. I can't say I agree with that. In terms of naming, it's a minor release because the 'major' release number has stayed at 2. In terms of time, it's a minor release because it's only happening about once every 18 months or so - a short period in computer language terms. In terms of semantics, I'd argue they are minor releases because generally the changes are just minor additions rather than large revisions; I don't see much in the way of significant language alterations for 2.5 apart from arguably 'unified try/except/finally', nor in 2.4. I don't count addition of new types or modules as 'major'. The language itself is fairly stable; it's just the way that it links to extensions which is pretty fragile. -- Ben Sizer From gagsl-py at yahoo.com.ar Wed Feb 21 04:59:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Feb 2007 06:59:58 -0300 Subject: BDFL in wikipedia References: <32822fe60702201827k36f8bd53k69908869a19f00e6@mail.gmail.com> <20070221082830.31BD26F4CF3@longblack.object-craft.com.au> Message-ID: En Wed, 21 Feb 2007 05:28:30 -0300, Andrew McNamara escribi?: >> Hi I just hit this page in wikipedia BDFL[1] >> and it redirected me to Guido's wikipedia[2] entry >> [1] http://en.wikipedia.org/wiki/BDFL > > I suspect, in this case, the redirect is implicit. It's happening > because the Wikipedia search engine finds no page called BDFL, and the > Guido_van_Rossum is the next closest match. No, both BDFL and Benevolent_Dict... have an explicit redirect to Guido's entry. It used to be quite different in the past, but the topic has been heavily discussed and edited. See http://en.wikipedia.org/wiki/Talk:Benevolent_Dictator_for_Life#Concerned_about_accuracy_-_BDs_versus_BDFLs Guido appears to be the *only* one called BDFL. -- Gabriel Genellina From michele.simionato at gmail.com Wed Feb 21 00:44:53 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 20 Feb 2007 21:44:53 -0800 Subject: How to do a Decorator Here? In-Reply-To: References: Message-ID: <1172036693.751715.70910@k78g2000cwa.googlegroups.com> On Feb 20, 9:20 pm, "Gregory Pi?ero" wrote: > Or is this not what decorators do? I'm trying to avoid subclassing if I can. Your problem, overriding a method, is what inheritance was made for. If you want to know more about decorators, see Dr Mertz's last article http://www-128.ibm.com/developerworks/linux/library/l-cpdecor.html Michele Simionato From ptmcg at austin.rr.com Wed Feb 21 15:27:54 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 Feb 2007 12:27:54 -0800 Subject: PLY for standard library In-Reply-To: <1172062961.384337.295280@j27g2000cwj.googlegroups.com> References: <1172062961.384337.295280@j27g2000cwj.googlegroups.com> Message-ID: <1172089673.964842.7810@v45g2000cwv.googlegroups.com> On Feb 21, 7:02 am, "Jakub Stolarski" wrote: > On 20 Lut, 19:29, "Alan Isaac" wrote:> If not, what module providing substantially similar functionality is? > > AFAIK there's no parser generator module in standard library. > > I would like to see PLY in standard library too. > > -- > Jakub Stolarski Other candidates besides PLY: http://www.nedbatchelder.com/text/python-parsers.html http://wiki.python.org/moin/LanguageParsing I'm not sure this is a "one size fits all" problem space. Personally I find PLY's use of docstrings for grammar definition a bit too clever (as I'm sure others have their own personal likes and dislikes on any of these packages, even (gasp) pyparsing). -- Paul From nszabolcs at gmail.com Sat Feb 3 09:35:15 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 3 Feb 2007 06:35:15 -0800 Subject: Python does not play well with others In-Reply-To: <7xirek9pdt.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> Message-ID: <1170513315.797227.90250@v33g2000cwv.googlegroups.com> Paul Rubin wrote: > "George Sakkis" writes: > > > What does "batteries included" mean to you? To me, it means you don't > > > have to install add-ons. > > > > So let's make a 500MB executable and add Numpy, Zope, Django, PIL, > > pretty much everything actually. Even better, make CheeseShop just a > > frontend to a build system that adds and updates automatically > > submitted packages to the core. Problem solved ! . > > Numpy should certainly be included and I think there are efforts in > that direction. There is also a movement to choose a web framework to > include and Django might be a good choice. I think the Zope > maintainers want to keep Zope separate and I think PIL has an > incompatible license... do not do that (1) i love when i can create a minimalistic system think about it this way: what if you want to run python on an embeded/ low resource system? if you want python to do webhosting the solution is _not_ to include every related package look at eg. debian: you can use it for lowresource system, desktop, scientific computation and for webserver as well because of it's package management system --> you can build a min. system and a huge system as well. (2) seriously, python is a programming language and not a flee market (so don't compare it to java or php) unfortunately lots of ppl working on web related stuff think web is the only reason a programming language should exist, which is pretty stupid i don't want a "webmodule" in a stdlib at all. implementing the standards and recommendations should be enough. web in general is a huge and ugly bloat, keep it away from a language core. (3) having a maintained set of modules for every possible problem is nice, but shouldn't be a part of the core lib. eg. numpy, mysql, ssl, pil, ... are not needed in the stdlib since most of the programming tasks don't need those they should be maintained separately, with an easy way to find and install them. that's what cheese shop and distutils are for. for me batteries included means i get a clean and consistent stdlib and if i need special functionality i can add modules and extensions easily nsz From ryankaskel at gmail.com Wed Feb 28 19:06:08 2007 From: ryankaskel at gmail.com (Ryan K) Date: 28 Feb 2007 16:06:08 -0800 Subject: text wrapping help Message-ID: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> I'm trying to text wrap a string but not using the textwrap module. I have 24x9 "matrix" and the string needs to be text wrapped according to those dimensions. Is there a known algorithm for this? Maybe some kind of regular expression? I'm having difficulty programming the algorithm. Thanks, Ryan From joja15 at gmail.com Wed Feb 14 11:07:02 2007 From: joja15 at gmail.com (joja15 at gmail.com) Date: 14 Feb 2007 08:07:02 -0800 Subject: How to ping and shutdown a remote computer? Message-ID: <1171469222.163242.157040@q2g2000cwa.googlegroups.com> I am working on a Python script to perform as a remote computer manager. So far I have a WOL function working and I would like to add the ability to show if a machine is on or off (I figured I would do so by pinging the machine and seeing if I get a response). I would also like to add the ability to remotely shutdown a computer from the python script. Does anyone have a code snippet for pinging an IP, a code snippet for shutting down a remote Windows XP machine, and a code snippet for sending a HTTP request? Here is my current setup: - PC running python script - FreeNAS (media server running on FreeBSD. Can be shutdown from web interface so I planned on just sending that same web button click from the python script to shutdown the FreeNAS server) - Windows XP machine with folder share (What packet is sent over the network to remotely shutdown a Windows XP machine?) My hope is to have a script then when you start it will list all your remote computers/servers and show if they are currently on/off. Then you can select a server and turn it off if it is on or turn it on if it is off. Thank you in advance for any help provided. - John From aspineux at gmail.com Sat Feb 3 19:01:30 2007 From: aspineux at gmail.com (aspineux) Date: 3 Feb 2007 16:01:30 -0800 Subject: asyncore DoS vulnerability In-Reply-To: <1170430334.170669.215150@q2g2000cwa.googlegroups.com> References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> <1170422700.309941.203320@a34g2000cwb.googlegroups.com> <1170430334.170669.215150@q2g2000cwa.googlegroups.com> Message-ID: <1170547290.641750.191370@s48g2000cws.googlegroups.com> On 2 f?v, 16:32, "billie" wrote: > >> Why does this exception isn't handled inside asyncore.py? > > To do what ? To raise a custom asyncore error ? > > asyncore aims to be a framework, right? > I think that when select() limit is reached asyncore should just drop > other connections. That's all. Nice idea. It shoul be nice to be able to limit the number of connections asyncore can manage, to say, limit the load of the server, or in your case tell asyncore you are working on a poor platform :-) Then asyncore could call a user defined function (a policy) when this limit is reached. This function could interact with asyncore to take an action: reject the connection, close idle connections ..... You could try to persuade asyncore developers to include this feature. > > You can can probably run over this limit by starting multiple of your > > server process (not thread, process). > > Hope you're joking... > Why should I have to run multiple processes / threads to avoid such a > problem? > And what if my system / inteprepter does not support multiple > processes / threads? I was just giving a possible workaround. From bruno.desthuilliers at gmail.com Tue Feb 20 03:54:33 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 20 Feb 2007 00:54:33 -0800 Subject: Bypassing __setattr__ for changing special attributes In-Reply-To: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> Message-ID: <1171961673.334761.147300@q2g2000cwa.googlegroups.com> On 20 f?v, 05:39, "George Sakkis" wrote: > I was kinda surprised that setting __class__ or __dict__ goes through > the __setattr__ mechanism, like a normal attribute: But __class__ and __dict___ *are* 'normal' attributes... From mccredie at gmail.com Tue Feb 27 19:18:19 2007 From: mccredie at gmail.com (Matimus) Date: 27 Feb 2007 16:18:19 -0800 Subject: how to convert an integer to a float? In-Reply-To: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Message-ID: <1172621899.743712.39800@t69g2000cwt.googlegroups.com> On Feb 27, 4:05 pm, "ying... at gmail.com" wrote: > Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, > i1)' always return 0, can you please tell me how can i convert it from > an integer to float? > > def compareValue(n1, n2): > i1 = int(n1) > i2 = int(n2) > > dx = abs(i2 - i1)/min(i2, i1) > print dx > return dx < 0.05 dx = float(abs(i2 -i1))/min(i2, i1) Or you could just put "from __future__ import division" at the top of your file. see http://www.python.org/dev/peps/pep-0238/ for details. -Matt From nospam at riddergarn.dk Tue Feb 13 08:13:26 2007 From: nospam at riddergarn.dk (NOSPAM plz) Date: Tue, 13 Feb 2007 14:13:26 +0100 Subject: Regex highlight html Message-ID: <45D1B976.3080704@riddergarn.dk> Hey, I want to write a function that highlights html code. I have read the wiki page http://en.wikipedia.org/wiki/Regular_expressions just like this: test pic test to this: test pic test Just example colors - not so pretty :) Any suggestions? Andreas From andrewfelch at gmail.com Tue Feb 27 17:02:24 2007 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 27 Feb 2007 14:02:24 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172609437.801573.150900@m58g2000cwm.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> Message-ID: <1172613744.661578.227150@k78g2000cwa.googlegroups.com> On Feb 27, 3:50 pm, "Ziga Seilnacht" wrote: > Andrew Felch wrote: > > Hello all, > > > I'm using the metaclass trick for automatic reloading of class member > > functions, found at:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > > > My problem is that if I > > 1) pickle an object that inherits from "AutoReloader" > > 2) unpickle the object > > 3) modify one of the pickled' object's derived class methods > > 4) reload the module holding the class > > > ... then the changes don't affect the unpickled object. If I unpickle > > the object again, of course the changes take effect. > > > My friend that loves Smalltalk is laughing at me. I thought I had the > > upperhand when I discovered the metaclasses but now I am not sure what > > to do. I really don't want to have to unpickle again, I'm processing > > video and it can take a long time. > > > By the way, I used to avoid all of these problems by never making > > classes, and always building complex structures of lists, > > dictionaries, and tuples with global functions. It's going to take me > > a while to kick those horrible habits (during my transition, I'm > > deriving from list, dict, etc. hehe), perhaps a link to the metaclass > > trick is in order in the tutorial's comments on reload? > > > Any help that avoids having to unpickle again is appreciated! > > > Thanks, > > Andrew Felch > > This happens because unpickling doesn't recreate your object by > calling its type. MetaInstanceTracker registers an instance only > when it is created by calling a class. > > You can solve this by moving the instance registration to > AutoReloader.__new__ and using pickle protocol version 2, but the > best solution is to avoid both pickle (old pickles break if you > change your code) and autoreloading (it's meant to be used in > interactive console and entertaining ircbots, not in normal code). > > Ziga- Hide quoted text - > > - Show quoted text - Thanks Ziga. I use pickle protocol 2 and binary file types with the command: "cPickle.dump(obj, file, 2)" I did your suggestion, i commented out the "__call__" function of MetaInstanceTracker and copied the text to the __new__ function of AutoReloader (code appended). I got a crazy recursive error message (also appended below). In my code, I am creating a new instance, rather than using the pickled object (it needs to work in both modes). Thanks very much for helping me get through this. With my development approach, finding a solution to this problem is really important to me. ... File "C:\Python25\lib\site-packages\tdbu.py", line 67, in __new__ instance = super(MetaInstanceTracker, self).__call__(*args, **kw) File "C:\Python25\lib\site-packages\tdbu.py", line 67, in __new__ instance = super(MetaInstanceTracker, self).__call__(*args, **kw) File "C:\Python25\lib\site-packages\tdbu.py", line 67, in __new__ instance = super(MetaInstanceTracker, self).__call__(*args, **kw) File "C:\Python25\lib\site-packages\tdbu.py", line 67, in __new__ instance = super(MetaInstanceTracker, self).__call__(*args, **kw) File "C:\Python25\lib\site-packages\tdbu.py", line 67, in __new__ instance = super(MetaInstanceTracker, self).__call__(*args, **kw) File "C:\Python25\lib\site-packages\tdbu.py", line 67, in __new__ instance = super(MetaInstanceTracker, self).__call__(*args, **kw) RuntimeError: maximum recursion depth exceeded import weakref, inspect class MetaInstanceTracker(type): def __new__(cls, name, bases, ns): t = super(MetaInstanceTracker, cls).__new__(cls, name, bases, ns) t.__instance_refs__ = [] return t def __instances__(self): instances = [(r, r()) for r in self.__instance_refs__] instances = filter(lambda (x,y): y is not None, instances) self.__instance_refs__ = [r for (r, o) in instances] return [o for (r, o) in instances] ## def __call__(self, *args, **kw): ## instance = super(MetaInstanceTracker, self).__call__(*args, **kw) ## self.__instance_refs__.append(weakref.ref(instance)) ## return instance class InstanceTracker: __metaclass__ = MetaInstanceTracker class MetaAutoReloader(MetaInstanceTracker): def __new__(cls, name, bases, ns): new_class = super(MetaAutoReloader, cls).__new__( cls, name, bases, ns) f = inspect.currentframe().f_back for d in [f.f_locals, f.f_globals]: if d.has_key(name): old_class = d[name] for instance in old_class.__instances__(): instance.change_class(new_class) new_class.__instance_refs__.append( weakref.ref(instance)) # this section only works in 2.3 for subcls in old_class.__subclasses__(): newbases = () for base in subcls.__bases__: if base is old_class: newbases += (new_class,) else: newbases += (base,) subcls.__bases__ = newbases break return new_class class AutoReloader: __metaclass__ = MetaAutoReloader def change_class(self, new_class): self.__class__ = new_class def __new__(self, *args, **kw): instance = super(MetaInstanceTracker, self).__call__(*args, **kw) self.__instance_refs__.append(weakref.ref(instance)) return instance Thanks, Andrew Felch From ziga.seilnacht at gmail.com Tue Feb 27 18:47:40 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 27 Feb 2007 15:47:40 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172619395.282157.187030@a75g2000cwd.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> <1172615426.752353.25610@8g2000cwh.googlegroups.com> <1172616850.962166.27480@k78g2000cwa.googlegroups.com> <1172618605.121435.247300@t69g2000cwt.googlegroups.com> <1172619395.282157.187030@a75g2000cwd.googlegroups.com> Message-ID: <1172620060.412942.212130@a75g2000cwd.googlegroups.com> Andrew Felch wrote: > Thanks for checking. I think I narrowed the problem down to > inheritance. I inherit from list or some other container first: > > class PointList( list, AutoReloader ): > def PrintHi1(self): > print "Hi2" > > class MyPrintingClass( AutoReloader ): > def PrintHi2(self): > print "Hi2v2" > > Automatic reloading works for MyPrintingClass but not for PointList. > Any ideas? > > -Andrew Ah yes, this is the problem of list.__new__ not calling the next class in MRO. Try to switch the bases, so that AutoReloader's __new__ method will be called first. Ziga From bj_666 at gmx.net Fri Feb 9 01:51:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 09 Feb 2007 07:51:02 +0100 Subject: Regexp not performing the same in FTP versus Python References: <1170978596.337428.261110@h3g2000cwc.googlegroups.com> Message-ID: In <1170978596.337428.261110 at h3g2000cwc.googlegroups.com>, IamIan wrote: > Hello all, > > I'm trying to use a regular expression in an FTP script to list > certain files. When run in a standard FTP session the command: > > dir ????????.??[oOdDnNmM]* > > returns 48 files. When I use the following Python script it prints > roughly 12 files (a subset of the 48), ending with 'None': > > [?] > > Is my Python syntax off? Your `re` syntax is off. What you give FTP is a shell or glob pattern, not a regular expression for the `re` module. The `fnmatch` module has a function to translate a glob pattern to a `re` pattern: In [8]: fnmatch.translate('????????.??[oOdDnNmM]*') Out[8]: '........\\...[oOdDnNmM].*$' Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 11:25:58 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Feb 2007 03:25:58 +1100 Subject: Pep 3105: the end of print? References: Message-ID: On Fri, 16 Feb 2007 09:32:56 -0600, Edward K Ream wrote: >> Even in the Python world, nobody expects to run the same code base under > C Python and Jython and IronPython and PyPy. > > Leo now runs under CPython with both wxWidgets and Tkinter. The gui code is > confined to plugins, and a similar gui plugin will suffice to run Leo under > IronPython. Indeed, Leo's startup code already runs unchanged under CPython > and IronPython. I expect minimal changes will be needed to run Leo's core > under Jython. And I *am* talking about a single code base: no translator > needed. Good for Leo. I'm not being sarcastic. But that doesn't just happen, it happens because Leo's developers don't insist on using mutually incompatible CPython and IronPython features or modules, but instead worked really hard to *make* Leo work with both. They didn't just expect IronPython code to work unchanged with CPython (or vice versa). -- Steven. From antroy at gmail.com Fri Feb 9 05:29:53 2007 From: antroy at gmail.com (Ant) Date: 9 Feb 2007 02:29:53 -0800 Subject: Calling J from Python In-Reply-To: <52q04iF1pl3l8U1@mid.individual.net> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> Message-ID: <1171016992.962017.10540@m58g2000cwm.googlegroups.com> On Feb 6, 12:21 am, greg wrote: ... > Yes, but with Python you wouldn't have to spend a > couple of weeks sitting and thinking before starting > to type that line... This is a good point often overlooked. You often get these threads on c.l.python about "How can I do this in one line", usually with some example of how it is done in only 13 characters in Perl. Yes you may spend less time typing - but unless you are a true expert in (J, Perl, other terse language) the time you spend actually working out how to type it, and in debugging it far outweighs the time you'd spend on all of that typing in a clean but more verbose language such as Python. From cniharral at gmail.com Fri Feb 2 07:27:06 2007 From: cniharral at gmail.com (cniharral at gmail.com) Date: 2 Feb 2007 04:27:06 -0800 Subject: How do I print out in the standard output coloured lines In-Reply-To: References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> Message-ID: <1170419225.989358.311600@h3g2000cwc.googlegroups.com> On Feb 2, 1:16 pm, rzed wrote: > cnihar... at gmail.com wrote innews:1170417631.268771.108090 at v45g2000cwv.googlegroups.com: > > > Hi, > > > I'm interested in printing out coloured lines of my > > application and > > I don't know what to use. Can anybody give me an idea?? > > You could speed up the process if you explain what your application > is and what you mean by colored lines. Does your application emit > output to a plotter, an ink-jet printer, or a color laser printer? Is > it a drawing program? An editor in which you want lines colored to > highlight context? It might be useful to know what system you are > running as well. Just a little detail here. > > -- > rzed Well, yes, it's a program that prints out lines to the standard output with a print command, and I want to print them coloured. For example: print "Hello World!!" I want it in red colour. That's all. From laurent.pointal at limsi.fr Tue Feb 20 07:56:03 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 20 Feb 2007 13:56:03 +0100 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: References: Message-ID: joanne matthews (RRes-Roth) a ?crit : > I'm getting different results when I add up a list of floats depending > on the order that I list the floats. For example, the following returns > False: > def check(): > totalProp=0 > inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1] > for each in inputs: > > totalProp+=each > print "totalProp=",totalProp > if totalProp != 1: > print "Your proportions must add up to 1" > > return False > return True > > However, if I swap, the 4th and 5th list items like this: > > totalProp=0 > inputs=[0.2,0.2,0.2,0.2,0.1,0,0.1] > for each in inputs: > > totalProp+=each > print "totalProp=",totalProp > if totalProp != 1: > print "Your proportions must add up to 1" > > return False > return True > > I get True returned. Can anyone tell me whats going Its related to the internal representation of real numbers using a finite number of binary digits - intermediate additions may (here the order is have an impact) produce results which have no representation, and lead to dismiss of an epsilon value. http://en.wikipedia.org/wiki/Floating_point > on and how I can > avoid the problem. Thanks Use an ad-hoc library with numerical types using a different representation (other posters may give examples of libraries they use). From nospam at this.addy.com Sun Feb 25 15:27:52 2007 From: nospam at this.addy.com (*) Date: Sun, 25 Feb 2007 14:27:52 -0600 Subject: Who has not attended these free tutorial courses ? References: <1172257564.241642.300140@m58g2000cwm.googlegroups.com> Message-ID: <01c7591a$b28179c0$4090c3d8@race> Is it true that all the above-listed "tutorials" offer undergraduate credit at Islam University? From usenet200702 at tobyinkster.co.uk Sat Feb 24 06:21:14 2007 From: usenet200702 at tobyinkster.co.uk (Toby A Inkster) Date: Sat, 24 Feb 2007 11:21:14 +0000 Subject: Finding non ascii characters in a set of files References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> Message-ID: bg_ie wrote: > What I'd like to do is scan a directory and list all the > files in it that contain a non ascii character. Not quite sure what your intention is. If you're planning a one-time scan of a directory for non-ASCII characters in files, so that you can manually fix those files up, then this Perl one-liner will do the trick. At the command line, type: perl -ne 'print "$ARGV:$.\n" if /[\x80-\xFF]/;' * This will print out a list of files that contain non-ASCII characters, and the line numbers which those characters appear on. Note this also operates on binary files like images, etc, so you may want to be more specific with the wildcard. e.g.: perl -ne 'print "$ARGV:$.\n" if /[\x80-\xFF]/;' *.py *.txt *.*htm* -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From kylotan at gmail.com Fri Feb 9 15:21:26 2007 From: kylotan at gmail.com (Ben Sizer) Date: 9 Feb 2007 12:21:26 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> Message-ID: <1171052486.043598.239470@p10g2000cwp.googlegroups.com> On Feb 9, 5:53 pm, s... at pobox.com wrote: > Ben> Python extensions written in C require recompilation for each new > Ben> version of Python, due to Python limitations. > > Can you propose a means to eliminate this limitation? By putting an intermediate layer between the extensions and the language. I suppose this is essentially what ctypes does, except from the other direction. If someone could explain the limitation in detail, I expect ways could be found around it. After all, I don't know of any other systems that require you to recompile all the extensions when you upgrade the application. Winamp is one application that comes to mind which has kept plugins working across many upgrades. I doubt they're still compiling with Visual Studio 6. Perhaps it works because they have a more restrictive API that isn't passing non-primitive types across the DLL boundary. -- Ben Sizer From jura.grozni at gmail.com Mon Feb 12 20:54:39 2007 From: jura.grozni at gmail.com (azrael) Date: 12 Feb 2007 17:54:39 -0800 Subject: Testers please In-Reply-To: References: Message-ID: <1171331679.634133.94060@m58g2000cwm.googlegroups.com> I took a first look on the video. Amazing. I love it. You got a tester good job, man // but one thing, why not zope and postgre? martien friedeman je napisao/la: > I have written this tool that allows you to look at runtime data and > code at the same time. > And now I need people to test it. > > The easiest way to see what I mean is to look at some videos: > http://codeinvestigator.googlepages.com/codeinvestigator_videos > > It requires Apache and Sqlite. > > It works for me with a Firefox browser on Linux. From gagsl-py2 at yahoo.com.ar Mon Feb 26 02:12:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 26 Feb 2007 04:12:52 -0300 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> Message-ID: En Sat, 24 Feb 2007 01:42:00 -0300, Martin Manns escribi?: > On Fri, 23 Feb 2007 20:20:12 -0300 > "Gabriel Genellina" wrote: > >> mx.Number.Rational is horribly broken. They break this rule: >> a==b => hash(a)==hash(b) >> so they can'b be used as dictionary keys, by example. > > I would be interested, under which circumstances the rule is broken. > In my (few) tests, hash(a)==hash(b) worked. I can't reproduce this issue with the latest mx experimental package, it appears to be fixed now. Also, I'm currently using Python 2.5 and it was 2.3 by that time. -- Gabriel Genellina From Bulkan at gmail.com Tue Feb 20 23:47:57 2007 From: Bulkan at gmail.com (placid) Date: 20 Feb 2007 20:47:57 -0800 Subject: getting a thread out of sleep In-Reply-To: References: Message-ID: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> On Feb 21, 3:08 pm, mark wrote: > Right now I have a thread that sleeps for sometime and check if an > event has happened and go back to sleep. Now instead I want the thread > to sleep until the event has occured process the event and go back to > sleep. How to do this? > thanks > mark > > class eventhndler(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > > def run(self): > while True: > time.sleep(SLEEPTIME) > ''''do event stuff''' The way i would do this is by using an threading.Event ( http://docs.python.org/lib/event-objects.html ) class eventhandler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.event = threading.Event() def run: while True: # block until some event happens self.event.wait() """ do stuff here """ self.event.clear() the way to use this is to get the main/separate thread to set() the event object. Cheers From gagsl-py at yahoo.com.ar Mon Feb 12 14:29:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 16:29:37 -0300 Subject: favourite editor References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> <45D08DAB.6080908@websafe.com> <1171307483.481407.167480@a75g2000cwd.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 16:11:23 -0300, azrael escribi?: > I expirienced some big craches. tra running some aplication vith using > Vpython. when you close the vpython window, pyscripter also crashes. > sometimes im writing some code and suddenly get about 300 error > messages without running anything. I like pyscripter, but sometimes it > drives me crazy But why blame PyScripter when it might be a problem in VPython as well? -- Gabriel Genellina From jcrocholl at googlemail.com Tue Feb 6 04:37:53 2007 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 6 Feb 2007 01:37:53 -0800 Subject: Taint (like in Perl) as a Python module: taint.py In-Reply-To: References: <1170713584.199237.22210@v33g2000cwv.googlegroups.com> Message-ID: <1170754673.707050.13110@p10g2000cwp.googlegroups.com> On Feb 6, 3:01 am, Ben Finney wrote: > "Gabriel Genellina" writes: > > And tainted() returns False by default????? > > Sorry but in general, this won't work :( > > I'm inclined to agree that the default should be to flag an object as > tainted unless known otherwise. That's true. For example, my first attempt didn't prevent this: os.open(buffer('/etc/passwd'), os.O_RDONLY) Here's a stricter version: def tainted(param): """ Check if a parameter is tainted. If it's a sequence or dict, all values will be checked (but not the keys). """ if isinstance(param, unicode): return not isinstance(param, SafeString) elif isinstance(param, (bool, int, long, float, complex, file)): return False elif isinstance(param, (tuple, list)): for element in param: if tainted(element): return True elif isinstance(param, dict): return tainted(param.values()) else: return True From n.emami at gmail.com Wed Feb 28 09:07:10 2007 From: n.emami at gmail.com (Nader) Date: 28 Feb 2007 06:07:10 -0800 Subject: installing "pysqlite" In-Reply-To: <1172663495.011225.76410@v33g2000cwv.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> <1172663495.011225.76410@v33g2000cwv.googlegroups.com> Message-ID: <1172671630.741991.198700@t69g2000cwt.googlegroups.com> On Feb 28, 12:51 pm, "Paul Boddie" wrote: > On 28 Feb, 12:07, Nader Emami wrote: > > > > > I am back with another problem. I suppose that I can tell it! > > I have installed both, 'sqlite' and 'pysqlite' without any problem. But > > If I try to test whether the 'pysqlite' interface works, I get the next > > error message: > > [...] > > > /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so: > > undefined symbol: sqlite3_set_authorizer > > > I don't understand it. Could you tell me how I can solve this last > > point? I hope so! > > It looks like Python (although it's really the dynamic linker) can't > locate the SQLite libraries. If you have installed SQLite into a non- > standard place, which I'm guessing is the case, then you will need to > set your LD_LIBRARY_PATH environment variable to refer to the > directory where the libraries were installed. > > So, if you installed SQLite into /usr/people/emami and you see files > like libsqlite3.so in /usr/people/emami/lib, then you need to change > your LD_LIBRARY_PATH as follows: > > export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib > > (The actual directory should be the same as the one you specified for > library_dirs in the setup.cfg file for pysqlite.) > > If you're not using bash as your shell, the syntax for the command may > be different. Don't forget to add this command to your shell > configuration file (eg. .bashrc) so that your system remembers this > information. > > Paul I see now your respond to my problem, but i can check it tomorrow because I don't have at this moment on this machine. However thank for the reaction and I will tell about it after assiging the new lib to its PATH. Nader From devicerandom at gmail.com Tue Feb 13 11:02:24 2007 From: devicerandom at gmail.com (massimo s.) Date: 13 Feb 2007 08:02:24 -0800 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171360113.585827.17440@v45g2000cwv.googlegroups.com> Message-ID: <1171382544.431125.299020@v45g2000cwv.googlegroups.com> On 13 Feb, 12:46, Peter Otten <__pete... at web.de> wrote: > Well, what problems ocurring with > > class A: pass > class B: pass > class C(A, B): pass > > could be avoided by writing > > class A: pass > class B(A): pass > class C(B): pass > > instead? Classes have to be designed for subclassing, so essentially you get > two interfaces, one for subclasses and one for client code instead of just > the latter. A more relevant mantra governing inheritance is "Flat is better > than nested". I am truly getting lost. Are you saying that doing A-->B(A)--C(B) is better than C(A,B)? And isn't the former thing nested? Or are you saying that C(A,B) is better than A,B(A),C(B)? And in both cases:why? And why "classes have to be designed for subclassing"? I often do classes that are not thought to be subclassed. > If you use attributes starting with two underscores inside a method, Python > transparently prepends them with the class name. This allows to you to use > the same variable name in two base classes and reduces coupling: Wow, I didn't know it. Thanks a lot. > But if two classes with the same name use the "private" variable, the > mechanism fails: Of course.I'll remember it. m. From Shawn at Milochik.com Thu Feb 8 11:39:42 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Thu, 8 Feb 2007 11:39:42 -0500 Subject: Strings in Python In-Reply-To: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> References: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> Message-ID: <2dc0c81b0702080839y332b9cbcp96951f9b47a4c56a@mail.gmail.com> On 8 Feb 2007 08:28:25 -0800, Johny wrote: > Playing a little more with strings, I found out that string.find > function provides the position of > the first occurance of the substring in the string. > Is there a way how to find out all substring's position ? > To explain more, > let's suppose > > mystring='12341' > import string > > >>> string.find(mystring ,'1') > 0 > > But I need to find the possition the other '1' in mystring too. > Is it possible? > Or must I use regex? > Thanks for help > L > > -- > http://mail.python.org/mailman/listinfo/python-list > Loop it -- once you know the index of the first character, add the third argument to string.find(), which tells it the position at which to start (the last find + 1). From thinker at branda.to Tue Feb 27 13:32:09 2007 From: thinker at branda.to (Thinker) Date: Wed, 28 Feb 2007 02:32:09 +0800 Subject: spawnl and waitpid In-Reply-To: <1172600050.794986.47140@m58g2000cwm.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> <1172600050.794986.47140@m58g2000cwm.googlegroups.com> Message-ID: <45E47929.8080703@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 naima.mans at gmail.com wrote: > On 27 f?, 18:54, Thinker wrote: > hello > ha ok... > i tried this one and the browser don't write the message at once... > I have alos tried with thread and have the same result... :( Does child-process terminate it-self in a very short time ? It can be a race condition, here. You can try to sleep for a while in child-process to make sure parent being executed. Parent process may not schedule to run immediately after spawn. And, you can print some thing before os.spawnl() to make sure that message can be delivered successfully. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF5Hkp1LDUVnWfY8gRAtDdAKCKy8/ap5VJvZV14nhSCWYfLZdyYACffJ+Y 0sHMgyaQBmsOMwq/rxEvm1Q= =qjTU -----END PGP SIGNATURE----- From cniharral at gmail.com Fri Feb 2 08:20:19 2007 From: cniharral at gmail.com (cniharral at gmail.com) Date: 2 Feb 2007 05:20:19 -0800 Subject: How do I print out in the standard output coloured lines In-Reply-To: References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> <1170419225.989358.311600@h3g2000cwc.googlegroups.com> Message-ID: <1170422415.477885.175980@q2g2000cwa.googlegroups.com> On Feb 2, 2:08 pm, Bart Van Loon wrote: > It was 2 Feb 2007 04:27:06 -0800, when cnihar... at gmail.com wrote: > > > print "Hello World!!" > > > I want it in red colour. > > > That's all. > > Use colour escape codes: > > print "\033[1;31mHello World\033[0m" > > That's all. :-) > > -- > groetjes, > BBBart > > Golly, I'd hate to have a kid like me! > -- Calvin Well, this is fine. It's what I was looking for. I have done something similar with a system command execution (echo) but it was not really smart, but this fit my needs. Thanks a lot. Regards. Carlos Niharra L?pez From greg at cosc.canterbury.ac.nz Mon Feb 5 04:53:45 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 05 Feb 2007 22:53:45 +1300 Subject: Decimating Excel files In-Reply-To: <1170585737.044166.155920@v45g2000cwv.googlegroups.com> References: <52kn9eF1odticU1@mid.individual.net> <1170585737.044166.155920@v45g2000cwv.googlegroups.com> Message-ID: <52od99F1p5s4vU1@mid.individual.net> Arnd wrote: > Good observation, but as we have numbers of type Cardinalia, > Ordinalia, Distributiva & Multiplicativa in Latin I would prefer > secundating or secondating. (Bisimating or bicimating would multiply > the lines by a factor 2) Interesting. But does this mean that "duplicating" is actually from the wrong root? And also we have "bifurcation", which means splitting in two rather than multiplication by two -- or does that come down to the same thing? -- Greg From vinay_sajip at yahoo.co.uk Fri Feb 23 06:15:29 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 23 Feb 2007 03:15:29 -0800 Subject: TimedRotatingFileHandler() isn't rotating at midnight? In-Reply-To: References: <1171021836.812953.183150@m58g2000cwm.googlegroups.com> <86tzxvwhjn.fsf@Bacalao.shenton.org> Message-ID: <1172229329.497528.306810@v33g2000cwv.googlegroups.com> On 9 Feb, 14:14, s... at pobox.com wrote: > Right. Check out the logrotate facility on your system. This can be used together with the WatchedFileHandler recently checked into SVN trunk - this (Unix/Linux-only) handler checks to see if the dev or inode have changed, and if they have (because of rotation by e.g. logrotate), reopens the file before writing to it. Regards, Vinay Sajip From sickcodemonkey at gmail.com Mon Feb 26 16:42:14 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Mon, 26 Feb 2007 16:42:14 -0500 Subject: Walk thru each subdirectory from a top directory In-Reply-To: <1172525300.450438.57080@8g2000cwh.googlegroups.com> References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> Message-ID: <2adc542f0702261342r7f3a8ff8gffc6e30356c792de@mail.gmail.com> I had a do something similar. I had to get a program to traverse through a directory and delete all files with a specific file extension. (The program below will delete files, so I do not recommend you running it without paying close attention to it.) This program will start at a given directory and will traverse thru the subdirectories by using "listdir". +++++++++++++++++++++++++++++++++++ #!/usr/bin/python -u import sys, time from os import listdir, unlink from os.path import isdir, isfile, islink, join, getmtime deldir = "C:\some\Dir" delFileType = ".txt" # ------------------------------------- def del_entry(_name): try: if isdir(_name): print "This is a directory, do nothing." else: #print "now" unlink(_name) # or remove(_name) sys.stdout.write("Delete FILE %s\n" % (_name)) except IOError: sys.stderr.write("Cannot delete %s\n" % (_name)) # ------------------------------------- def list_dir(_dir,_action): if not isdir(_dir): print "%s is not a directory" % (_dir) return for file in listdir(_dir): path = join(_dir, file) if isdir(path): list_dir(path, _action) else: if path.rfind(delFileType) != -1: #print path _action(path) # ------------------------------------- # Run it list_dir(deldir, del_entry) On 26 Feb 2007 13:28:20 -0800, silverburgh.meryl at gmail.com < silverburgh.meryl at gmail.com> wrote: > > > i am trying to use python to walk thru each subdirectory from a top > directory. Here is my script: > > savedPagesDirectory = "/home/meryl/saved_pages/data" > > dir=open(savedPagesDirectory, 'r') > > for file in dir: > if (isdir(file)): > # get the full path of the file > fileName = savedPagesDirectory + file + 'index.html' > print fileName > > $ ./scripts/regressionTest.py > Traceback (most recent call last): > File "./scripts/regressionTest.py", line 12, in ? > dir=open(savedPagesDirectory, 'r') > IOError: [Errno 21] Is a directory > > But I get the above error: > > Can you please tell me what did I do wrong? > > Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sickcodemonkey at gmail.com Tue Feb 27 09:45:35 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 27 Feb 2007 09:45:35 -0500 Subject: os.system and quoted strings In-Reply-To: <1172586281.606903.79990@s48g2000cws.googlegroups.com> References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> Message-ID: <2adc542f0702270645x7cd06104j203a6783f77b3f92@mail.gmail.com> Do you mean: >>> import time, os >>> dir = "C:\\Documents and Settings\\somepath\\" >>> fileName = time.strftime("%d%m%Y") >>> finalname = "%s%s.txt" % (dir,fileName) >>> print finalname C:\Documents and Settings\somepath\27022007.txt On 27 Feb 2007 06:24:41 -0800, svata wrote: > > Hello, > > as I'm new to python I've stumbled accros os.system and its not very > well documented usage. > > I use Win XP Pro and Python 2.5. > > Here is the code snippet: > > > -------------------------------------------------------------------------------------------------- > > import time > import os > > dir = "C:\\Documents and Settings\\somepath\\" > fileName = time.strftime("%d%m%Y") > os.system('gvim dir+fileName+".txt"') > > > --------------------------------------------------------------------------------------------------- > > The problem is that concatenated variable dir+fileName doesn't get > expanded as expected. > > Is there anything I omitted? > > svata > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerald.kaszuba at gmail.com Wed Feb 21 00:45:43 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 20 Feb 2007 21:45:43 -0800 Subject: ANN: pyraknet 0.1.4 Message-ID: <1172036743.134486.136300@p10g2000cwp.googlegroups.com> I just released a new version of pyraknet - a UDP game network library. http://pyraknet.slowchop.com/ The changes are: * Changed license to LGPL * Mac OS X binaries for Python 2.4 (thanks to Simon Howe for testing) * Added Peer.is_active(...) * Added Peer.get_max_connections(...) * setup.py will tell you what's wrong when you don't have Pyrex installed Gerald From aboudouvas at panafonet.gr Thu Feb 8 06:00:39 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 8 Feb 2007 03:00:39 -0800 Subject: Object type check In-Reply-To: References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> Message-ID: <1170932439.393593.200090@h3g2000cwc.googlegroups.com> > def modify(list_of_x): > for x in list_of_x: > try: > x.change_in_place # don't call the method, just check it exists XXmmmm...what exactly is going on here ? I mean, what is actually happens if you omit the parenethesis as you just did ? I understand that it does not call the method, but what is really doing ?? From steveo at syslang.net Fri Feb 23 11:12:20 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 23 Feb 2007 11:12:20 -0500 (EST) Subject: Question about idiomatic use of _ and private stuff. Message-ID: I understand that two leading underscores in a class attribute make the attribute private. But I often see things that are coded up with one underscore. Unless I'm missing something, there's a idiom going on here. Why do people sometimes use one leading underscore? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From irmen.NOSPAM at xs4all.nl Mon Feb 12 16:40:12 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 12 Feb 2007 22:40:12 +0100 Subject: How to Speed Up Internet Searches?? In-Reply-To: References: <1171129634.795533.325560@k78g2000cwa.googlegroups.com> Message-ID: <45d0dee7$0$327$e4fe514c@news.xs4all.nl> Patrick Klos wrote: > In article <1171129634.795533.325560 at k78g2000cwa.googlegroups.com>, > wrote: >> How to Speed Up Internet Searches?? >> When you go to a web site, the first thing that happens is that......... >> and for networking tips see at >> : : : > > Please don't post this kind of stuff here any more. It's off topic and > unappreciated! > Not to mention so ugly and extremely outdated that I had to read the page twice to see what it was about. It actually contains Hayes modem commands. (sorry, I went there out of curiousity...) -Irmen From gagsl-py at yahoo.com.ar Fri Feb 2 11:33:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 2 Feb 2007 13:33:19 -0300 Subject: coping directories References: Message-ID: "Gigs_" escribi? en el mensaje news:epve95$ksd$1 at ss408.t-com.hr... Gabriel Genellina wrote: > En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ escribi?: > >> class CVisitor(FileVisitor): >> def __init__(self, fromdir, todir): >> self.fromdirLen = len(fromdir) + 1 # here is my problem >> self.todir = todir >> FileVisitor.__init__(self, fromdir) >> def visitdir(self, dirpath): >> topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) >> os.mkdir(topath) >> def visitfile(self, filepath): >> topath = os.path.join(self.todir, filepath[self.fromdirLen:]) >> cpfile(filepath, topath) #copy contents from filepath to >> topath[/code] >> >> >> When I copy contents from C:\IronPython to C:\temp >> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this >> self.fromdirLen = len(fromdir) + 1 >> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen >> = len(fromdir) i get contents copied to C:\ (actually to parent dir) > > Instead of actually doing os.mkdir and cpfile, use a print statement to > output the involved variables, and try with and without +1. You'll see > yourself what happens. > > well I have tried with print but can't figure out > I got this when I have removed + 1 > >>> C = CpallVisitor('C:\\New', 'c:\\temp') > >>> C.run(startdir='C:\\New') > c:\temp\ > filepath: C:\New\AUTOEXEC.BAT Topath: \AUTOEXEC.BAT > filepath: C:\New\boot.ini Topath: \boot.ini > filepath: C:\New\CONFIG.SYS Topath: \CONFIG.SYS So it's clear that you need the +1 for the program to work properly, ok? > In python shell I got same thing, no matter fromdirLen is > len(fromdir) + 1 or len(fromdir) > >>> fromdir = 'C:\\New' > >>> fromdirLen = len(fromdir) > >>> todir = 'C:\\temp' > >>> topath = os.path.join(todir, fromdir[fromdirLen:]) > >>> topath > 'C:\\temp\\' This is *not* what your program does; the original code above has another variable, filepath. > Please help I assume that you're doing this as some kind of learning exercise - else there are other simpler ways. And you want to know why do you need that +1. Because it's clear that using +1 is the right answer, ok? You'll have to understand it yourself. Try running the program step by step. Hints: - compare os.path.join("c:\\temp", "AUTOEXEC.BAT") with os.path.join("c:\\temp", "\\AUTOEXEC.BAT") with os.path.join("c:\\temp\\", "AUTOEXEC.BAT") with os.path.join("c:\\temp\\", "\\AUTOEXEC.BAT") - remember that len("\\") == 1 - compare c:\temp c:\temp\AUTOEXEC.BAT and see where the filename part begins and what your program is doing with this. -- http://mail.python.org/mailman/listinfo/python-list From ajdeshpande at gmail.com Thu Feb 1 11:26:20 2007 From: ajdeshpande at gmail.com (Analog Kid) Date: Thu, 1 Feb 2007 21:56:20 +0530 Subject: Python module for the IPod shuffle ... In-Reply-To: <8c7f10c60702010400v22ff980ey9ec05c92b5829214@mail.gmail.com> References: <4ccf86300701310900g2b642847s5d0dab31857f42a6@mail.gmail.com> <8c7f10c60702010400v22ff980ey9ec05c92b5829214@mail.gmail.com> Message-ID: <4ccf86300702010826n70ae9b59q9ee20557b1cca2ac@mail.gmail.com> hi simon: thanks a lot for that resource ... i downloaded it and tried to use it ... but when i try to import pypod, i get an error, which is as follows... ImportError: No module named _gpod I guess I have to do something more than merely putting the two files ( pypod.py and gpod.py) in my site-packages. what am i missing? thanks for your help. -ajay On 2/1/07, Simon Brunning wrote: > > On 1/31/07, Analog Kid wrote: > > Hi all: > > Im looking for a python module thatll let me do simple reads/writes from > and > > to an iPod shuffle similar to iTunes ... I read about the gPod module > ... > > but Im not sure whether it will work in Windows ... > > This any good? > > > > -- > Cheers, > Simon B > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- BBQ - "Spare (My) Ribs" being contemplated -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sun Feb 4 16:26:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Feb 2007 22:26:28 +0100 Subject: raise or not to raise [Newbie] In-Reply-To: References: Message-ID: <45c64875$0$5159$426a34cc@news.free.fr> Jacol a ?crit : > I understand that author generated exception and than extracted the name of > function from the exeption. But is any sens in using exeptions service if > we have smthing simpler: just print for example? In my opinion no, it > doesn't make sens. You're of course right. Exceptions are mainly a way of handling 'exceptional' conditions without cluttering the source code with error code checking. The canonical use case is: try: some_call_that_may_raise(args) except SomeException, e: try_to_solve_the_problem() The nice thing with exceptions (compared to 'manual' error handling) is that you can choose where you want to handle the problem without having to pass back error code/error message all along the call stack... From deets at nospam.web.de Fri Feb 23 08:08:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Feb 2007 14:08:06 +0100 Subject: Module trouble [newbie] References: <54830uF1ukj2kU1@mid.uni-berlin.de> Message-ID: <54879mF1ukp6jU2@mid.uni-berlin.de> Boris Ozegovic wrote: > Diez B. Roggisch wrote: > >> Are you sure the above is what you really used for your test? Because >> your output features a single 100, which the above lacks a >> print-statement for. > > Yeah, I cancelled the message, but synchronization allready happened. :) > > Problem was in some other place. > > One more question: is calling import inside function definition poor > design? e.g. > > def foo(): > doSomething: > import someModule > someModule.doSomethin I use it sometimes myself, to avoid otherwise circular imports. However, I don't like it very much. Try to go without it I'd say, but that is just a gut-feeling. Diez From gagsl-py at yahoo.com.ar Tue Feb 6 12:08:33 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 6 Feb 2007 14:08:33 -0300 Subject: How can I use __setitem__ method of dict object? References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> Message-ID: "jeremito" escribi? en el mensaje news:1170775388.533078.115330 at k78g2000cwa.googlegroups.com... > Please excuse me if this is obvious to others, but I can't figure it > out. I am subclassing dict, but want to prevent direct changing of > some key/value pairs. For this I thought I should override the > __setitem__ method as such: > if key == 'xT': > raise AttributeError("""Can't change xT. Please change, > xF, xS, or xG""") Why using a dictionary? I'd use a simple class with properties: py> class Xs(object): # class names should be Uppercase ... def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): ... self.xS = xS ... self.xF = xF ... self.nu = nu ... self.xG = xG ... xA = property(fget=lambda self: self.xG + self.xF) ... xT = property(fget=lambda self: self.xA + self.xS) ... py> xs = Xs(1.0, 0.95, 0.80, 0.70) py> print xs.xG 0.8 py> print xs.xA 1.75 py> print xs.xT 2.75 py> xs.xG = 0.5 py> print xs.xA 1.45 py> print xs.xT 2.45 py> xs.xA = 1.5 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute py> xs.xT = 1.2 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute py> -- Gabriel Genellina From baur79 at gmail.com Fri Feb 2 08:17:43 2007 From: baur79 at gmail.com (baur79) Date: 2 Feb 2007 05:17:43 -0800 Subject: mysqldb duplicate entry error handling In-Reply-To: References: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> <13Awh.21950$X72.6049@newsread3.news.pas.earthlink.net> Message-ID: <1170422263.342857.108470@h3g2000cwc.googlegroups.com> thanks John this solves my problem except MySQLdb.IntegrityError, message: thanks everybody again Baurzhan Zhakashev Kazakhstan / Shymkent city From rstupplebeen at gmail.com Mon Feb 26 08:50:24 2007 From: rstupplebeen at gmail.com (rstupplebeen at gmail.com) Date: 26 Feb 2007 05:50:24 -0800 Subject: a=b change b a==b true?? Message-ID: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> I do not have a clue what is happening in the code below. >>> a=[[2,4],[9,3]] >>> b=a >>> [map(list.sort,b)] [[None, None]] >>> b [[2, 4], [3, 9]] >>> a [[2, 4], [3, 9]] I want to make a copy of matrix a and then make changes to the matrices separately. I assume that I am missing a fundamental concept. Any help would be appreciated. Rob Stupplebeen From david at boddie.org.uk Wed Feb 28 19:08:19 2007 From: david at boddie.org.uk (David Boddie) Date: Thu, 01 Mar 2007 01:08:19 +0100 Subject: How do I Color a QTableView row in PyQt4 References: <1172685355.820708.149990@q2g2000cwa.googlegroups.com> Message-ID: <29fbf$45e61974$54d1d767$18593@news.chello.no> On Wednesday 28 February 2007 18:55, Mel wrote: > I am currently porting an SQL centered Visual Basic application to run > on Linux, Python, and Qt4. Currently I am stumped on changing row > colors in the QTableView widget. My test code is based on code from > the PyQt4 examples and looks like this: > > *** Start Code *** > > import sys > from PyQt4 import QtCore, QtGui, QtSql > > import connection > > > class CustomSqlModel(QtSql.QSqlQueryModel): > def data(self, index, role): > value = QtSql.QSqlQueryModel.data(self, index, role) > if value.isValid() and role == QtCore.Qt.DisplayRole: > if index.column() == 0: > return QtCore.QVariant(value.toString().prepend("#")) > elif index.column() == 2: > return QtCore.QVariant(value.toString().toUpper()) > if role == QtCore.Qt.TextColorRole and index.column() == 1: > return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue)) > return value [Snipping the rest of the code to keep this post short.] > Column 18 in the table shows a number from 1 to 3. I would like to > change the color of the row based on the value in column 18 but I have > not been able to find any resources that show me how. Can anyone lend > a hand? It's interesting to see that you subclassed QSqlQueryModel instead of using a custom delegate to display the data. It's usually recommended that you subclass QItemDelegate if you want to customize the way items are represented, but you can also customize the model if you want. What you can do is to check to see if the requested role is the Qt.BackgroundRole and, if so, query the base class for the data in column 18 in the same row. Then you can supply a different colour (as a brush, actually) depending on the value you obtained. if role == QtCore.Qt.BackgroundRole: # Get the data from column 18. column18_data = index.sibling(index.row(), 18).data() # The data is stored in a QVariant, so we unpack it. integer_value = column18_data.toInt()[0] # just the value # Look up the associated color in a dictionary which you # have already defined, and return it. color = self.colors.get(integer_value, self.default_color) return QtCore.QVariant(QtGui.QBrush(color)) You might also find the following pages useful: http://www.riverbankcomputing.com/Docs/PyQt4/html/qt.html#ItemDataRole-enum http://doc.trolltech.com/4.2/model-view-model.html Good luck! David From paddy3118 at netscape.net Fri Feb 2 09:50:42 2007 From: paddy3118 at netscape.net (Paddy) Date: 2 Feb 2007 06:50:42 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170427170.621243.160150@s48g2000cws.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> <1170427170.621243.160150@s48g2000cws.googlegroups.com> Message-ID: <1170427842.718814.94720@q2g2000cwa.googlegroups.com> On Feb 2, 2:39 pm, "Paddy" wrote: > On Feb 2, 1:55 pm, "ardief" wrote: > > > > > Hi everyone > > Here is my problem: > > I have a list that looks like this - > > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > > and I would like to end up with something like this, i.e. with the > > only one list per letter: > > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > > ['e', ['11', '5', '16', '7']]] > > > I have the feeling it's trivial, and I've scoured the group archives - > > sets might be a possibility, but I'm not sure how to operate on a list > > of lists with sets. > > > This function also gives me what I want, more or less, but I don't > > know how to make it run until it's covered all the possibilities, if > > that makes sense... > > > def sigh(list): > > for a in list: > > i = list.index(a) > > if a != list[-1]: ##if a is not the last one, i.e. there is a > > next one > > n = alist[i+1] > > if a[0] == n[0]: > > a.append(n[1:]) > > del alist[i+1] > > > Sorry about the lengthy message and thanks for your suggestions - I'm > > trying to learn... > > : python > Python 2.5 (r25:51908, Nov 28 2006, 16:10:01) > [GCC 3.4.3 (TWW)] on sunos5 > Type "help", "copyright", "credits" or "license" for more information.>>> from pprint import pprint as pp > >>> from collections import defaultdict > >>> data = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > >>> d = defaultdict(list) > >>> _ = [d[x0].append(x1) for x0,x1 in data] > >>> pp(d) > > defaultdict(, {'a': ['13', '3'], 'c': ['12', '15', '4'], > 'b': ['6'], 'e': ['11', '5', '16', '7'], 'd': ['2']})>>> pp(sorted(d.items())) > > [('a', ['13', '3']), > ('b', ['6']), > ('c', ['12', '15', '4']), > ('d', ['2']), > ('e', ['11', '5', '16', '7'])] > > > > - Paddy Use defaultdict(set) and d[x0].add(x1) if you also want to remove duplicates. - Paddy. From jeff.templon at gmail.com Wed Feb 21 02:40:26 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 23:40:26 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> Message-ID: <1172043626.705209.14870@v45g2000cwv.googlegroups.com> On Feb 21, 1:41 am, "BJ?rn Lindqvist" wrote: [ citing me ] > "if 2.4 code doesn't run on 3.0, it's rather likely that strong > pressure will be applied to port *away* from Python into something > less capricious." > > Who are these people that are applying the strong pressure? How can > you run a international and seemingly very important project without > knowing basic things about how to handle versioning problems? This isn't versioning. At least not the way I see it. Versioning has to do with changes in your own product. Indeed one needs to know how to handle it. Lately our project has been doing OK on this front, a couple years ago was a different story. Underlying technology is a different story. This should be reasonably stable. Small changes are inevitable but even these are a major pain, since we have dependency links like the following: OS release links to Python release which changes an Third-party extension module which requires A third party library whose Version needs to be upgraded but which Is used by some other non-python means that Requires the earlier version. Or the earlier problem, an OS upgrade comes with a new python version on which existing code breaks. The fraction of code in our system that's written in python is something like 10% -- it's not a big pure-python system. Now you're talking about major changes in the underlying technology, forcing, at some point in the future, an extensive rewrite of the python code. Yes, at that point, some people would make the comment that a language which changes to that extent by major versions is not fit for production work, and if one was going to have to rewrite, it would be better to rewrite in a more stable language. And finally, remember the original post I replied to said that python 3.0 was determined not to be hampered by backwards compatibility. This is quite a bit different than what you say here ("MIGHT cause problems"): > language than to continue using Python 2.x because Python 3.x, when it > is released, MIGHT cause them some problems several YEARS from now? If backwards compatibility is not a consideration, then it would be a miracle if there were no problems. JT From cheekymonkey4_u at yahoo.com Tue Feb 13 20:23:06 2007 From: cheekymonkey4_u at yahoo.com (Agent X) Date: Wed, 14 Feb 2007 01:23:06 GMT Subject: FedEx UN Travel Destinations Message-ID: <_vtAh.971513$5R2.627669@pd7urf3no> UN Spons.ored Southern Vacation Packages http://vacationdestiny.blogspot.com/ @------ d From supervau at gmail.com Fri Feb 16 01:23:27 2007 From: supervau at gmail.com (Frank) Date: 15 Feb 2007 22:23:27 -0800 Subject: numpy, numarray, or numeric? In-Reply-To: References: Message-ID: <1171607007.184589.78670@v33g2000cwv.googlegroups.com> On Feb 15, 4:40 pm, "Christian Convey" wrote: > I need to bang out an image processing library (it's schoolwork, so I > can't just use an existing one). But I see three libraries competing > for my love: numpy, numarray, and numeric. > > Can anyone recommend which one I should use? If one is considered the > officially blessed one going forward, that would be my ideal. > > Thanks, > Christian Hi, yeah numpy is the newest one. It has only one drawback, there is no comprehensive documentation available that would be free but of course you could buy one. numpy is very similar to the other two packages but not identical that means one has always some troulbe finding out how things work. For example, in numarray you can calculate the eigenvectors of a matrix with eigenvectors(A), in numpy it is eig(A). This looks similar, but the difference is that in numarray the eigenvectors are returned as rows and in numpy as columns. If someone knows of a free manual, let me know. Frank From silverfrequent at gmail.com Thu Feb 1 21:08:22 2007 From: silverfrequent at gmail.com (Silver Rock) Date: Fri, 2 Feb 2007 00:08:22 -0200 Subject: OSS and ALSA Message-ID: Hi all, I've seen that python comes by default with a module for communication with OSS. I've looked for a ALSA module too (pyalsa) but it seems to handle only limited operations. Can anyone confirm or point wrong the impression that a newbie should use the ossaudiodev module? thanks, cl -------------- next part -------------- An HTML attachment was scrubbed... URL: From hg at nospam.org Mon Feb 5 06:17:48 2007 From: hg at nospam.org (hg) Date: Mon, 05 Feb 2007 12:17:48 +0100 Subject: Python compiled on Windows References: Message-ID: Duncan Booth wrote: > Franz Steinhaeusler wrote: > >> Hello, I'm only curious. >> >> Why is Python and most extension (also wxPython) not built using an >> open source compiler like gcc or g++ on Windows? >> >> I'm always wondering, why Microsoft is still supported >> in that way, using VC++ 7.1, if I'm not wrong. >> >> Ok, maybe the compiled assembler code could be better, but >> this cannot be the reason, or? >> >> It would be wonderful (from the principle) if this could be possible. >> From the standpoint of open source. >> >> What are your opinions? > > Practicality beats purity. > > To maximise the interoperability of Python with other software on the > platform it makes sense to use the best supported compiler environment for > the platform. Still, if one considers the many threads of people trying to get it to work with the "free" version + other people that had to invest in VS mostly for that (I did) / it might eventually be fair to reconsider. + a dll is a dll hg From *firstname*nlsnews at georgea*lastname*.com Sat Feb 24 18:13:14 2007 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Sat, 24 Feb 2007 23:13:14 GMT Subject: newbie needs help building Python 2.5 for Fedora Core 6 References: <1172355934.549788.59820@a75g2000cwd.googlegroups.com> Message-ID: <*firstname*nlsnews-02C6F9.18133624022007@news.verizon.net> In article <1172355934.549788.59820 at a75g2000cwd.googlegroups.com>, "bobmon" wrote: > Hello, and please be gentle... > > I'm trying to build Python 2.5 on my Fedora Core 6 installation. I > think I've resolved most of my problems, but "make test" reports an > error for test_socket.py, shown below. > > I suppose my FC6 installation is missing something, but I have no idea > what. Any ideas, directions, pointers would be most appreciated. > > > > ====================================================================== > ERROR: testSockName (__main__.GeneralModuleTests) > > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "./Lib/test/test_socket.py", line 456, in testSockName > my_ip_addr = socket.gethostbyname(socket.gethostname()) > gaierror: (-2, 'Name or service not known') > > > ---------------------------------------------------------------------- > Ran 66 tests in 35.478s > > FAILED (errors=1) > Traceback (most recent call last): > File "./Lib/test/test_socket.py", line 962, in > test_main() > File "./Lib/test/test_socket.py", line 958, in test_main > test_support.run_unittest(*tests) > File "/home/Installer/Python/Python-2.5/Lib/test/test_support.py", > line 441, in run_uni > ttest > run_suite(suite, testclass) > File "/home/Installer/Python/Python-2.5/Lib/test/test_support.py", > line 426, in run_sui > te > raise TestFailed(err) > test.test_support.TestFailed: Traceback (most recent call last): > File "./Lib/test/test_socket.py", line 456, in testSockName > my_ip_addr = socket.gethostbyname(socket.gethostname()) > gaierror: (-2, 'Name or service not known') OK, so this fails: my_ip_addr = socket.gethostbyname(socket.gethostname()) Try it from the python command line. This is what happens when I try it on FC6 w/ Python 2.5 (retyped, tho): >>> import socket >>> socket.gethostname() 'localhost.localdomain' >>> socket.gethostbyname(_) '127.0.0.1' >>> ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From jura.grozni at gmail.com Thu Feb 8 23:18:49 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 20:18:49 -0800 Subject: Newbie Question In-Reply-To: <1170980835.761703.163120@j27g2000cwj.googlegroups.com> References: <1170980835.761703.163120@j27g2000cwj.googlegroups.com> Message-ID: <1170994729.917461.6460@p10g2000cwp.googlegroups.com> but look out for pyqt. there is one thing in the eula i don't like. there is written that if you use qtWidgets and they like the aplication, you have to give up all your rights of the aplication. patent, idea, money everything is gone. i know this is open source, but maybe one day i will manage to sell an apliction for big money. On Feb 9, 1:27 am, "Eric_Dex... at msn.com" wrote: > You have a large number of basic languages that use opengl and > wxwindows. I haven't tried them but when you are looking at 3d stuff > all the opengl stuff is pretty fried. You can get around this with a > whole host of other 3d options including directx. I have also used > borlands c++ and it does some things very well when it comes to gui.. > You may want several languages unless you are doing simple tasks. > > On Feb 8, 6:12 pm, "John" wrote: > > > Visual Basic is also good. > > > "Reid" wrote in message > > >news:LeNyh.4130$R71.62146 at ursa-nb00s0.nbnet.nb.ca... > > > > Hello all > > > > I am just starting to play with programing again as a hobby. I have heard > > > good things about python. I have not really looked into the language much. > > > My question is, will python make programs with a gui under windows xp. If > > it > > > will do this I will explore the language more, if not I will try some > > other > > > language. > > > > Reid- Hide quoted text - > > > - Show quoted text - From gnewsg at gmail.com Fri Feb 2 10:32:14 2007 From: gnewsg at gmail.com (billie) Date: 2 Feb 2007 07:32:14 -0800 Subject: asyncore DoS vulnerability In-Reply-To: <1170422700.309941.203320@a34g2000cwb.googlegroups.com> References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> <1170422700.309941.203320@a34g2000cwb.googlegroups.com> Message-ID: <1170430334.170669.215150@q2g2000cwa.googlegroups.com> > This is not a CRASH, It looks an exception with a "Traceback", this is > the normal way python report problems, nothing wrong with that. > You can handle it with a try: except: I think that such a thing should be handled by asyncore itself. > 512 is probably a fixed limit into XP, win2k3 or win2k server will > accept more. > Maybe It's possible to increase this value somewhere in the registry. > If not this is how microsoft justify the difference between server and > workstation products :-) Yeah, maybe... >> Why does this exception isn't handled inside asyncore.py? > To do what ? To raise a custom asyncore error ? asyncore aims to be a framework, right? I think that when select() limit is reached asyncore should just drop other connections. That's all. > You can can probably run over this limit by starting multiple of your > server process (not thread, process). Hope you're joking... Why should I have to run multiple processes / threads to avoid such a problem? And what if my system / inteprepter does not support multiple processes / threads? From steve at holdenweb.com Sun Feb 11 01:51:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 06:51:50 +0000 Subject: wxPython libraries never detected In-Reply-To: References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> <1171143155.537545.9530@j27g2000cwj.googlegroups.com> Message-ID: hg wrote: > hg wrote: > >> d.lidell at gmail.com wrote: >> >>> On Feb 10, 1:07 pm, hg wrote: >>>> By default, you need to have wx installed in the python site-package >>>> path / under Mandriva, I have wx 2.8 installed >>>> here: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-ansi/ >>>> >>>> hg >>> Ah, now I see. But I have a new problem: >>> >>> "ls /usr/lib/python2.4/site-packages | grep wx-2.8" returns "wx-2.8- >>> gtk2-unicode" >>> >>> I copied wx-2.8-gtk2-unicode to /usr/lib/python2.5/site-packages/, >>> which I assume the programs I am attempting to compile and run are >>> using by default, but they still do not find the libraries. How can I >>> tell where the programs are searching for the libraries? >>> >>> Thanks. >> If you're going to try the copy technique (never tried it) , you also need >> to copy wx.pth and wxversion.py. >> >> hg > > Oh, and remember that a 2.4.pyc will not run with 2.5 ... so I would also > remove all .pyc that I might have copied. > In fact the interpreter will attempt to regenerate .pyc files if the current ones are from the wrong version, irrespective of file creation times. This is a good reason why you shouldn't share pure Python libraries between different versions (which I have just realised that a couple of my projects are still doing, explaining some extended timings I'd been wondering about - great question!) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From daftspaniel at gmail.com Thu Feb 8 08:01:38 2007 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 8 Feb 2007 05:01:38 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1170939698.599843.232030@j27g2000cwj.googlegroups.com> Srikanth wrote: > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. My favourite at the mo is Komodo Edit - free (though not OSS). On the OSS side, SPE is very good too - more of an IDE than Komodo Edit. DrPython is worth a look as is the similar Ulipad. Also have a look at Boa. Cheers, Davy Mitchell From nejucomo at gmail.com Tue Feb 20 03:33:55 2007 From: nejucomo at gmail.com (Nathan) Date: Tue, 20 Feb 2007 01:33:55 -0700 Subject: Checking for EOF in stream In-Reply-To: <13f991410702200027gb45f6b0pba8e8e192dabe497@mail.gmail.com> References: <12tkgeh32duee72@corp.supernews.com> <45DA45C3.2000707@gentlemail.com> <13f991410702200027gb45f6b0pba8e8e192dabe497@mail.gmail.com> Message-ID: <13f991410702200033m62f80a9dh898dc62b02bd987e@mail.gmail.com> On 2/20/07, Nathan wrote: > On 2/19/07, Gabriel Genellina wrote: > > En Mon, 19 Feb 2007 21:50:11 -0300, GiBo escribi?: > > > > > Grant Edwards wrote: > > >> On 2007-02-19, GiBo wrote: > > >>> > > >>> Classic situation - I have to process an input stream of unknown length > > >>> until a I reach its end (EOF, End Of File). How do I check for EOF? The > > >>> input stream can be anything from opened file through sys.stdin to a > > >>> network socket. And it's binary and potentially huge (gigabytes), thus > > >>> "for line in stream.readlines()" isn't really a way to go. > > >>> > > >>> For now I have roughly: > > >>> > > >>> stream = sys.stdin > > >>> while True: > > >>> data = stream.read(1024) > > >> if len(data) == 0: > > >> break #EOF > > >>> process_data(data) > > > > > > Right, not a big difference though. Isn't there a cleaner / more > > > intuitive way? Like using some wrapper objects around the streams or > > > something? > > > > Read the documentation... For a true file object: > > read([size]) ... An empty string is returned when EOF is encountered > > immediately. > > All the other "file-like" objects (like StringIO, socket.makefile, etc) > > maintain this behavior. > > So this is the way to check for EOF. If you don't like how it was spelled, > > try this: > > > > if data=="": break > > > > If your data is made of lines of text, you can use the file as its own > > iterator, yielding lines: > > > > for line in stream: > > process_line(line) > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > Not to beat a dead horse, but I often do this: > > data = f.read(bufsize): > while data: > # ... process data. > data = f.read(bufsize) > > > -The only annoying bit it the duplicated line. I find I often follow > this pattern, and I realize python doesn't plan to have any sort of > do-while construct, but even still I prefer this idiom. What's the > concensus here? > > What about creating a standard binary-file iterator: > > def blocks_of(infile, bufsize = 1024): > data = infile.read(bufsize) > if data: > yield data > > > -the use would look like this: > > for block in blocks_of(myfile, bufsize = 2**16): > process_data(block) # len(block) <= bufsize... > (ahem), make that iterator something that works, like: def blocks_of(infile, bufsize = 1024): data = infile.read(bufsize) while data: yield data data = infile.read(bufsize) From gagsl-py at yahoo.com.ar Sun Feb 11 13:13:22 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 15:13:22 -0300 Subject: Regular Expressions References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 13:35:26 -0300, deviantbunnylord at gmail.com escribi?: >> (Steven?) >> That's a little harsh -- regexes have their place, together with pointer >> arithmetic, bit manipulations, reverse polish notation and goto. The >> problem is when people use them inappropriately e.g. using a regex when >> a >> simple string.find will do. > > So as a newbie, I have to ask. I've played with the re module now for > a while, I think regular expressions are super fun and useful. As far > as them being a problem I found they can be tricky and sometimes the > regex's I've devised do unexpected things...(which I can think of two > instances where that unexpected thing was something that I had hoped > to get into further down the line, yay for me!). So I guess I don't > really understand why they are a "bad idea" to use. I don't know of > any other way yet to parse specific data out of a text, html, or xml > file without resorting to regular expressions. > What other ways are there? For very simple things, it's easier/faster to use string methods like find or split. By example, splitting "2007-02-11" into y,m,d parts: y,m,d = date.split("-") is a lot faster than matching "(\d+)-(\d+)-(\d+)" On the other hand, complex tasks like parsing an HTML/XML document, *can't* be done with a regexp alone; but people insist anyway, and then complain when it doesn't work as expected, and ask how to "fix" the regexp... Good usage of regexps maybe goes in the middle. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 17:55:51 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 28 Feb 2007 23:55:51 +0100 Subject: Question about raise and exceptions. In-Reply-To: References: Message-ID: <45e600aa$0$31978$426a34cc@news.free.fr> Ben Finney a ?crit : (snip) > The syntax of the 'raise' statement requires one, two, or three > arguments, all of which instruct 'raise' what to do, and none of which > refer to arguments given to the exception instance. Not quite. If the first argument is a class and the second argument is not an instance of that class, then it's passed as argument for instanciating the class - if it's a tuple, it's passed using the *args expansion. From fred at adventistcare.org Wed Feb 28 13:48:48 2007 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 28 Feb 2007 13:48:48 -0500 Subject: Eric on XP for Newbie Message-ID: <1A4BF05172023E468CB6E867923BC90404B0CFF1@accmail2.sunbelt.org> I've been using Eclipse with the PyDev extension. it's not bad, although you need a reasonably powerful computer to handle the bloat of Eclipse. For short programs, I still like emacs, but I'm old school. -----Original Message----- From: python-list-bounces+frsells=adventistcare.org at python.org [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On Behalf Of SPE - Stani's Python Editor Sent: Wednesday, February 28, 2007 1:38 PM To: python-list at python.org Subject: Re: Eric on XP for Newbie On Feb 28, 6:15 pm, jeffwatkins2... at gmail.com wrote: > On Feb 28, 4:27 pm, Alan Franzoni > > wrote: > > Il 28 Feb 2007 08:13:42 -0800, jeffwatkins2... at gmail.com ha scritto: > > > [cut] > > > Forget the tars. > > >http://www.quadgames.com/download/pythonqt/ > > > Get the two EXEs here. BTW, I don't think Eric3 is a really good IDE on > > Windows (yet). Try something likeSPE, or Scite, or any other editor like > > UltraEdit32. > > Thanks > > I've installedSPE. But what now? How do I run it? It doesn't appear > in "all programs" and ther's no .exe file that I can find Which installer did you use? If you used the python25 installer, use the python24 installer instead. (It will also work as it is not specific to 2.4 I have removed the python25 installer.) Than the shortcuts should appear in your "All Programs". Stani PS. A new version is about to released: http://pythonide.stani.be -- http://mail.python.org/mailman/listinfo/python-list From bob at passcal.nmt.edu Thu Feb 1 14:40:04 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 1 Feb 2007 12:40:04 -0700 Subject: Fixed length lists from .split()? References: <2007012611072716807-bob@passcalnmtedu> <2007012611264650073-bob@passcalnmtedu> <9CCuh.19350$X72.434@newsread3.news.pas.earthlink.net> Message-ID: <2007020112400475249-bob@passcalnmtedu> This idiom is what I ended up using (a lot it turns out!): Parts = Line.split(";") Parts += (x-len(Parts))*[""] where x knows how long the line should be. If the line already has more parts than x (i.e. [""] gets multiplied by a negative number) nothing seems to happen which is just fine in this program's case. Bob From johnjsal at NOSPAMgmail.com Thu Feb 1 14:52:03 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Feb 2007 14:52:03 -0500 Subject: Sorting a list In-Reply-To: <45c243a7$0$3020$426a34cc@news.free.fr> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> Message-ID: <45c24563$0$31965$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: > You don't tell how these lines are formatted, but it's possible that you > don't even need a regexp here. But wrt/ sorting, the list of tuples with > the sort key as first element is one of the best solutions. Ah, so simply using sort() will default to the first element of each tuple? The citations are like this: lastname, firstname. (year). title. other stuff. From gonzlobo at gmail.com Sat Feb 3 19:12:13 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Sat, 3 Feb 2007 17:12:13 -0700 Subject: Decimating Excel files In-Reply-To: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> Message-ID: Thanks, but I was looking for a python solution. > Excel has VBA and can do this easily. One thing about > Excel's VBA is that it already understands Excel. From steve at REMOVE.THIS.cybersource.com.au Tue Feb 20 08:02:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 00:02:43 +1100 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: On Tue, 20 Feb 2007 00:44:24 +0000, Peter mayne wrote: > Steven D'Aprano wrote: >> If Python 3 dropped the print >> statement and replaced it with official_print_function(), how would that >> help you in your goal to have a single code base that will run on both >> Python 2.3 and Python 3, while still using print? > > Is there any reason why official_print_function isn't sys.stdout.write? Why would you want a convenience function like print to take one import, three look-ups and 16 characters instead of always available, one look-up and five characters? > I can't remember the last time I used print in actual code (apart from > short-lived debugging lines), so I'm bewildered as to why print seems to > be so important. print is important for the convenience, for short-lived debugging, and for use in the interactive interpreter. -- Steven. From aspineux at gmail.com Thu Feb 1 18:08:01 2007 From: aspineux at gmail.com (aspineux) Date: 1 Feb 2007 15:08:01 -0800 Subject: LDAP/LDIF Parsing In-Reply-To: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> Message-ID: <1170371281.543905.261440@m58g2000cwm.googlegroups.com> The tree hierarchy is defined by the DN of each object, the types of the object is specified by its objectClass. Just collect all items (or do it dynamically by tunning the scope and the base of your search request) On 1 f?v, 18:22, "Cruelemort" wrote: > All, > > I am hoping someone would be able to help me with a problem. I have an > LDAP server running on a linux box, this LDAP server contains a > telephone list in various groupings, the ldif file of which is - > > dn: dc=example,dc=com > objectClass: top > objectClass: dcObject > objectClass: organization > dc: example > o: Example Organisation > > dn: ou=groupa,dc=example,dc=com > ou: groupa > objectClass: top > objectClass: organizationalUnit > description: Group A > > dn: cn=johnsmith,ou=groupa,dc=example,dc=com > cn: johnsmith > objectClass: top > objectClass: person > sn: Smith > telephoneNumber: 112 > > dn: cn=davesteel,ou=groupa,dc=example,dc=com > cn: davesteel > objectClass: top > objectClass: person > sn: Steel > telephoneNumber: 113 > > dn: ou=groupb,dc=example,dc=com > ou: groupb > objectClass: top > objectClass: organizationalUnit > description: Group B > > dn: cn=williamdavis,ou=groupb,dc=example,dc=com > cn: williamdavis > objectClass: top > objectClass: person > sn: Davis > telephoneNumber: 122 > > dn: cn=jamesjarvis,ou=groupb,dc=example,dc=com > cn: jamesjarvis > objectClass: top > objectClass: person > sn: Jarvis > telephoneNumber: 123 > > I am creating a python client program that will display the telephone > list in the same directory structure as is on the LDAP server (i.e. it > starts with buttons of all the groups, when you click on a group it > comes up with buttons of all the numbers or groups available, and you > can continually drill down). > > I was wondering the best way to do this? I have installed and used the > python-ldap libraries and these allow me to access and search the > server, but the searches always return a horrible nesting of lists, > tuples and dictionaries, below is an example of returning just one > record - > > ('dc=example,dc=com', {'objectClass': ['top', 'dcObject', > 'organization'], 'dc': ['example'], 'o': ['Example Organisation']}) > > Basically i think i need to parse the search results to create objects > and build the python buttons around this, but i was hoping someone > would be able to point me in the correct direction of how to do this? > Is there a parser available? (there is an ldif library available but > it is not obvious how this works, i cannot see much documentation, and > it seems to be deprecated...). > > Many thanks. > > Ian From gagsl-py at yahoo.com.ar Wed Feb 14 01:17:24 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 03:17:24 -0300 Subject: Please help about an instance var References: Message-ID: En Tue, 13 Feb 2007 23:54:29 -0300, escribi?: >>>> from UserDict import UserDict >>>> d = {1:2,3:4,5:6} >>>> d1 = UserDict(d) >>>> d1 > {1: 2, 3: 4, 5: 6} >>>> d1.data > {1: 2, 3: 4, 5: 6} > Here why both d1 and d1.data have the same values?As shown below,they're > different types. > >>>> type(d1) > >>>> type(d1.data) > > Please help.Thanks! UserDict is a specially crafted class that looks and acts like a dictionary, so, its str() and repr() looks like a true dictionary. But as you have seen, using type() you can distinguish between the two. d1.__class__ is different too, as many other details; but many functions don't require a "true" dictionary anyway, just use methods like keys(), items(), and magic support for d[key], d[key]=value, and so on. As far as UserDict provides those methods, all functions expecting a dictionary-like argument are happy. An historical note: On older Python versions, you could not inherit from builtin types. If you wanted a custom dictionary-like class, you had to inherit from UserDict or a similar class. Now, you can inherit from dict if you want; and DictMixin can be used to provide any class with dictionary functionalities in a much convenient way. -- Gabriel Genellina From lbates at websafe.com Thu Feb 22 13:33:14 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 22 Feb 2007 12:33:14 -0600 Subject: How to covert ASCII to integer in Python? In-Reply-To: References: Message-ID: John wrote: > I just found ord(c), which convert ascii to integer. > > Anybody know what the reverse is? > > "John" wrote in message > news:erkknl$6d4p$1 at netnews.upenn.edu... >> Is there any built in function that converts ASCII to integer or vice > versa >> in Python? >> >> Thanks! >> >> > > The phrasing of your question threw us all. What you want is chr backslash=chr(92) -Larry Bates From mrsanad1 at yahoo.com Mon Feb 12 06:26:37 2007 From: mrsanad1 at yahoo.com (Magdy Sanad) Date: Mon, 12 Feb 2007 03:26:37 -0800 (PST) Subject: Question Message-ID: <868522.81158.qm@web37312.mail.mud.yahoo.com> Dear Dr. I'm a Researcher from Cairo, Egypt. I installed the language programmer (Python) on my PC. I executed the following statements to read unformatted fortran data. I have the original program which I translate it to the Python language : pro rd_gadget, f=fname, d = data, h= hdr, swap=swap ;modified from Volker's read_snapshot_single.pro to be a free-standing ;program that reads fname, and returns data and header structures M-MML 6/16/06 ;added option to swap byte order to read Intel files on PowerPC ;11/8/06 M-MML if not keyword_set(fname) then fname="/home/vspringe/ICs/galaxy.dat.intel" npart=lonarr(6) massarr=dblarr(6) time=0.0D redshift=0.0D flag_sfr=0L flag_feedback=0L npartTotal=lonarr(6) bytesleft=256-6*4 - 6*8 - 8 - 8 - 2*4-6*4 la=intarr(bytesleft/2) openr,1,fname,/f77_unformatted, swap_endian = swap readu,1,npart,massarr,time,redshift,flag_sfr,flag_feedback,npartTotal,la hdr = { np: npart, mass: massarr, time: time, z: redshift, sfr: $ flag_sfr, fb: flag_feedback, nptot: npartTotal, la: la} N=total(npart) pos=fltarr(3,N) vel=fltarr(3,N) id=lonarr(N) ind=where((npart gt 0) and (massarr eq 0)) if ind(0) ne -1 then begin Nwithmass= total(npart(ind)) mass=fltarr(Nwithmass) endif else begin Nwithmass= 0 endelse nfield = 0 readu,1,pos nm = 'position' nfield = nfield + 1 readu,1,vel nm = [nm, 'velocity'] nfield = nfield + 1 readu,1,id nm = [nm, 'id'] nfield = nfield + 1 if Nwithmass gt 0 then begin readu,1,mass nm = [nm, 'mass'] nfield = nfield + 1 endif NGas=npart(0) if Ngas gt 0 then begin u=fltarr(Ngas) readu,1,u nm = [nm, 'gas specific energy'] nfield = nfield + 1 rho=fltarr(Ngas) readu,1,rho nm = [nm, 'gas density'] nfield = nfield + 1 endif close,1 if (nfield lt 3) or (nfield gt 6) then $ print,'RD_GADGET: Unexpected number of data fields, nfield = ',nfield $ else if nfield eq 3 then $ data = { nf: nfield, nm: nm, pos: pos, vel: vel, id: id } $ else if nfield eq 4 then $ data = { nf: nfield, nm: nm, pos: pos, vel: vel, id: id, mass: mass } $ else if nfield eq 6 then $ data = { nf: nfield, nm: nm, pos: pos, vel: vel, id: id, mass: mass, $ spe: u, den: rho } end Below you will find my attempt to translate the first part of this program to Python language import scipy.io.mio import Numeric from Numeric import * file_hdg = 'D:/mm/hdg' # Integer (Long) Arrays npart = array (6) # Floating point (double precision) array massarr = array(6) time=0.0 redshift=0.0 flag_sfr=0L flag_feedback=0L npartTotal=array(6) bytesleft=256-6*4 - 6*8 - 8 - 8 - 2*4-6*4 la=array(bytesleft/2) def readdata ( filePath ): fileHandle = scipy.io.mio.fopen( filePath, 'r') def fort_read(self,fmt,dtype=None): numberOfBlocks = fileHandle.fort_read( 1 , 'l' ) print numberOfBlocks readdata (file_hdg),npart,massarr,time,redshift,flag_sfr,flag_feedback,npartTotal,la All these commands are accepted, the result with the last command : readdata(file_hdg),npart,massarr,time,redshift,flag_sfr,flag_feedback,npartTotal,la Is (None, 6, 6, 0.0, 0.0, 0L, 0L, 6, 68) I will be very appreciated if you send me your opinion about this and what the ( None ) means in this result. Best Regards Magdy Sanad National Research Institute of Astronomy and Geophysics Astronomy Department Helwan - Cairo - Egypt --------------------------------- Looking for earth-friendly autos? Browse Top Cars by "Green Rating" at Yahoo! Autos' Green Center. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jordan.taylor2 at gmail.com Thu Feb 15 12:39:54 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 15 Feb 2007 09:39:54 -0800 Subject: How to write a programe that include both pipe(low speed system call) and signal In-Reply-To: References: Message-ID: <1171561193.843864.292540@h3g2000cwc.googlegroups.com> On Feb 15, 2:51 am, Marco wrote: > Hi, > I have know that signal will interrupt some kind low speed system > call like pipe. But how to design a program that both support signal > and pipe? > > I have a mplayer.py to play movie via os.popen2() and mplayer > slave mode. And there is a mplayer_ctl.py send signal to mplayer.py to > trigger function from mplayer.py. Sometimes os.popen2() is reading or > writing when user run mplayer_ctl.py the bad things raise... > > Is there some better way to design the programe? Thank you > > -- > LinuX Power Take a look at the subprocess module, which is meant to replace popen[1,2,3...](). Also, please try to explain the problem again, because I just can't decypher everything you're trying to do (and say). cheers, Jordan From grante at visi.com Mon Feb 12 22:35:56 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 13 Feb 2007 03:35:56 -0000 Subject: can't find a way to display and print pdf through python. References: <12t17gsjh6vgh94@corp.supernews.com> <12t1ch1n8hj9n69@corp.supernews.com> Message-ID: <12t2cgssrrbmf1a@corp.supernews.com> On 2007-02-12, Larry Bates wrote: > Grant Edwards wrote: >> On 2007-02-12, Larry Bates wrote: >>> On 2007-02-12, Larry Bates wrote: >>>>>> I at least need the code for useing some library for >>>>>> connecting to acrobat reader and giving the print command on >>>>>> windows and some thing similar on ubuntu linux. >>>>> Just let the registered .PDF viewer do it for you. >>>>> >>>>> os.start('myfile.pdf') >>>> Eh? I don't see os.start() it either 2.5 or 2.44 >>>> documentation, and it's sure not there in 2.4.3: >>> My bad. os.system() >> >> That doesn't work either: >> >> $ ls -l user.pdf >> -rw------- 1 grante users 35640 2005-11-21 14:33 user.pdf >> >> $ python >> Python 2.4.3 (#1, Dec 10 2006, 22:09:09) >> [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 >> Type "help", "copyright", "credits" or "license" for more >> information. >> >>> import os >> >>> os.system('user.pdf') >> sh: user.pdf: command not found >> 32512 >> >>> > > Works fine on my system. You linux guys just have it hard. > The op said "windows". The posting to which you replied specified Linux. > I can't answer for ubuntu linux but maybe you can help there? I don't see how. Pdf files just aren't executable. -- Grant Edwards grante Yow! FIRST, I'm covering at you with OLIVE OIL and visi.com PRUNE WHIP!! From bj_666 at gmx.net Sat Feb 3 11:40:31 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 03 Feb 2007 17:40:31 +0100 Subject: HELP NEEDED ... Regd. Regular expressions PyQt References: Message-ID: In , vishal wrote: > I am trying to work out a regular expression in a PyQt environment for > time in hh:mm:ss format. Any suggestions? Maybe don't use a re for something that simple. Splitting at ``:`` characters, converting to `int` and checking the value ranges isn't that hard without a regular expression. Ciao, Marc 'BlackJack' Rintsch From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 12:07:45 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 18:07:45 +0100 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: Thinker wrote: > It should be "PyObject *coord;" . > Maybe, it is what is wrong with your program! > > Should it? The gcc shows me a warning then: warning: 'coord' is used uninitialized in this function and during the execution I get the same error *plus* a segfault. zefciu From sjmachin at lexicon.net Tue Feb 6 19:41:00 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Feb 2007 16:41:00 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170806724.447542.206120@m58g2000cwm.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> <1170775779.707583.131420@k78g2000cwa.googlegroups.com> <1170806044.201254.289080@l53g2000cwa.googlegroups.com> <1170806724.447542.206120@m58g2000cwm.googlegroups.com> Message-ID: <1170808860.240144.151820@v33g2000cwv.googlegroups.com> On Feb 7, 11:05 am, garri... at gmail.com wrote: > On Feb 6, 4:54 pm, "John Machin" wrote: > > > Recursive? Bzzzt! > > I woudl be happy to hear your alternative, which doesn't depend on > language specific tricks. Thus far, all you have suggested is using an > alternative form of the division function, Huh? Thus far (in this post) all I've said is (in effect) that IMHO mentioning recursion is just cause for termination of job interview. > which I would consider to > be outside the spirit of the question (though I have been wrong many > times before). > > > Might it not be better to halve the interval at each iteration instead > > of calling a random number function? mid = (lo + hi) >> 1 looks > > permitted and cheap to me. Also you don't run the risk of it taking a > > very high number of iterations to get a result. > > I had considered this, but to halve, you need to divide by 2. Using > random, while potentially increasing the number of iterations, removes > the dependency of language tricks and division. "Potentially increases the number of iterations"? Sorry, the interview for marketing manager is across the hall. For example if your N must fit in 16 bits, you could end up with O(2**16) iterations. This may not show up in acceptance testing. And each iteration involves calling a random number function. A binary search has a guaranteed upper limit of O(16). Let's get this in contect: the traditional "long division" approach takes 16 iterations! Shifting to divide by a power of 2 is not a "language trick". In any case any compiler that deserves to be used will replace division by a power of 2 with a shift. > > > Did you notice the important word *efficiently* in line 1 of the spec? > > Even after ripping out recursion and random numbers, your proposed > > solution is still way off the pace. > > Again, I look forward to reading your solution. > Respectfully, read my other posts in this thread. The correct answer IMHO is "Semi-decent compilers like gcc will do a good-enough job of dividing an integer by a constant. Only in situations like a very high-use library routine where the N is known to be much smaller than 2**wordsize might it be worthwhile to see if a bit-bashing approach could generate faster code". Cheers, John From skpeterson at nospam.please.ucdavis.edu Sun Feb 11 23:55:17 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 20:55:17 -0800 Subject: string.replace non-ascii characters Message-ID: Greetings Pythonistas. I have recently discovered a strange anomoly with string.replace. It seemingly, randomly does not deal with characters of ordinal value > 127. I ran into this problem while downloading auction web pages from ebay and trying to replace the "\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from urllib2. Yet today, all is fine, no problems whatsoever. Sadly, I did not save the exact error message, but I believe it was a ValueError thrown on string.replace and the message was something to the effect "character value not within range(128). Some googling seemed to indicate other people have reported similar troubles: http://mail.python.org/pipermail/python-list/2006-July/391617.html Anyone have any enlightening advice for me? -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From flupke at nonexistingdomain.com Fri Feb 9 02:17:17 2007 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 09 Feb 2007 07:17:17 GMT Subject: postgres backup script and popen2 In-Reply-To: References: Message-ID: <1eVyh.334214$bn7.6423643@phobos.telenet-ops.be> flupke schreef: Thanks for all the info. I'm sure i will get it right this time :) Benedict From Michel.Al1 at gmail.com Thu Feb 8 12:42:01 2007 From: Michel.Al1 at gmail.com (k0mp) Date: 8 Feb 2007 09:42:01 -0800 Subject: begin to parse a web page not entirely downloaded Message-ID: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> Hi, Is there a way to retrieve a web page and before it is entirely downloaded, begin to test if a specific string is present and if yes stop the download ? I believe that urllib.openurl(url) will retrieve the whole page before the program goes to the next statement. I suppose I would be able to do what I want by using the sockets module, but I'm sure there's a simpler way to do it. From sickcodemonkey at gmail.com Wed Feb 28 21:05:06 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 28 Feb 2007 21:05:06 -0500 Subject: pyHook or SetWindowsHookEx In-Reply-To: <1172684780.613003.30350@z35g2000cwz.googlegroups.com> References: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> <1172684780.613003.30350@z35g2000cwz.googlegroups.com> Message-ID: <2adc542f0702281805j4eecca2fj211c68a600262fee@mail.gmail.com> I have just gotten into pyHook, so I could be incredibly wrong, but I have researched a lot into your problem. (cuz I have the same question) I think the python program has to be on the remote machine becuase from my understanding pyHook just reads in the windows' keyboard driver. And when you remote desktop or VNC into another machine, i am pretty sure either windows (for remote desktop) and vnc (the actual host program) controls the key commands so the win objects would not work for remoting. On 28 Feb 2007 09:46:20 -0800, abcd wrote: > > anyone? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Sat Feb 3 19:42:19 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 03 Feb 2007 17:42:19 -0700 Subject: [OT] main In-Reply-To: References: Message-ID: fatwallet961 at yahoo.com wrote: > def main(argv): > try: > optlist, args = getopt.getopt(argv[1:], 'hvo:D:', ['help', > 'verbose']) > except getopt.GetoptError, msg: > sys.stderr.write("preprocess: error: %s" % msg) > sys.stderr.write("See 'preprocess --help'.\n") > return 1 > outfile = sys.stdout > defines = {} > for opt, optarg in optlist: > if opt in ('-h', '--help'): > sys.stdout.write(__doc__) > return 0 > elif opt in ('-v', '--verbose'): > log.setLevel(logging.DEBUG) > elif opt == '-o': > outfile = optarg > elif opt == '-D': > if optarg.find('=') != -1: > var, val = optarg.split('=', 1) > try: > val = eval(val, {}, {}) > except: > pass > else: > var, val = optarg, None > defines[var] = val > > if len(args) != 1: > sys.stderr.write("preprocess: error: incorrect number of "\ > "arguments: argv=%r\n" % argv) > return 1 > else: > infile = args[0] > > try: > preprocess(infile, outfile, defines) > except PreprocessError, ex: > sys.stderr.write("preprocess: error: %s\n" % str(ex)) This is offtopic, but I suggest looking into using optparse_ or argparse_ instead of getopt. This would simplify your code to something like:: parser = argparse.ArgumentParser(description='Preprocess a file.') parser.add_argument('infile', default=sys.stdin, type=argparse.FileType('r')) parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-o', dest='outfile', default=sys.stdout, type=argparse.FileType('w')) parser.add_argument('-D', dest='defines', action='append') args = parser.parse_args() if args.verbose is not None: log.setLevel(logging.DEBUG) defines = {} for define in args.define: var, sep, val = define.partition('=') defines[var] = val or None try: preprocess(args.infile, args.outfile, defines) except PreprocessError, ex: sys.stderr.write("preprocess: error: %s\n" % str(ex)) Additionally, if you include your help messages using the help= argument to add_argument(), your usage message will be generated automatically. .. _optparse: http://docs.python.org/lib/module-optparse.html .. _argparse: http://argparse.python-hosting.com/ STeVe From steven.bethard at gmail.com Mon Feb 12 00:23:59 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 11 Feb 2007 22:23:59 -0700 Subject: string.replace non-ascii characters In-Reply-To: References: Message-ID: Samuel Karl Peterson wrote: > Greetings Pythonistas. I have recently discovered a strange anomoly > with string.replace. It seemingly, randomly does not deal with > characters of ordinal value > 127. I ran into this problem while > downloading auction web pages from ebay and trying to replace the > "\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from > urllib2. Yet today, all is fine, no problems whatsoever. Sadly, I > did not save the exact error message, but I believe it was a > ValueError thrown on string.replace and the message was something to > the effect "character value not within range(128). Was it something like this? >>> u'\xa0'.replace('\xa0', '') Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) You might get that if you're mixing str and unicode. If both strings are of one type or the other, you should be okay: >>> u'\xa0'.replace(u'\xa0', '') u'' >>> '\xa0'.replace('\xa0', '') '' STeVe From michele.simionato at gmail.com Sat Feb 10 10:39:21 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 Feb 2007 07:39:21 -0800 Subject: Please recommend library for multithread download In-Reply-To: <1171121213.759544.274870@q2g2000cwa.googlegroups.com> References: <1171121213.759544.274870@q2g2000cwa.googlegroups.com> Message-ID: <1171121960.981798.224890@s48g2000cws.googlegroups.com> On Feb 10, 4:26 pm, "David Xiao" wrote: > Hello there, > > I am looking for library (small better) that can fetch URL and > download to local file in multi-threads. > > urllib2 is not thread safe as I tested. What will be? You may want to look at this recent thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/77fc9888e43bac46/1df3bcbfb785395c?lnk=gst&q=download+simionato&rnum=1&hl=en#1df3bcbfb785395c Michele Simionato From horpner at yahoo.com Sat Feb 3 05:24:49 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 03 Feb 2007 10:24:49 GMT Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" References: Message-ID: On 2007-02-03, Gabriel Genellina wrote: > En Sat, 03 Feb 2007 06:12:33 -0300, Peter Otten <__peter__ at web.de> > escribi?: > >> John Nagle wrote: >> >>> How do I suppress "DeprecationWarning: Old style callback, use >>> cb_func(ok, >>> store) instead". A library is triggering this message, the library is >>> being fixed, but I need to make the message disappear from the output >>> of a >>> CGI program. >> >> import warnings >> warnings.filterwarnings("ignore", message="Old style callback, use >> cb_func(ok, store) instead") > > Or you can be more aggressive and filter out all DeprecationWarnings: > warnings.simplefilter("ignore",DeprecationWarning) > (same as using option -Wignore::DeprecationWarning on the python command > line) Ah, yes! The null module. Python should have more of these. I mean "shouldn't". ;) -- Neil Cerutti From steveo at syslang.net Thu Feb 1 13:54:09 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 1 Feb 2007 13:54:09 -0500 (EST) Subject: Question about a single underscore. In-Reply-To: <7xveilzpvs.fsf@ruckus.brouhaha.com> References: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> <7xveilzpvs.fsf@ruckus.brouhaha.com> Message-ID: On Thursday, Feb 1st 2007 at 10:36 -0800, quoth Paul Rubin: =>"Steven W. Orr" writes: =>> to cause a different instantiation a la =>> foo = _const() =>> The goal would be to create different instances of consts. => =>The idea of putting it in sys.modules is so it's visible in all modules. => =>> >>> import const =>> >>> iii=_const() => =>You need => iii = const._const =>-- =>http://mail.python.org/mailman/listinfo/python-list => 547 > python Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import const >>> iii = const._const Traceback (most recent call last): File "", line 1, in ? AttributeError: _const instance has no attribute '_const' *>>> iii = const._const() Traceback (most recent call last): File "", line 1, in ? AttributeError: _const instance has no attribute '_const' >>> What am I missing here? (Sorry if it should be obvious) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From deets at nospam.web.de Tue Feb 27 05:46:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Feb 2007 11:46:56 +0100 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> Message-ID: <54igh0F2143jeU1@mid.uni-berlin.de> boris.smirnov at gmail.com wrote: > Hi all, > > I have a python script that works without any problem on Windows but > with error: > > QPaintDevice: Must construct a QApplication before a QPaintDevice > > on Linux. > > Where could be the problem? This is the problem: You Must construct a QApplication before a QPaintDevice Diez From rshepard at nospam.appl-ecosys.com Wed Feb 7 09:26:27 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 7 Feb 2007 14:26:27 GMT Subject: Running Application Within Emacs Message-ID: My editor is emacs in linux, and I have the python mode enabled. The two menus -- IM-Python and Python -- allow me to navigate within the loaded module and open execute buffers, among other things. But, I don't see a way to run a wxPython application from within the editor as I would from the command line. Is this possible? If so, how? Ric From rzantow at gmail.com Sat Feb 3 09:35:42 2007 From: rzantow at gmail.com (rzed) Date: Sat, 03 Feb 2007 09:35:42 -0500 Subject: strange test for None References: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> Message-ID: "karoly.kiripolszky" wrote in news:1170510427.981922.170100 at m58g2000cwm.googlegroups.com: > in my server i use the following piece of code: > > ims = self.headers["if-modified-since"] > if ims != None: > t = int(ims) > > and i'm always getting the following error: > > t = int(ims) > ValueError: invalid literal for int(): None > > i wanna know what the hell is going on... first i tried to test > using is not None, but it makes no difference. > It appears that ims is the string 'None', so it fails the test, but is an invalid literal. -- rzed From sxn02 at yahoo.com Thu Feb 15 01:20:09 2007 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Wed, 14 Feb 2007 22:20:09 -0800 (PST) Subject: Enter Enter... troubles Message-ID: <500853.58412.qm@web56004.mail.re3.yahoo.com> Hi All, In my application I have a class like this: from Tkinter import * class MyClass: def __init__(self, root): self.property=value self.aButton=Button(root, text='Press me!') self.aButton.bind('', self.handler) self.aButton.bind('',self.handler) ... def handler(self,event): self.aButton.unbind('') self.aButton.unbind('') ... localVar=self.property self.property=newCalculatedValue ... self.aButton.bind('', self.handler) self.aButton.bind('',self.handler) The idea is to prevent a fast user (like my boss) to press repeatedly the "enter" key and create havoc with self.property and localVar. But it doesn't work: my boss manages to start at least twice the handler (which, among other things creates a Toplevel, so I end up with a messy screen). How should I proceed? Thanks for your advices, Sorin --------------------------------- Sucker-punch spam with award-winning protection. Try the free Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: From troy.melhase at gmail.com Thu Feb 15 03:32:09 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Wed, 14 Feb 2007 23:32:09 -0900 Subject: Method overloading? In-Reply-To: <1171515271.811324.218020@s48g2000cws.googlegroups.com> References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> Message-ID: On 14 Feb 2007 20:54:31 -0800, placid wrote: > class Test: > def __init__(self): > pass > > def puts(self, str): > print str > > def puts(self, str,str2): > print str,str2 you might look into the overloading module and its decorator. source is in the sandbox: http://svn.python.org/view/sandbox/trunk/overload/overloading.py using it, you could re-write your example as: # from overloading import overloaded class Test(object): @overloaded def puts(self, S): print S @puts.register(object, str, str) def puts_X(self, S, S2): print S, S2 two things to note. first, i changed your class to derive from object. I don't know if that's required, but i suspect it is. second, i changed your argument names. the argument names in your example shadow built-in names. you shouldn't do that in any case, but it could become especially confusing using the overloaded decorator, which relies on argument type to select the correct method. From malaclypse2 at gmail.com Sun Feb 25 10:59:49 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Sun, 25 Feb 2007 10:59:49 -0500 Subject: finding out the precision of floats In-Reply-To: <1172412661.998318.109180@s48g2000cws.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> Message-ID: <16651e80702250759s767888e0k336ccee0ec3c249a@mail.gmail.com> On 25 Feb 2007 06:11:02 -0800, Arnaud Delobelle wrote: > Moreover the reason I got interested in this is because I am creating > a Dec class (decimal numbers) Are you familiar with Python's Decimal library? http://docs.python.org/lib/module-decimal.html -- Jerry From sjmachin at lexicon.net Fri Feb 23 19:54:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Feb 2007 16:54:33 -0800 Subject: Regex Speed In-Reply-To: <1172272548.867795.289560@m58g2000cwm.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172079285.197453.131490@h3g2000cwc.googlegroups.com> <1172272548.867795.289560@m58g2000cwm.googlegroups.com> Message-ID: <1172278473.849093.264970@s48g2000cws.googlegroups.com> On Feb 24, 10:15 am, garri... at gmail.com wrote: > On Feb 21, 10:34 am, garri... at gmail.com wrote: > > > On Feb 20, 6:14 pm, Pop User wrote: > > >http://swtch.com/~rsc/regexp/regexp1.html > > Going back a bit on a tangent, the author of this citation states that > any regex can be expressed as a DFA machine. However, while > investigating this more I appear to have found one example of a regex > which breaks this assumption. > > "ab+c|abd" > > Am I correct? No. > Can you think of a deterministic method of computing > this expression? Firstly rewrite a bit: ab+c|abd a(b+c|bd) a(bb*c|bd) ab(b*c|d) ab(b+c|c|d) Here's a DFA that recognises that: State 0: a -> 1 State 1: b -> 2 State 2: b -> 3 # start of the b+c branch c -> 4 # the c branch d -> 4 # the d branch State 3: b -> 3 c -> 4 State 4: accepting state > It would be easier with a NFA machine, What is "It"? > but given that > the Python method of computing RE's involves pre-compiling a re > object, AFAIK all serious regex engines precompile a regex into an internal representation which can be saved for reuse. > optimizing the matching engine What does that mean? > would make the most sense to > me. Compared to what alternatives? > > Here's what I have so far: [big snip] > >>> a = compile("ab+c|abd") [snip] > >>> a.match("abbd") > Match! Bzzzt. Neither "ab+c" nor "abd" match a prefix of "abbd". HTH, John From larry.bates at websafe.com Mon Feb 12 10:56:32 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Feb 2007 09:56:32 -0600 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: Message-ID: krishnakant Mane wrote: > hello all, > I am stuck with a strange requirement. > I need a library that can help me display a pdf file as a report and > also want a way to print the same pdf file in a platform independent > way. > if that's not possible then I at least need the code for useing some > library for connecting to acrobat reader and giving the print command > on windows and some thing similar on ubuntu linux. > the problem is that I want to display reports in my application. the > user should be able to view the formatted report on screen and at his > choice click the print button on the screen to send it to the printer. > I have reportlab installed and that is sufficient to generate pdf reports. > but I still can't fine the way to display it directly and print it > directly. > Please help me. > Krishnakant. Just let the registered .PDF viewer do it for you. os.start('myfile.pdf') Launches whatever is registered as .PDF viewer and user can then print, save, zoom, etc. on their own. -Larry From creechm at gmail.com Sat Feb 3 18:03:03 2007 From: creechm at gmail.com (Mark) Date: 3 Feb 2007 15:03:03 -0800 Subject: .pth configuration method not working Message-ID: <1170543783.843044.22670@k78g2000cwa.googlegroups.com> Sys.path doesn't recognize any directories that I add using the .pth method. I'm running Windows XP if that helps diagnose the problem. Here is what I've done: The original output of sys.path: ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat- win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\ \site-packages'] I've added a file "MyPaths.pth" to "C:\Python25\". MyPaths.pth contains one line that reads: C:\Python25\MyModules. For some reason sys.path won't ever recognize that C:\Python25\MyModules exists. This is very frustrating because I know that this method is supposed to work. ANY help would be appreciated. Thanks in advance, Mark From webmaster at cacradicalgrace.org Thu Feb 8 12:29:34 2007 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Thu, 08 Feb 2007 10:29:34 -0700 Subject: Partial 1.0 - Partial classes for Python References: Message-ID: Martin v. L?wis wrote: > I'm happy to announce partial 1.0; a module to implement > partial classes in Python. It is available from > > http://cheeseshop.python.org/pypi/partial/1.0 > > A partial class is a fragment of a class definition; > partial classes allow to spread the definition of > a class over several modules. One location serves > as the original definition of the class. > > To extend a class original_module.FullClass with > an additional function, one writes > > from partial import * > import original_module > Erm, Please don't use 'from x import *', especially in a demo example like this. It makes it less clear which variables below come from your module. Thanks, Cliff > class ExtendedClass(partial, original_module.FullClass): > def additional_method(self, args): > body > more_methods > > This module is licensed under the Academic Free License v3.0. > > Please send comments and feedback to martin at v.loewis.de From uymqlp502 at sneakemail.com Mon Feb 19 02:03:04 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 18 Feb 2007 23:03:04 -0800 Subject: generating Java bytecode Message-ID: <1171868584.254570.244180@m58g2000cwm.googlegroups.com> I would like to generate Java bytecode from Python source. I know this is possible using Jython, but I am having problems getting my code to run on Jython. Is there another way to get Java bytecode? Thanks. From garrickp at gmail.com Tue Feb 20 19:40:40 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 20 Feb 2007 16:40:40 -0800 Subject: Regex Speed In-Reply-To: <1172013317.943062.303110@t69g2000cwt.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172013317.943062.303110@t69g2000cwt.googlegroups.com> Message-ID: <1172018440.659870.195010@h3g2000cwc.googlegroups.com> On Feb 20, 4:15 pm, "John Machin" wrote: > What is an "exclusionary set"? It would help enormously if you were to > tell us what the regex actually is. Feel free to obfuscate any > proprietary constant strings, of course. My apologies. I don't have specifics right now, but it's something along the line of this: error_list = re.compile(r"error|miss|issing|inval|nvalid|math") exclusion_list = re.complie(r"No Errors Found|Premature EOF, stopping translate") for test_text in test_file: if error_list.match(test_text) and not exclusion_list.match(test_text): #Process test_text Yes, I know, these are not re expressions, but the requirements for the script specified that the error list be capable of accepting regular expressions, since these lists are configurable. > I presume you mean you didn't read the whole file into memory; > correct? 2 million lines doesn't sound like much to me; what is the > average line length and what is the spec for the machine you are > running it on? You are correct. The individual files can be anywhere from a few bytes to 2gig. The average is around one gig, and there are a number of files to be iterated over (an average of 4). I do not know the machine specs, though I can safely say it is a single core machine, sub 2.5ghz, with 2gigs of RAM running linux. > map is a built-in function, not a trick. What "tricks"? I'm using the term "tricks" where I may be obfuscating the code in an effort to make it run faster. In the case of map, getting rid of the interpreted for loop overhead in favor of the implied c loop offered by map. > What system calls? Do you mean running grep as a subprocess? Yes. While this may not seem evil in and of itself, we are trying to get our company to adopt Python into more widespread use. I'm guessing the limiting factor isn't python, but us python newbies missing an obvious way to speed up the process. > To help you, we need either (a) basic information or (b) crystal > balls. Is it possible for you to copy & paste your code into a web > browser or e-mail/news client? Telling us which version of Python you > are running might be a good idea too. Can't copy and paste code (corp policy and all that), no crystal balls for sale, though I hope the above information helps. Also, running a trace on the program indicated that python was spending a lot of time looping around lines, checking for each element of the expression in sequence. And python 2.5.2. Thanks! From hg at nospam.org Tue Feb 13 02:34:10 2007 From: hg at nospam.org (hg) Date: Tue, 13 Feb 2007 08:34:10 +0100 Subject: float print formatting References: Message-ID: Peter Otten wrote: > hg wrote: > >> Considering the float 0.0, I would like to print 00.00. >> >> I tried '%02.02f' % 0.0 ... but I get 0.00 >> >> Any clue ? > > The first integer specifies the total width: > >>>> "%05.2f" % 0 > '00.00' > > Peter Many thanks ! hg From vithi99 at hotmail.com Fri Feb 16 21:35:53 2007 From: vithi99 at hotmail.com (vithi) Date: 16 Feb 2007 18:35:53 -0800 Subject: how to use Dispatch to open an application in win32com.client Message-ID: <1171679753.878696.145210@s48g2000cws.googlegroups.com> Hi' I am trying to launch an application. When I try like that When I try like that Excel is opening import win32com.client object = win32com.client.Dispatch("Excel.Application") object.Visible = 1 But when I try my application which is QeepIt.exe which is in the c:\ drive it is not running Any body tell me how to give path to open an exectable application in Dispatch modules I try like that object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") It give an error. From kent at kentsjohnson.com Thu Feb 8 16:09:09 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 08 Feb 2007 21:09:09 GMT Subject: Array delete In-Reply-To: <1170897199.005278.259190@p10g2000cwp.googlegroups.com> References: <45BC84B6.9080505@riddergarn.dk> <1170897199.005278.259190@p10g2000cwp.googlegroups.com> Message-ID: <45CB9172.9040000@kentsjohnson.com> azrael wrote: > if you are new to python then this will be easier to understand. if > you change this a liitle bit (depending on syntax) it should work in > any language. > just copy and paste to a .py file Yikes. If you are new to Python please ignore this un-Pythonic abomination. Check(listItem, temp) is just a long-winded way to say 'listItem in temp' and the whole thing could better be written as def main(): list, temp = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10], [] for item in list: if item not in temp: temp.append(item) print temp # print the new list where duplicates are removed For longer lists the set() method will probably be faster as this one searches temp for each item. Kent > > def main(): > list, temp = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10], [] > for i in range(len(list)): > if Check(list[i], temp) == 1: > temp.append(list[i]) > print temp # print the new list where duplicates are removed > > def Check(listItem,temp): > for i in range(len(temp)): > if listItem == temp[i]: > return 0 > return 1 > > if __name__=="__main__": > main() From nick at craig-wood.com Tue Feb 6 04:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 06 Feb 2007 03:30:07 -0600 Subject: Finding cpu time spent on my program References: <1170664629.719220.249570@k78g2000cwa.googlegroups.com> <1170703427.559432.155740@k78g2000cwa.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Feb 5, 2:37 am, "jm.sur... at no.spam.gmail.com" > wrote: > > I am trying to measure the time the processor spends on some > > operation, and I want this measure to not depend on the current load > > of the machine. > > One of the best ways to time small snippets of code is python's timeit > module. See the docs at > http://docs.python.org/lib/module-timeit.html Timeit is very cool, but it doesn't measure CPU time, it measure real time, eg on a linux box $ python -m timeit 'for i in xrange(100000): pass' 100 loops, best of 3: 11.4 msec per loop Now run 10 copies of the same program at once $ for i in `seq 10` ; do python -m timeit 'for i in xrange(100000): pass' & done 10 loops, best of 3: 24.4 msec per loop 10 loops, best of 3: 83.2 msec per loop 10 loops, best of 3: 83.4 msec per loop 10 loops, best of 3: 81.4 msec per loop 10 loops, best of 3: 83 msec per loop 10 loops, best of 3: 60.7 msec per loop 10 loops, best of 3: 47 msec per loop 10 loops, best of 3: 48.6 msec per loop 10 loops, best of 3: 42.3 msec per loop 10 loops, best of 3: 38.7 msec per loop > > Is there a way to measure the number of cpu cycles spent on my program > > alone irrespective of the current load etc of the machine. The most accurate way of measuring CPU usage under linux is getrusage, eg >>> import resource >>> def cpu_time(): ... return resource.getrusage(resource.RUSAGE_SELF)[0] ... Now try this out >>> def f(): ... for i in xrange(100000): ... pass ... >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.008001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.016001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.008001 You'll see the result is quantised to 4 ms (not sure what the .000001 bits are about!) 4ms is the clock rate of this machine, ie 250 Hz. This is a compile time option for the linux kernel and is usually set in the range 100 Hz to 1000 Hz. The kernel doesn't measure CPU usage more accurately than this. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py at yahoo.com.ar Sat Feb 10 18:28:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 20:28:47 -0300 Subject: Python 2.4 pdf Tutorial--Available References: <1hpzh.5885$4H1.5133@newssvr17.news.prodigy.net> Message-ID: En Sat, 10 Feb 2007 16:45:08 -0300, W. Watson escribi?: > I was able to download the 2.5 tutorial, but think I may need the 2.4 > tutorial (Guido van Rossum) if it exists. Anyone know where to find it? Go to http://docs.python.org/ and follow the link "Locate previous versions" -- Gabriel Genellina From l at l.com.au Wed Feb 28 02:59:29 2007 From: l at l.com.au (l) Date: Wed, 28 Feb 2007 18:59:29 +1100 Subject: Pyastro Message-ID: <45e5366e$0$16554$afc38c87@news.optusnet.com.au> Where can I find the code... I have checked starship, "the vaults" and googled for a long time. either they point to starshup(wiki) where it doesn't exists, or to dead links. Any help would be much appreciated. TIA From gagsl-py at yahoo.com.ar Mon Feb 12 00:48:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 02:48:51 -0300 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 02:24:54 -0300, Samuel Karl Peterson escribi?: > James Stroud on Sun, 11 Feb 2007 16:53:16 -0800 > didst step forth and proclaim thus: > >> agent-s wrote: >> > Basically I'm programming a board game and I have to use a list of >> > lists to represent the board (a list of 8 lists with 8 elements each). >> > I have to search the adjacent cells for existing pieces and I was >> > wondering how I would go about doing this efficiently. Thanks > Wow, maybe it's just me (I'm a pretty bad programmer) but this is > where list comprehensions begin to look unreadable to me. Here's a > C-like way to do it, (warning, untested in python): Just for fun, and to add one more way. This is a generator for adjacent indexes, that can be used to search for occupied cells, for locating a suitable next move, or whatever: py> def adj(i, j): ... for ni in (i-1, i, i+1): ... if ni not in range(8): continue ... for nj in (j-1, j, j+1): ... if nj not in range(8): continue ... if ni!=i or nj!=j: ... yield ni,nj ... py> py> print list(adj(4,3)) [(3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3), (5, 4 py> print list(adj(7,3)) [(6, 2), (6, 3), (6, 4), (7, 2), (7, 4)] py> print list(adj(4,7)) [(3, 6), (3, 7), (4, 6), (5, 6), (5, 7)] py> print list(adj(0,7)) [(0, 6), (1, 6), (1, 7)] -- Gabriel Genellina From __peter__ at web.de Sat Feb 3 09:07:02 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 15:07:02 +0100 Subject: compound statement from C "?:" References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> Message-ID: Jussi Salmela wrote: > bearophileHUGS at lycos.com kirjoitti: >> Jussi Salmela: >>> In this particular case you don't need the ternary operator: >>> print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) >> >> The last newline is probably unnecessary. This seems be a bit more >> readable: >> print "I saw", n, "car" + ("", "s")[n != 1] >> >> With Python 2.5 this looks better: >> print "I saw", n, "car" + ("" if n == 1 else "s") >> >> Or the vesion I like better: >> print "I saw", n, ("car" if n == 1 else "cars") >> >> Those () aren't necessary, but they help improve readability, and >> avoid problems with operator precedence too. That if has a quite low >> precedence. >> >> Bye, >> bearophile >> > This is getting weird but here's 2 more in the spirit of > "who needs the ternary operator - I don't!". And I'm starting to > wonder what the 'obvious way' (as in 'Zen of Python') to write > this would be. > > print "I saw %d car%s" % (n, {1:''}.get(n==1, 's')) > > print "I saw %d car%s" % (n, 's'*(n!=1)) Isn't that obvious? Don't do it in one line: if n == 1: print "I saw a car" else: print "I saw %d cars" % n I guess that most of us will have read, understood, and verified (are there any errors or cases that should be covered but aren't) those four lines faster than any of the "smart" constructs, including the official 2.5 ternary operator. Now modify all proposed versions to print I didn't see any cars I saw 7 cars missing for n=0 and n=-7, respectively, and you will see 1 light :-) Peter From steve at REMOVEME.cybersource.com.au Sun Feb 25 19:59:20 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 26 Feb 2007 11:59:20 +1100 Subject: newbie question References: Message-ID: On Sun, 25 Feb 2007 18:49:56 -0600, S.Mohideen wrote: >>>> asd={} >>>> asd={1:2,3:4,4:5} You don't need to initialise asd to an empty dict. >>>> print asd > {1: 2, 3: 4, 4: 5} > >>>> asd.has_key(3) > True >>>> asd.update() >>>> print asd > {1: 2, 3: 4, 4: 5} You're not updating it with anything. > what does asd.update() signifies. What is the use of it. Any comments > would help to understand it. Try this: >>> asd = {1: 2, 3: 4, 4: 5} >>> D = {1: -99, 7: -99} >>> asd.update(D) >>> asd {1: -99, 3: 4, 4: 5, 7: -99} -- Steven D'Aprano From martin at browns-nospam.co.uk Wed Feb 28 07:55:35 2007 From: martin at browns-nospam.co.uk (Martin Evans) Date: Wed, 28 Feb 2007 12:55:35 -0000 Subject: py2exe, library.zip and python.exe References: Message-ID: "Thomas Heller" wrote in message news:mailman.4509.1172662567.32031.python-list at python.org... > Martin Evans schrieb: >> I have converted a Python script using py2exe and have it set to not >> bundle >> or compress. The result is my exe and all the support files including >> library.zip (exactly as planned - nice job py2exe). >> >> Question: My py2exe application needs to be able to execute extra copies >> of >> python.exe. I have placed python.exe in the same directory. It obviously >> picks up the main python24.dll but how can I configure things so that it >> would use the same library.zip for all the library files? This would >> save >> me having two sets of files. >> >> (The py2exe application happens to be a twisted server app running as a >> service which has the ability to launch python scripts as a logged on >> user) >> >> Thanks, Martin. >> >> > You have to put library.zip on sys.path. Maybe you could create a site.py > file > in that directory which can do this, I assume the python.exe will try to > load that. > > There may be other possibilities as well. > > Thomas > Many thanks for the tip, it got me thinking. When python.exe is loaded, sys.path already had python24.zip in it so changing the specified library in py2exe from the default libary.zip to python24.zip solved it! Martin From thinker at branda.to Tue Feb 27 12:54:02 2007 From: thinker at branda.to (Thinker) Date: Wed, 28 Feb 2007 01:54:02 +0800 Subject: spawnl and waitpid In-Reply-To: <1172583591.509707.190240@p10g2000cwp.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> Message-ID: <45E4703A.9080504@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 naima.mans at gmail.com wrote: > i have tried as you said (cf bellow) and same result... is there > any link which explain how a server Web read script and send the > answer ? > ------------------------------------------------------------------------- > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > \python.exe","python","Main.py") print 'please wait...' > ret = os.waitpid(pid,0) You have missed my idea. Since os.waitpid will be blocked, you should print your message before calling os.waitpid(). - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF5HA61LDUVnWfY8gRAu8sAJ4n1dogsw7RzTxH8Ke3xnNX6gXnRQCeMOKf /dsGHttcJc/KGpx414I7rxw= =E3o7 -----END PGP SIGNATURE----- From sseebbaa123 at yahoo.com Fri Feb 9 14:17:51 2007 From: sseebbaa123 at yahoo.com (jiddu) Date: Fri, 09 Feb 2007 14:17:51 -0500 Subject: Thanks to all References: Message-ID: Thanks for all the input guys, I know it is difficult, but the calculators and statistic sites/books are missing some things which I need for my play so I guess I have no choice but to study up and work. When I was learning C++ I wrote some code to calculate simple things like probability of 1 or more player to have pocket pair in 9 handed game, its not finished but I realised I need to use some kind of database and someone suggested to me try python because it will be easier to learn. Again thanks for the help guys From sturlamolden at yahoo.no Wed Feb 28 09:16:56 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 28 Feb 2007 06:16:56 -0800 Subject: pyopengl vs directpython In-Reply-To: <54lg5sF20rdnnU2@mid.uni-berlin.de> References: <54lg5sF20rdnnU2@mid.uni-berlin.de> Message-ID: <1172672216.327157.223060@t69g2000cwt.googlegroups.com> On Feb 28, 2:59 pm, "Diez B. Roggisch" wrote: > OpenGL is platform-agnostic. If you ever want to reach people on linux or > macs, use that. > > Beyond that I've got no idea which is technically superior - but John > Carmack seems to favor OpenGL :) To ask which is better, OpenGL or Direct3D, is trolling with flame bait. Both systems deliver excellent 3D graphics, and which is faster depends on the video card. There are also PyOGRE and Panda3D (from Disney), and PyGame (the project seems to be torpid). John Carmack denounced the Direct3D8. DirectPython uses Direct3D9 and hides away the nasty COM-programming details. From gigs at hi.t-com.hr Wed Feb 28 09:28:49 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 28 Feb 2007 15:28:49 +0100 Subject: pyscripter Message-ID: im using pyscripter ide it is all alright till the next def class Checkbar(Frame): def __init__(self, parent=None, picks=[], side=LEFT, anchor=W): Frame.__init__(self, parent) self.vars = [] for pick in picks: var = IntVar() chk = Checkbutton(self, text=pick, variable=var) chk.pack(side=side, anchor=anchor, expand=YES) self.vars.append(var) # it is all alright till here, but if im going to write next # class method it wont go with tab for 4 fields # it goes here all the time (8 fields) if i remove for statement it all work fine From n00b at n00b.n00b.n00b Fri Feb 2 15:09:20 2007 From: n00b at n00b.n00b.n00b (Mister Newbie) Date: Fri, 02 Feb 2007 15:09:20 -0500 Subject: Is Python Right for Me? Message-ID: I want to make small, 2D games. I have no programming experience. Is Python a good choice? Thank you. From paul at boddie.org.uk Fri Feb 16 08:45:21 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Feb 2007 05:45:21 -0800 Subject: Approaches of interprocess communication In-Reply-To: <53lp57F1t2g4mU2@mid.uni-berlin.de> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <45d5a499$0$5995$b9f67a60@news.newsdemon.com> <1171631180.776312.258100@v33g2000cwv.googlegroups.com> <53lp57F1t2g4mU2@mid.uni-berlin.de> Message-ID: <1171633519.379342.306750@j27g2000cwj.googlegroups.com> On 16 Feb, 14:16, "Diez B. Roggisch" wrote: > > You can't leave WSDL out of SOAP Yes you can, since they're two different things. What you probably meant was that you can't leave WSDL out of "big architecture", W3C standards-intensive Web services. Of course, RPC-style SOAP without the contracts imposed by WSDL may remove some of the attractions for some people (who really should consider CORBA, anyway), but then there's always document-oriented SOAP, although if you don't want the baggage associated with routing and other things, plain XML messaging would be easier. And there's always XMPP if you want stuff like routing and a standard that isn't undergoing apparently continuous change. Paul From grante at visi.com Wed Feb 7 15:39:17 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 07 Feb 2007 20:39:17 -0000 Subject: Can somebody give me a python code for this? References: Message-ID: <12ske7ls7meuvb4@corp.supernews.com> On 2007-02-07, John wrote: > Given an array of elements, look at it as a binary tree. Start > at the last interior node, and downheap it. Then downheap the > previous interior node, and continue in this fashion, up to > the root. I'll give you python code for that if you give me your degree in the remotely possible case where you do graduate... -- Grant Edwards grante Yow! Is this BOISE?? at visi.com From jorge.vargas at gmail.com Wed Feb 21 17:58:38 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 21 Feb 2007 18:58:38 -0400 Subject: CherryPy/Turbogears on server not controlled by me In-Reply-To: <45DAF7F0.1080503@bryant.edu> References: <45DAF7F0.1080503@bryant.edu> Message-ID: <32822fe60702211458u15b0e9a6r6217d8b55c0260f5@mail.gmail.com> On 2/20/07, Brian Blais wrote: > Hello, > > I was wondering if there is a way to run CherryPy/Turbogears on a server that I don't > have root access to. I have never run ANY webapp as root. you should follow that advice. in fact don't run any server as root. > If I just choose a random port, I think the security guys on > the server would get annoyed at me. What are my options? I can talk to the admin, why will the port be a problem are they all closed? if so well the only way is to poke a whole in the firewall and you can't do that without the boring talk to the admin. > but they are very slow/reluctant to make changes...it took me a couple months to get > them to upgrade to 2.4 from 2.3 last year, even when 2.5 was out. > > > thanks, > > Brian Blais > > -- > ----------------- > > bblais at bryant.edu > http://web.bryant.edu/~bblais > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py at yahoo.com.ar Tue Feb 6 20:32:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 22:32:47 -0300 Subject: Dictionary/Hash question References: <2adc542f0702061531g7504de83ob01b56933794a37e@mail.gmail.com> <2adc542f0702061718h5a943312id61c3ac77c074a95@mail.gmail.com> Message-ID: En Tue, 06 Feb 2007 22:18:07 -0300, Sick Monkey escribi?: > I have never seen this "with open(fname,'r') as finput:" > > It is actually throwing an error . Do I have to import a special > library to > use this? > > File "dictNew.py", line 23 > with open(fname,'r') as finput: > ^ > SyntaxError: invalid syntax Oh, sorry. You need two things: - Python 2.5 - include this line at the very beginning of your script: from __future__ import with_statement If you're using an earlier version, you can write: finput = open(fname,'r') try ... finally finput.close() (Or just omit the try/finally and rely on the garbage collector, but it's not the recommended practice, specially when external resources are involved, like files). -- Gabriel Genellina From grante at visi.com Tue Feb 13 10:42:34 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 13 Feb 2007 15:42:34 -0000 Subject: Mulig SPAM: float print formatting References: <4OjAh.22047$NI1.19760@newsfe14.lga> Message-ID: <12t3n3a2l68hne4@corp.supernews.com> On 2007-02-13, hg wrote: > NOSPAM plz wrote: >>> Considering the float 0.0, I would like to print 00.00. >>> >>> I tried '%02.02f' % 0.0 ... but I get 0.00 >> Try this: >> >> a = 45.45 # the floating number >> >> print "some text", >> print a, >> print "some text again" > Sorry, > > must be very slow or not enough coffee yet... Don't worry. I do know what you did wrong and how to fix it, and I have absolutely no idea what "NOSPAM plz" is trying to say either. -- Grant Edwards grante Yow! I'm in a twist at contest!! I'm in a visi.com bathtub! It's on Mars!! I'm in tip-top condition! From B.Steinbrink at gmx.de Thu Feb 8 14:06:34 2007 From: B.Steinbrink at gmx.de (=?iso-8859-1?b?Qmr2cm4=?= Steinbrink) Date: Thu, 8 Feb 2007 19:06:34 +0000 (UTC) Subject: begin to parse a web page not entirely downloaded References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> <45cb63d4$0$6842$4d3efbfe@news.sover.net> <1170958856.700750.3080@a75g2000cwd.googlegroups.com> Message-ID: On Thu, 08 Feb 2007 10:20:56 -0800, k0mp wrote: > On Feb 8, 6:54 pm, Leif K-Brooks wrote: >> k0mp wrote: >> > Is there a way to retrieve a web page and before it is entirely >> > downloaded, begin to test if a specific string is present and if yes >> > stop the download ? >> > I believe that urllib.openurl(url) will retrieve the whole page before >> > the program goes to the next statement. >> >> Use urllib.urlopen(), but call .read() with a smallish argument, e.g.: >> >> >>> foo = urllib.urlopen('http://google.com') >> >>> foo.read(512) >> ' ... >> >> foo.read(512) will return as soon as 512 bytes have been received. You >> can keep caling it until it returns an empty string, indicating that >> there's no more data to be read. > > Thanks for your answer :) > > I'm not sure that read() works as you say. > Here is a test I've done : > > import urllib2 > import re > import time > > CHUNKSIZE = 1024 > > print 'f.read(CHUNK)' > print time.clock() > > for i in range(30) : > f = urllib2.urlopen('http://google.com') > while True: # read the page using a loop > chunk = f.read(CHUNKSIZE) > if not chunk: break > m = re.search('', chunk ) > if m != None : > break > > print time.clock() > > print > > print 'f.read()' > print time.clock() > for i in range(30) : > f = urllib2.urlopen('http://google.com') > m = re.search('', f.read() ) > if m != None : > break A fair comparison would use "pass" here. Or a while loop as in the other case. The way it is, it compares 30 times read(CHUNKSIZE) against one time read(). Bj?rn From fabiofz at gmail.com Mon Feb 19 13:55:20 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 19 Feb 2007 15:55:20 -0300 Subject: PyDev on Mac In-Reply-To: <1171910501.783846.196300@v45g2000cwv.googlegroups.com> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> <1171910501.783846.196300@v45g2000cwv.googlegroups.com> Message-ID: On 19 Feb 2007 10:41:41 -0800, Ahmer wrote: > > On Feb 18, 4:50 am, "Diez B. Roggisch" wrote: > > Ahmer schrieb: > > > > > I've been trying to set up PyDev on my new MacBook Pro, but i have not > > > had an success. > > > > > Could you please help! > > > > Just wait until my crystal ball comes back from the cleaners, and I will > > start looking at your problem. > > > > As you can lay back and do nothing while that happens, I suggest you > > take this highly entertaining read: > > > > http://www.catb.org/~esr/faqs/smart-questions.html > > > > Diez > > The error I am getting is: > > Check your error log for more details. > > More info can also be found at the bug report: > > http://sourceforge.net/tracker/index.php?func=detail&aid=1523582&group_id=85796&atid=577329 > > > I am trying to use Jython since I am mainly a Java programmer. > > And what's in your error log? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffwatkins2000 at gmail.com Wed Feb 28 12:15:36 2007 From: jeffwatkins2000 at gmail.com (jeffwatkins2000 at gmail.com) Date: 28 Feb 2007 09:15:36 -0800 Subject: Eric on XP for Newbie In-Reply-To: <1d9au31u0gabx$.bmnr6jzorw6m.dlg@40tude.net> References: <1172679222.026525.248430@a75g2000cwd.googlegroups.com> <1d9au31u0gabx$.bmnr6jzorw6m.dlg@40tude.net> Message-ID: <1172682935.812867.239660@k78g2000cwa.googlegroups.com> On Feb 28, 4:27 pm, Alan Franzoni wrote: > Il 28 Feb 2007 08:13:42 -0800, jeffwatkins2... at gmail.com ha scritto: > > [cut] > > Forget the tars. > > http://www.quadgames.com/download/pythonqt/ > > Get the two EXEs here. BTW, I don't think Eric3 is a really good IDE on > Windows (yet). Try something like SPE, or Scite, or any other editor like > UltraEdit32. > Thanks I've installed SPE. But what now? How do I run it? It doesn't appear in "all programs" and ther's no .exe file that I can find From johnjsal at NOSPAMgmail.com Thu Feb 1 14:54:09 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Feb 2007 14:54:09 -0500 Subject: Sorting a list In-Reply-To: <45c243a7$0$3020$426a34cc@news.free.fr> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> Message-ID: <45c245e1$0$31965$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: > John Salerno a ?crit : >> Hi everyone. If I have a list of tuples, and each tuple is in the form: >> >> (year, text) as in ('1995', 'This is a citation.') >> >> How can I sort the list so that they are in chronological order based >> on the year? > > Calling sort() on the list should just work. Amazing, it was that easy. :) From gerald.kaszuba at gmail.com Sat Feb 10 04:46:43 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 10 Feb 2007 01:46:43 -0800 Subject: pycallgraph 0.1.0 In-Reply-To: References: <108b15f0702090719i170c76b9jd17770b4afb53a25@mail.gmail.com> Message-ID: <1171100803.055476.168130@v33g2000cwv.googlegroups.com> > http://pycallgraph.slowchop.com/files/examples/mongballs-client.png > > indicate you are subject to the slashdot effect? Steve, No /. effect :) I rearranged some files around because of the new version of pycallgraph. The new preview image is: http://pycallgraph.slowchop.com/pycallgraph/wiki/RegExpExample Gerald From cheekymonkey4_u at yahoo.com Mon Feb 19 18:28:18 2007 From: cheekymonkey4_u at yahoo.com (Flash Games) Date: Mon, 19 Feb 2007 23:28:18 GMT Subject: Free Flash Games Message-ID: Free Flash Games http://www.clipplay.com/ fun videos games and more. Fun flash games. Free flash games... From paul at boddie.org.uk Tue Feb 20 17:13:16 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Feb 2007 14:13:16 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: <1172008387.851412.181530@p10g2000cwp.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> Message-ID: <1172009596.807348.36110@s48g2000cws.googlegroups.com> Jay Tee wrote: > > Paul, thanks for this, I didn't realize the scope of the situation. I > agree with your assessment to the extent that I understand what the > whole python 3.0 thing is about. I don't know if I've delimited the scope of any situation, really. However... [...] > The fact that there are three (or > four depending if you count Linz V4) different Oberon System > implementations, and several different compilers, and even four or > five separate dialects of Oberon with none of them appearing to be > really "official", [...] The fortunate thing about different Python implementations and in contrast to a lot of other languages and their implementations is that the most actively developed Python implementation, CPython, is very portable and is present on all major operating systems of consequence (capable of running it). Other languages have suffered because there'd be a UNIX version and then a version for Windows or the Mac which wasn't as well maintained, or perhaps no version at all for one or more of these platforms. So with Python, even if one implementation is lagging behind (eg. Jython) there's still likely to be some deployment solution on one's operating system of choice, given some level of flexibility. Where incompatibilities may arise with Python implementations is in the level of support for recent language developments and additions. Again, CPython's portability prevents this from becoming an operating system issue, but we see rifts between implementations targeting different runtime platforms, and whilst CPython 2.x and CPython 3.x may continue to cover similar operating systems (although a desire to drop support for various operating systems was stated), it's the rift between them that presents the risk to any common notion of what Python actually is. Paul From nszabolcs at gmail.com Wed Feb 14 16:07:57 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 14 Feb 2007 13:07:57 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Sergey Dorofeev wrote: > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> (1,)+[1] > Traceback (most recent call last): > File "", line 1, in > TypeError: can only concatenate tuple (not "list") to tuple > >>> [1]+(1,) > Traceback (most recent call last): > File "", line 1, in > TypeError: can only concatenate list (not "tuple") to list > >>> > > Its ugly and boring. what? for me it works fine: >>> (1,)+tuple([1]) (1, 1) >>> [1]+list((1,)) [1, 1] also >>> L=[1] >>> L.extend((1,)) >>> L [1, 1] From kavithapython at yahoo.co.in Mon Feb 19 06:02:29 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Mon, 19 Feb 2007 11:02:29 +0000 (GMT) Subject: writing a file:newbie question Message-ID: <933431.84534.qm@web7806.mail.in.yahoo.com> Hi, i have a file test.txt and it contains a list of strings say,,, "a","b","c","d","a1","b1","c1","d1","a2","b2","c2","d2", i would like to write the file as "a","b","c","d" "a1","b1","c1","d1 "a2","b2","c2","d2" and would like to delete the comma at the end. if soneone knows pls help me,,, kavitha --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From exhuma at gmail.com Fri Feb 16 08:06:20 2007 From: exhuma at gmail.com (exhuma.twn) Date: 16 Feb 2007 05:06:20 -0800 Subject: Approaches of interprocess communication In-Reply-To: <45d5a499$0$5995$b9f67a60@news.newsdemon.com> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <45d5a499$0$5995$b9f67a60@news.newsdemon.com> Message-ID: <1171631180.776312.258100@v33g2000cwv.googlegroups.com> On Feb 16, 1:33 pm, Duncan Grisby wrote: > In article <1171620696.577982.283... at m58g2000cwm.googlegroups.com>, > > exhuma.twn wrote: > >Supposing you have two separate processes running on the same box, > >what approach would you suggest to communicate between those two > >processes. > > [...] > > >* Webservices > > Advantage: Relatively easy to use, can work across different > >languages > > Disadvantage: Even more overhead on the TCP/IP side that simple > >sockets, as really bulky SOAP messages need to be passed around. > > >* CORBA -- similar to webservices but more complicated to code. > > Lots of people say that, but I don't think it's true. Obviously as the > maintainer of a CORBA implementation I'm biased, but take a look at > some examples of code that implement SOAP clients and servers and > compare it to similar CORBA code. Especially in Python, the SOAP code > tends to be incredibly verbose and complex, and the CORBA code really > small and simple. > > My recommendation would be that for simple communications where > performance isn't important use XML-RPC; for more complex cases where > performance is a bit more important but you don't need anything except > Python, use Pyro; for cases where performance is particularly > important and/or you need cross-language communications, use CORBA. Maybe this line of mine was a bit too condensed ;) I fully agree with you on what you say about CORBA. It's just that for most people IDL looks a bit out of place. Especially because it resembles C. But once you actually wrote a few projects using CORBA, you actually begin to see it's elegance ;) I find Webservices "easier" as you can (although it's not recommendable) leave out the WSDL part. And some implementations actually generate the WSDL for you. But it's true, comparing WSDL and IDL I'd rather write some IDL than WSDL ;) But, returning back to topic, I first want to thank you all for your input. I appreciate all the ideas. Especially the idea of using the "cmd" module for sockets. That sound's very intriguing and I will very likely play around with that. But also PYRO seems quite useful. About "Linda": Am I right that it looks very similar to "JavaSpaces"? If yes, are there any funcdamental differences between those two? From wolf_tracks at invalid.com Thu Feb 8 18:35:38 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 08 Feb 2007 15:35:38 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> Message-ID: <45CBB3CA.7010501@invalid.com> Robert Kern wrote: > W. Watson wrote: >> Robert Kern wrote: >>> W. Watson wrote: >>> >>>> I did a search in the python24 folder for sys.exec* (in c:\python24), but >>>> came up with nothing. [nothing in a search of c:--sys.exec*] I have two >>>> python folders, c:\python24 and c:\python25. The contents of both folders >>>> look fairly similar and each have a python.exe. I do not use a PIL or >>>> Numeric in 2.5. >>> I'm sorry. sys is a module. I meant for you to execute the following Python code: >>> >>> import sys >>> print sys.executable >>> >> I'm savvy about a number of languages, but not yet about Python. What py >> file will allow this to be executed? > > Just the lines between the comments here: > > #### > import sys > print sys.executable > #### > > I recommend going through the tutorial first, before worrying about Numeric or > PIL. Here is the URL for the 2.4.4 version: > > http://www.python.org/doc/2.4.4/tut/tut.html > Here's the program I ran. ### begin #!/usr/bin/python # Check mysys import sys print sys.executable ### end It put up a black screen in a flash and disappeared. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two million years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From nagle at animats.com Sun Feb 25 15:54:02 2007 From: nagle at animats.com (John Nagle) Date: Sun, 25 Feb 2007 20:54:02 GMT Subject: BeautifulSoup modified to use weak refs and avoid circular links. In-Reply-To: References: Message-ID: <45E1FEE1.8080901@animats.com> John Nagle wrote: > Are weak refs slower than strong refs? I've been considering making the > "parent" links in BeautifulSoup into weak refs, so the trees will release > immediately when they're no longer needed. In general, all links back > towards the root of a tree should be weak refs; this breaks the loops > that give reference counting trouble. > > John Nagle I just finished converting BeautifulSoup to use weak back references. All that's necessary is to make the "parent", "previous", "previousSibling", and "tagStack" links into weak proxy references. Those are the "backlinks" of the Beautiful Soup tree; once they're weak links, BeautifulSoup then becomes loop-free and GC in debug mode reports zero garbage. This is useful, because BeautifulSoup's backlinks create huge amounts of collectable garbage, leading to frequent GC cycles. The "weakref" module could use some support functions. If you try to create a weakref proxy from a weakref proxy, or from "None", you get an exception, which is not usually what you want. It's more useful to pass through "None" or an existing weakref proxy. So I wrote the function below, which makes it much easier to convert code to use weak proxy references. "weakref.proxy()" probably should work that way. Weakref proxies are supposed to be transparent, but they're not quite transparent enough. Patches to BeautifulSoup are below. John Nagle 59a60,80 > import weakref # Weak references for previous, parent, previousSibling > # > # Weakref allocation control > # > # The following links are always weak references, to avoid internal referenc > # require extra garbage collection. > # self.parent > # self.previous > # self.previousSibling > # These are all "back links". > # > # backref -- create a weak reference as a back pointer > # > # Generates a weakref proxy, but handles input of "none" or an existing weak > # > def backref(p) : > if p == None : # if none > return(None) # then none > if isinstance(p,weakref.ProxyType) or isinstance(p,weakref.CallableProxyTyp > return(p) > return(weakref.proxy(p)) # otherwise a new weakref 60a82 > # 79,80c101,102 < self.parent = parent < self.previous = previous --- > self.parent = backref(parent) > self.previous = backref(previous) 85c107 < self.previousSibling = self.parent.contents[-1] --- > self.previousSibling = backref(self.parent.contents[-1]) 127c149 < self.nextSibling.previousSibling = self.previousSibling --- > self.nextSibling.previousSibling = backref(self.previousSibling) 157c179 < newChild.parent = self --- > newChild.parent = backref(self) 161c183 < newChild.previous = self --- > newChild.previous = backref(self) 164c186 < newChild.previousSibling = previousChild --- > newChild.previousSibling = backref(previousChild) 166c188 < newChild.previous = previousChild._lastRecursiveChild() --- > newChild.previous = backref(previousChild._lastRecursiveChild()) 190c212 < newChild.nextSibling.previousSibling = newChild --- > newChild.nextSibling.previousSibling = backref(newChild) 194c216 < newChildsLastElement.next.previous = newChildsLastElement --- > newChildsLastElement.next.previous = backref(newChildsLastElemen 1052c1074 < self.tagStack.append(tag) --- > self.tagStack.append(backref(tag)) 1074c1096 < self.previous = o --- > self.previous = backref(o) 1167c1189 < self.previous = tag --- > self.previous = backref(tag) From skip at pobox.com Thu Feb 15 10:46:00 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 15 Feb 2007 09:46:00 -0600 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <17876.32824.293063.624185@montanaro.dyndns.org> Sergey> posix.stat_result is CLASS, not regular tuple. I believe it morphed from being a tuple though. I wasn't suggesting that there is some other way to approximate records. I was trying to demonstrate the use of a tuple as a record. It eventually became so compelling that a new struct_time type was created. It works both like a tuple as a class. The notion of tuples as records in Python is not new: http://mail.python.org/pipermail/python-list/1999-December/thread.html Search for "super tuples". Skip From mbm at mediamonger.ch Sun Feb 11 08:47:31 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Sun, 11 Feb 2007 14:47:31 +0100 Subject: How to find all the same words in a text? In-Reply-To: References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: <45CF1E73.5040702@mediamonger.ch> In order to find all the words in a text, you need to tokenize it first. The rest is a matter of calling the count method on the list of tokenized words. For tokenization look here: http://nltk.sourceforge.net/lite/doc/en/words.html A little bit of warning: depending on what exactly you need to do, the seemingly trivial taks of tokenizing a text can become quite complex. Enjoy, Ma?l Neil Cerutti schrieb: > On 2007-02-10, Johny wrote: >> I need to find all the same words in a text . >> What would be the best idea to do that? >> I used string.find but it does not work properly for the words. >> Let suppose I want to find a number 324 in the text >> >> '45 324 45324' >> >> there is only one occurrence of 324 word but string.find() finds 2 >> occurrences ( in 45324 too) >> >> Must I use regex? >> Thanks for help > > The first thing to do is to answer the question: What is a word? > > The second thing to do is to design some code that can find > words in strings. > > The last thing to do is to search those actual words for the word > you're looking for. > From fuzzyman at gmail.com Fri Feb 16 10:21:35 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Feb 2007 07:21:35 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> <1171636975.653884.122850@p10g2000cwp.googlegroups.com> Message-ID: <1171639295.615356.230560@s48g2000cws.googlegroups.com> On Feb 16, 3:00 pm, "Edward K Ream" wrote: > > So you only have one codebase to maintain and you can still use print... > > Not if the theorum is correct. > > > It may be true that you won't be able to write code that runs > > untranslated on 2 and 3. > > That's my definition of a common code base. That is the content of the > theorum. > Ok - in which case it is very limited. > > That doesn't stop you writing code for Python > > 2.X, then translating a version for Python 3. (Uhm... indeed that's the > > point of 2to3.) > > That is not what I would call a common code base. But it is what I call a common code base. We are at an impasse. :-) > The developer would have > to run the translater every time the code changed. And if the Python 3.0 > code were considered the 'master' code, the developer would need a 3to2 > translater. > > Either disprove the theorum or give up the notion of having a common code > base that uses print. > Yes the use of print is changing in a backwards incompatible way, no one is disputing that. Personally I wish it wasn't, print 'feels like a statement' to me. But it's not the end of the world and it is *definitely* going to be able to be handled by 2to3. It's also not about to change. Fuzzyman http://www.voidpsace.org.uk/python/articles.shtml > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream... at charter.net > Leo:http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- From lists at fabis-site.net Thu Feb 22 10:36:35 2007 From: lists at fabis-site.net (Fabian Steiner) Date: Thu, 22 Feb 2007 16:36:35 +0100 Subject: How to test whether a host is reachable? In-Reply-To: References: Message-ID: Hello! Chris Mellon wrote: > On 2/22/07, Fabian Steiner wrote: >> [...] >> Now I am wondering if there isn't any better method which would be more >> general. In fact, I think of something like a python version of ping >> which only tries to send ICMP packets. However, I don't know what the >> code has to look like then. Any ideas or suggestions? >> > > This is the only reliable way of telling if you can communicate with a > service on a machine. A ping will tell you if it's connected to the > network, but not if it is actually providing any services. > > If you really want a ping, the common way is to just execute the systems > ping. Ok, obviously, my approach was already the best way to achive this aim. Thanks for you help, Fabian From oliphant.travis at ieee.org Thu Feb 22 12:42:38 2007 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Thu, 22 Feb 2007 10:42:38 -0700 Subject: export an array of floats to python In-Reply-To: References: Message-ID: Peter Wuertz wrote: > Hi, > > I'm writing a C module for python, that accesses a special usb camera. > This module is supposed to provide python with data (alot of data). Then > SciPy is used to fit the data. > Which version of scipy are you using? > My question is, how to make python read from a C array? By reading the > documentation, one could get the impression that PyBufferObjects do that > job. > > http://docs.python.org/api/bufferObjects.html > > It says: > "Two examples of objects that support the buffer interface are strings > and arrays." > > Where this function looks promising: > "PyBuffer_FromMemory - Return a new read-only buffer object that reads > from a specified location in memory, with a specified size." > > All right, lets imagine I created a PyBufferObject from my float array > in the C module, and passed it to python. How about creating an array directly from your float array using PyArray_SimpleNewFromData (the NumPy C-API) or PyArray_FromDimsAndData (the Numeric C-API). -Travis From gagsl-py at yahoo.com.ar Wed Feb 14 03:16:29 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 05:16:29 -0300 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> <1171437825.977798.249420@q2g2000cwa.googlegroups.com> Message-ID: En Wed, 14 Feb 2007 04:23:46 -0300, jm.suresh at no.spam.gmail.com escribi?: > I am OK with calls being stacked, but I wondering will the local > variables be stacked given that return statement is followed by the > function call? > > def test(): > x = 22 > y = 33 > z = x+y > return anotherFunction(z) > > In this function will all the local variables (x,y,z) be pushed into > the stack before calling anotherFunction(z) or Python will find out > that the locals are no longer needed as anotherFunction(z) is just > returned? Not exactly like "pushed into the stack", but there exists a frame object, and it contains references to its local variables, and will be alive until anotherFunction returns. From inside anotherFunction you can even inspect those variables: py> def test(): ... x = 22 ... y = 33 ... z = x+y ... return anotherFunction(z) ... py> def anotherFunction(z): ... print "previous frame:", sys._getframe(1).f_locals ... py> test() previous frame: {'y': 33, 'x': 22, 'z': 55} So x,y,z will still be there until anotherFunction actually returns to test, and the frame object is disposed. For a highly recursive function, that's bad news. For debugging normal programs, that's good news; the cgitb module, by example, is able to show the values for local variables in all previous frames when an exception is raised. -- Gabriel Genellina From stj911 at rock.com Fri Feb 23 14:06:04 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 23 Feb 2007 11:06:04 -0800 Subject: Who has not attended these free tutorial courses ? Message-ID: <1172257564.241642.300140@m58g2000cwm.googlegroups.com> "President Bush ... you are under arrest" - 911 truth video by Dr Morgan Reynolds, Former Chief Economist under Bush You can also save them by right clicking the links and saving them as flv files and download a free flv player. google is your best friend. "Bush Administration Insider Says U.S. Government Behind 911.flv" "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w" <--- key video "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http:// youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" "911 Truth, Consequences of Revealing the Truth about 911.flv" "http:// youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv" "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax- v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" "Bush gets caught off guard on 9/11 prior knowledge question.flv" "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" "Bush gets caught off guard on 911 prior knowledge question.flv" "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" "World Trade Center -- Controlled Demolition.flv" "http:// v187.youtube.com/get_video?video_id=87fyJ-3o2ws" "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv" "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90" The Answer: Why do they hate our freedoms :)))) From thewritersclub at gmail.com Thu Feb 15 00:03:31 2007 From: thewritersclub at gmail.com (thewritersclub at gmail.com) Date: 14 Feb 2007 21:03:31 -0800 Subject: AUX File Writing Error Message-ID: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> Hi guys! I'm new to python so please be aware that I'm probably missing the obvious. Here's my problem... >>> t = "AUX" >>> f = open('c:\\' + t + '.csv', 'a') Traceback (most recent call last): File "", line 1, in f = open('c:\\' + t + '.csv', 'a') IOError: [Errno 2] No such file or directory: 'c:\\AUX.csv' >>> t = "A" >>> f = open('c:\\' + t + '.csv', 'a') >>> As you can see python has no problem opening a file when t = "A", but not when it is "AUX" (no "A.csv" or "AUX.csv" exists on the C:\ folder prior to when these are run). Is there any way I can create an "AUX.csv" file without the error? Thanks, Ryan From indiankid at gmail.com Fri Feb 2 19:33:28 2007 From: indiankid at gmail.com (andy king) Date: Fri, 2 Feb 2007 16:33:28 -0800 Subject: how to merge strings to a line Message-ID: Hello, I have a file that contains the following: my name is larry is in 10th grade got A+ in math my name is john is in 10th grade got A+ in english my name is peter [...] i need to convert the file to look like: my name is larry my name is larry is in 10th grade --> (my name is larry is common and needs to be prepend to the string. my name is larry got A+ in match my name is larry i am good --> (this is an addition) my name is john my name is john is in 10th grade my name is john got A+ in english my name is john i am good I would really appreciate if someone could help me out with the logic here. any tips/direction would be helpful. -- --andy -------------- next part -------------- An HTML attachment was scrubbed... URL: From richard_l at latter.demon.co.uk Fri Feb 23 03:31:26 2007 From: richard_l at latter.demon.co.uk (richard_l at latter.demon.co.uk) Date: 23 Feb 2007 00:31:26 -0800 Subject: How can I track/monitor an application and system resources. In-Reply-To: References: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> Message-ID: <1172219486.020466.54560@z35g2000cwz.googlegroups.com> Hello, Many thanks for your advice so far! The phone reference is actually because the target device is WM 5.0. I've found a python port Pyce that will run on this platform. We have a target application that runs on this platform which we would like to develop some automated tests for. The application is written in VC++ and we're using python to stress test it! Many thanks again! R. On 22 Feb, 20:07, Tim Golden wrote: > richar... at latter.demon.co.uk wrote: > > Hello All, > > > I'm a newbie to Python! > > > I am trying to develop a program that monitors the performance of an > > application. The kind of information I am interested in is the CPU/ > > Process/Thread and memory performance. Specifically, I would like to > > track the following > > > CPU usage > > Used Memory on Phone > > Free Memory on Phone > > Number of Processes running > > Number of threads running > > Number of Filehandles currently open > > Memory used by a process/thread > > Process/Thread CPU activity. > > > All this under Windows > > Not sure about the "... on Phone" bit. Assuming you're > on a supported platform, sounds like you want to look > at the WMI stuff, in particular Win32_PerfFormattedData[1]. > There are examples around the web, usually in VBS style. > They're easy enough to translate into Python, either > using the win32com module[2] directly, or using my WMI > helper module[3]. > > [1]http://msdn2.microsoft.com/en-us/library/aa394253.aspx > [2]http://pywin32.sf.net > [3]http://timgolden.me.uk/python/wmi.html > > TJG- Hide quoted text - > > - Show quoted text - From jjl at pobox.com Fri Feb 23 16:53:29 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 23 Feb 2007 21:53:29 GMT Subject: timeout in urllib.open() References: Message-ID: <87vehsy204.fsf@pobox.com> Steve Holden writes: [...] > This has recently been discussed on python-dev. It's likely that > certain libraries will acquire a timeout keyword argument in the next > release, but only if someone is concerned enough to develop the > appropriate patches - the principle appears to be accepted. I didn't read the recent python-dev thread, but ISTM this has been true since the socket timeout feature was added (Python 2.3?). Apparently so far nobody wanted it enough to actually implement it. John From timr at probo.com Fri Feb 2 01:50:56 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 02 Feb 2007 06:50:56 GMT Subject: win32com.client References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170379374.589869.158610@p10g2000cwp.googlegroups.com> <1170379682.386807.99880@a34g2000cwb.googlegroups.com> Message-ID: "vithi" wrote: >Hi, >I use python for window. If you are saying win32com in part of the >python then you are wrong. Look, you aren't paying attention. No one has said win32com is part of Python. What everyone has said is that win32com is part of the "Python for Windows extensions" by Mark Hammond. They used to be called "win32all" and are now called "pywin32". http://sourceforge.net/projects/pywin32 The download includes a huge number of useful Python tools for Windows users, of which win32com is just one. >Here is a prove:- >>>> import win32com > >Traceback (most recent call last): > File "", line 1, in > import win32com >ImportError: No module named win32com >>>> > >you try in your computer It works just fine in my computer, because I have "pywin32" installed. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From thebrasse at brasse.org Thu Feb 15 10:54:45 2007 From: thebrasse at brasse.org (=?iso-8859-1?B?TWF0dGlhcyBCcuRuZHN0cvZt?=) Date: 15 Feb 2007 07:54:45 -0800 Subject: filecmp.cmp() cache Message-ID: <1171554885.517477.316470@s48g2000cws.googlegroups.com> Hello! I have a question about filecmp.cmp(). The short code snippet blow does not bahave as I would expect: import filecmp f0 = "foo.dat" f1 = "bar.dat" f = open(f0, "w") f.write("1:2") f.close() f = open(f1, "w") f.write("1:2") f.close() print "cmp 1: " + str(filecmp.cmp(f0, f1, False)) f = open(f1, "w") f.write("2:3") f.close() print "cmp 2: " + str(filecmp.cmp(f0, f1, False)) I would expect the second comparison to return False instead of True. Looking at the docs for filecmp.cmp() I found the following: "This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures.". I guess that this is the reason for my test case failing. Is there someone here that can tell me how I should invalidate this cache? If that is not possible, what workaround could I use? I guess that I can write my own file comparison function, but I would not like to have to do that since we have filecmp. Any ideas? Regards, Mattias From carl.douglas at gmail.com Mon Feb 19 05:51:05 2007 From: carl.douglas at gmail.com (Carl Douglas) Date: Mon, 19 Feb 2007 21:51:05 +1100 Subject: Embedded and extending python 2.5: trouble with __main__ in PyRun_SimpleFileExFlags? Message-ID: <6f7c837c0702190251o6e48a4abx7d8309a885deba13@mail.gmail.com> Hi Python fans, I am developing a DLL that is loaded by a host application on windows. I'm using python 2.5. My DLL uses an embedded python interpreter which can access the host application through an API which I have exposed using SWIG 1.3.31. Therefore I have both extended and embedded Python at once: the SWIG generated code is statically linked into my DLL, and one of the functions in my DLL executes PyRun_SimpleFile. Using python25_d.dll, I stepped through some python code to understand what is happening, and it appears that PyRun_SimpleFile is returning -1 because python cannot create the module __main__. Here's the code from pythonrun.c: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) { PyObject *m, *d, *v; const char *ext; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; . . . } BTW, PyImport_AddModule fails because deeper down a dictionary check fails: if (!PyDict_Check(op)) return NULL; Can someone suggest what I need to do to get this to work? Here are the relevant lines from my code: if (GetOpenFileName(&ofn)==TRUE) { Py_Initialize(); init_mymodule(); // SWIG generated method PyObject* PyFileObject = PyFile_FromString(ofn.lpstrFile, "r"); if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), ofn.lpstrFile)==-1) { MessageBox(NULL, "error running script", "Python", MB_ICONERROR); } Py_DECREF(PyFileObject); Py_Finalize(); } Thanks. From mail at microcorp.co.za Wed Feb 21 00:57:06 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 21 Feb 2007 07:57:06 +0200 Subject: Weird result returned from adding floats depending on order I add them References: Message-ID: <008601c7557d$1ebb1ac0$03000080@hendrik> "joanne matthews (RRes-Roth)" wrote: 8<---------------------------------------- > Can anyone tell me whats going on > and how I can avoid the problem. Thanks Don't know about the first question. Would avoid it by using ints and asking for percentages... - Hendrik From klachemin at comcast.net Thu Feb 1 11:46:37 2007 From: klachemin at comcast.net (Kamilche) Date: 1 Feb 2007 08:46:37 -0800 Subject: Quad Perspective Transformation Message-ID: <1170348396.754807.206560@m58g2000cwm.googlegroups.com> I have a need to tile a bitmap across an arbitrary quadrilateral, and apply perspective to it. The Python Imaging Library (PIL) has an undocumented function that might work, but I can't figure out how to make it work. You're supposed to pass it 8 parameters, a b c d e f g h . What I want is to take a rectangular texture map and 'flop it down on the floor' - pinch in the left and right with perspective, and squash down the top with perspective. I've modified those 8 parameters and examined the results, but that hasn't brought me any closer to my goal. The PIL function is this: im2 = im.transform(im.size, Image.PERSPECTIVE, (1, 0, 0, 0, 1, -100, 0, .001), Image.BILINEAR) Here's hoping someone can shed some light on this function! From mmanns at gmx.net Fri Feb 23 23:42:00 2007 From: mmanns at gmx.net (Martin Manns) Date: Fri, 23 Feb 2007 23:42:00 -0500 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> Message-ID: On Fri, 23 Feb 2007 20:20:12 -0300 "Gabriel Genellina" wrote: > En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns > escribi?: > > > I am starting to use rationals and since I found no batteries > > included, I tried out the mxNumber package. > > > > However, I get strange warnings on comparison operations > > (which however seem to yield correct results): > > mx.Number.Rational is horribly broken. They break this rule: > > a==b => hash(a)==hash(b) > > so they can'b be used as dictionary keys, by example. > Try the other packages suggested. I've used clnum without problems. > I would be interested, under which circumstances the rule is broken. In my (few) tests, hash(a)==hash(b) worked. But I will definitely try clnum. However, I already started trying out gmpy (1.1): $ python Python 2.4.3 (#1, Jan 13 2007, 20:53:15) [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from gmpy import * >>> a=mpq(0,1) >>> a mpq(0) >>> b=-50000000000000000000000000000000000000000000000000000000000 >>> a==b __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1 False >>> Looks pretty much the same as mx.Number Does this warning come up from gmp? Do I have to compile it with different flags? Or do both wrappers use the same code? I would like to encourage the python community (i.e. the guys maintaining the python docs) to point out a recommended rational library. In one of the rational PEPs, it is stated that there are multiple robust rational wrappers for python. But it is not stated, which ones were thoroughly reviewed. Martin From cwitts at gmail.com Fri Feb 9 06:36:13 2007 From: cwitts at gmail.com (Chris) Date: 9 Feb 2007 03:36:13 -0800 Subject: os.popen and broken pipes In-Reply-To: References: Message-ID: <1171020973.891832.166420@j27g2000cwj.googlegroups.com> It could easily be the 2gig file size limitation, how large are the extracts? From bruno.desthuilliers at gmail.com Fri Feb 9 05:05:54 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 9 Feb 2007 02:05:54 -0800 Subject: Thanks for the help In-Reply-To: References: Message-ID: <1171015554.461467.178340@q2g2000cwa.googlegroups.com> On 9 f?v, 04:06, "Reid" wrote: > Hello All > > Thanks for taking the time to answer my question. I do not need 3d stuff. > Just a couple of buttons and menu's. That's not "3D", that's GUI (Graphical User Interface). "3D" usually refers to "3D graphics"... > The reason I am looking at python is it > is free to download. I cannot afford VB or other commercial languages. It's not only "free to download", it's free (as in "free speech") software. And FWIW, there are other good reasons to use Python, one of them being that it's a pretty good language !-) Now, what is your question, exactly ?-) From sjmachin at lexicon.net Wed Feb 21 04:10:29 2007 From: sjmachin at lexicon.net (John Machin) Date: 21 Feb 2007 01:10:29 -0800 Subject: Regex Speed In-Reply-To: References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> Message-ID: <1172049029.217002.55560@v33g2000cwv.googlegroups.com> On Feb 21, 12:14 pm, Pop User wrote: > garri... at gmail.com wrote: > > While creating a log parser for fairly large logs, we have run into an > > issue where the time to process was relatively unacceptable (upwards > > of 5 minutes for 1-2 million lines of logs). In contrast, using the > > Linux tool grep would complete the same search in a matter of seconds. > > Its very hard to beat grep depending on the nature of the regex you are > searching using. The regex engines in python/perl/php/ruby have traded > the speed of grep/awk for the ability to do more complex searches. > > http://swtch.com/~rsc/regexp/regexp1.html > > This might not be your problem but if it is you can always popen grep. > > It would be nice if there were a Thompson NFA re module. Or a Glushkov NFA simulated by bit parallelism re module ... see http://citeseer.ist.psu.edu/551772.html (which Russ Cox (author of the paper you cited) seems not to have read). Cox uses a "pathological regex" (regex = "a?" * 29 + "a" * 29, in Python code) to make his point: grep uses a Thompson gadget and takes linear time, while Python perl and friends use backtracking and go off the planet. The interesting thing is that in Navarro's NR-grep, that's not pathological at all; it's a simple case of an "extended pattern" (? + and * operators applied to a single character (or character class)) -- takes linear time with a much easier setup than an NFA/DFA and not much code executed per byte scanned. Getting back to the "It would be nice ..." bit: yes, it would be nice to have even more smarts in re, but who's going to do it? It's not a "rainy Sunday afternoon" job :-) Cheers, John From duncan.booth at invalid.invalid Mon Feb 12 05:44:14 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Feb 2007 10:44:14 GMT Subject: string.replace non-ascii characters References: Message-ID: "Gabriel Genellina" wrote in triplicate: > If I were paid for the number of lines *written* that would not be a > great deal :) You don't by any chance get paid by the number of posts to c.l.python? From joshua at eeinternet.com Tue Feb 6 22:46:56 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 06 Feb 2007 18:46:56 -0900 Subject: Graphs, bar charts, etc References: <45c87a32@griseus.its.uu.se> Message-ID: <45c93f14$0$16314$88260bb3@free.teranews.com> Jan Danielsson wrote: > Hello all, > > I have some data in a postgresql table which I view through a web > interface (the web interface is written in python -- using mod_python > under apache 2.2). Now I would like to represent this data as graphs, > bar charts, etc. > > I know about matplotlib, and it seemed like exactly what I was > looking for. I tried importing it in my script, but it gave me some > error about a home directory not being writable. I'm not sure I like the > idea of it require to be able to write somewhere. Am I using it wrong? > > Is there something else I can use which can produce graphs easily? We've had good success with matplotlib. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From silverburgh.meryl at gmail.com Mon Feb 19 15:20:39 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 19 Feb 2007 12:20:39 -0800 Subject: How to call a function defined in another py file Message-ID: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> Hi, I have a function called 'test' defined in A.py. How can I call that function test in my another file B.py? Thank you. From jstroud at mbi.ucla.edu Wed Feb 21 21:16:09 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 21 Feb 2007 18:16:09 -0800 Subject: Which Crypto Library? In-Reply-To: References: Message-ID: GiBo wrote: > Hi > > I need some encryption done in my Python 2.5 application. I wonder > what's the most recommended library? I've found M2crypto and some > OpenSSL wrappers and Python Cryptography Toolkit and some others. No > surprise I'm confused :-) > > What's the most often used library for crypto? > > For now I need a simple AES, no asymmetric crypto or GPG involved. > > Thanks! > > GiBo > > > I use pycrypto without any simplification wrappers (e.g. ezPyCrypto) and it seems straightforward to me. You might try the simplification wrappers though. James From usenet200702 at tobyinkster.co.uk Wed Feb 21 11:35:22 2007 From: usenet200702 at tobyinkster.co.uk (Toby A Inkster) Date: Wed, 21 Feb 2007 16:35:22 +0000 Subject: BDFL in wikipedia References: <1172053544.515756.28200@v45g2000cwv.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Carl Banks wrote: >> >> Since when is Larry Wall benevolent? He should be called the SDFL. > > I can't think what the S stands for... if it was M, I'd say Malevolent, > but S? Scented, Sexy, Spanish... no, probably not those. I assume "Sadistic". -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux Now Playing ~ ./vol/music/gorkys_zygotic_mynci_-_poodle_rockin.ogg * = I'm getting there! From ullrich at math.okstate.edu Fri Feb 23 06:11:26 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Fri, 23 Feb 2007 05:11:26 -0600 Subject: CSV(???) Message-ID: Is there a csvlib out there somewhere? And/or does anyone see any problems with the code below? What csvline does is straightforward: fields is a list of strings. csvline(fields) returns the strings concatenated into one string separated by commas. Except that if a field contains a comma or a double quote then the double quote is escaped to a pair of double quotes and the field is enclosed in double quotes. The part that seems somewhat hideous is parsecsvline. The intention is that parsecsvline(csvline(fields)) should be the same as fields. Haven't attempted to deal with parsecsvline(data) where data is in an invalid format - in the intended application data will always be something that was returned by csvline. It seems right after some testing... also seems blechitudinous. (Um: Believe it or not I'm _still_ using python 1.5.7. So comments about iterators, list comprehensions, string methods, etc are irrelevent. Comments about errors in the algorithm would be great. Thanks.) The code: from string import replace, join def csvescape(s): if ',' in s or '"' in s or '\n' in s: res = replace(s, '"', '""') return '"%s"' % res else: return s def csvline(fields): return join(map(csvescape, fields), ',') class indexedstring: def __init__(self, s): self.s = s self.index = 0 def current(self): return self[self.index] def inc(self): self.index = self.index + 1 def next(self): self.inc() return self.current() def __getitem__(self, j): return self.s[j] def __len__(self): return len(self.s) def eos(self): return self.index >= len(self) def lookahead(self): return self[self.index + 1] def getfield(self): if self.eos(): return None if self.current() == '"': return self.quotedfield() else: return self.rawfield() def rawfield(self): """Read until comma or eos.""" start = self.index while not (self.eos() or (self.current() == ',')): self.inc() res = self.s[start:self.index] self.inc() return res def quotedfield(self): """Read until '",' or '" followed by eos. Replace "" in result with ".""" start = self.index while 1: self.inc() if self.current() == '"': self.inc() if (self.eos() or (self.current()==',')): break res = self.s[start + 1:self.index - 1] self.inc() return replace(res, '""', '"') def parsecsvline(csvline): """Inverts csvline(). Assumes csvline is valid, ie is something as returned by csvline(); output undefined if csvline is in invalid format""" s = indexedstring(csvline) res = [] while not s.eos(): res.append(s.getfield()) return res ************************ David C. Ullrich From steve at holdenweb.com Thu Feb 15 06:25:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 11:25:28 +0000 Subject: c++ for python programmers In-Reply-To: References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: Anders Arnholm wrote: > Sam skriver: >> On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn >> wrote: >>> Well, C++ is a better language than C in many ways. So, if he needs to learn >>> one of them, why does it have to be C? >>> >>> Another reason some people choose C++ over Python for some tasks is that >>> they feel that larger programs benefit from strong, static type checking. >>> I like both ways, but depending on the task, one or the other is better. >> C++ is -not- strongly typed. You can cast anything to void *, and >> manipulate it in ways unimaginable. Plus there's the whole mess that >> is pointer arithmetic and a weak typesystem... > > > C++ can be both, The type systenm is as fragila as you like it to be. > I mainlty use c++ when i the need stronger typing that Python och C > can't give me. In some ways it's even stronger types than languanges > as Java and ObjectiveC. C++ it however at least four different > languanges, in one ball of soupe. > Presuming "when i the need" is a typo for "when I need the" rather than "when i feel the need for", when do you actually *need* strong typing? By which I presume you to mean status typing, since Python is already a strongly-types language. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 12 13:42:18 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 12 Feb 2007 19:42:18 +0100 Subject: Newbie Question References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> Message-ID: <53bqoaF1rlgkqU1@mid.individual.net> Stef Mientki wrote: > - in Delphi the GUI design itself is done in a graphical > environment, making it much easier and faster RAD possible with Python, too. > - auto-scaling of components on a form is very easy (so if the > user changes form size ..) Just to name one library, wxPython can do this easily. > - even making everything on a form movable by the > end-user is just 1 mouse-click > - using the designers style, or the user style is just 1 click > - very good feedback, so creating interactive graphs is very easy, > cross-hair, slopes, region of interest etc. Those look like parts of the first point. > - a very huge collection of controls is standard available Just to name one, wxPython ... > [...] > but to be honest ... > ... I never even tried to write a GUI in Python, ... You should. There are several widely used libraries available (Tkinter, wxPython, pyQt, pyGTK, ...), chances are that you like at least one of them if you try. Regards, Bj?rn -- BOFH excuse #96: Vendor no longer supports the product From sjdevnull at yahoo.com Wed Feb 14 18:14:39 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 14 Feb 2007 15:14:39 -0800 Subject: threading and multicores, pros and cons In-Reply-To: <7xejosctev.fsf@ruckus.brouhaha.com> References: <7xodnx2vir.fsf@ruckus.brouhaha.com> <7x7iulqlvx.fsf@ruckus.brouhaha.com> <1171488267.433565.228110@a75g2000cwd.googlegroups.com> <7xejosctev.fsf@ruckus.brouhaha.com> Message-ID: <1171494879.866830.102710@m58g2000cwm.googlegroups.com> On Feb 14, 4:37 pm, Paul Rubin wrote: > "sjdevn... at yahoo.com" writes: > > Java has historically had no support at all for real multiple process > > solutions (akin to fork() or ZwCreateProcess() with NULL > > SectionHandle), which should make up the vast majority of parallel > > programs (basically all of those except where you don't want memory > > protection). > > I don't know what ZwCreateProcess is (sounds like a Windows-ism) Yeah, it's the Window equivalent to fork. Does true copy-on-write, so you can do efficient multiprocess work. > but I > remember using popen() under Java 1.1 in Solaris. That at least > allows launching a new process and communicating with it. Yep. That's okay for limited kinds of applications. > I don't know if there was anything like mmap. That would be important as well. > I think this is mostly a > question of library functions--you could certainly write JNI > extensions for that stuff. Sure. If you're writing extensions you can work around the GIL, too. > > Has this changed in recent Java releases? Is there a way to use > > efficient copy-on-write multiprocess architectures? > > I do think they've been adding more stuff for parallelism in general. Up through 1.3/1.4 or so they were pretty staunchly in the "threads for everything!" camp, but they've added a select/poll-style call a couple versions back. That was a pretty big sticking point previously. From bignose+hates-spam at benfinney.id.au Fri Feb 2 00:21:54 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 16:21:54 +1100 Subject: Overloading the tilde operator? References: Message-ID: <877iv1uob1.fsf@benfinney.id.au> James Stroud writes: > Peter Otten wrote: > > Chris wrote: > >>I am trying to overload the __invert__ operator (~) such that it > >>can take a second argument, > > > >>>>x ~ x > > File "", line 1 > > x ~ x > > ^ > > SyntaxError: invalid syntax > > Seems an arbitrary limitation. Consider > - x > and > x - y Both of which are meaningful syntax in Python, hence the Python parser accepts them and knows what operations to call on the objects. > Which is inconsistent with limiting ~ to a unary operation. Which is the only Python-meaningful way to use that operator, and translates to an appropriate call on the object. The Python runtime parser is designed to parse Python, not some arbitrary language that someone chooses to implement in Python. -- \ "You know what would make a good story? Something about a clown | `\ who makes people happy, but inside he's real sad. Also, he has | _o__) severe diarrhea." -- Jack Handey | Ben Finney From Eric.Gabrielson at gmail.com Thu Feb 8 18:16:13 2007 From: Eric.Gabrielson at gmail.com (Eric.Gabrielson at gmail.com) Date: 8 Feb 2007 15:16:13 -0800 Subject: Newbie Question In-Reply-To: <12sn8clg5iqlp81@corp.supernews.com> References: <12sn8clg5iqlp81@corp.supernews.com> Message-ID: <1170976573.303441.27460@k78g2000cwa.googlegroups.com> On Feb 8, 2:17 pm, Grant Edwards wrote: > On 2007-02-08, Reid wrote: > > > I am just starting to play with programing again as a hobby. I have heard > > good things about python. I have not really looked into the language much. > > My question is, will python make programs with a gui under windows xp. > > Yes. > > There are a number of GUI toolkits for python that will work > with Windows. Some of the more common ones are listed athttp://www.python.org/about/apps/under the "Desktop GUIs" > section. > > -- > Grant Edwards grante Yow! Someone is DROOLING > at on my collar!! > visi.com yes as the guy above stated it does but another fairly easy language that supports windows gui is pascal inspecific borland delphi which uses the pascal language I learned some of it and gui development and coding in it was fun also i found free video tutorials which helped alot, http://www.3dbuzz.com you can click on delphi classroom, they will explain the rest From bruno.desthuilliers at gmail.com Tue Feb 6 10:59:39 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 6 Feb 2007 07:59:39 -0800 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> Message-ID: <1170777579.390667.313670@q2g2000cwa.googlegroups.com> On 6 f?v, 16:23, "jeremito" wrote: > Please excuse me if this is obvious to others, but I can't figure it > out. I am subclassing dict, but want to prevent direct changing of > some key/value pairs. For this I thought I should override the > __setitem__ method as such: > > class xs(dict): > """ > XS is a container object to hold information about cross sections. > """ > > def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): > """ > """ > x = {} > x['xS'] = xS > x['xF'] = xF > x['nu'] = nu > x['xG'] = xG > x['xA'] = x['xG'] + x['xF'] > x['xT'] = x['xA'] + x['xS'] > > return x replace this with: def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): dict.__init__( self, xS=xS, xF=xF, xG=xG, nu=nu, xA=xG + xF, xT=xG + xF + xS ) > def __setitem__(self, key, value): > """ > I have overridden this method to prevent setting xT or xA > outside the > class. > """ > print "I am in __setitem__" > if key == 'xT': > raise AttributeError( "Can't change xT. Please change, xF, xS, or xG" ) dict.__setitem__(self, key, value) > But I can't even get __setitem__ to run. of course, since your __new__ method returns a dict instance, not a xs instance... There are very few cases where you really need to override the __new__ method. > Example: > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> import xs > >>> cs = xs.xs() > >>> cs > > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}>>> cs['xT'] = 3.1415 > >>> cs > > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': > 3.1415000000000002} > > Is this what the __setitem__ method is for? Yes. But note that you you need to manually call the superclass's overriden method - unless you really want to replace it with your own, which is obviously not the case here... Note that if someone manually changes the values of xG, xF, or xS, the computed values of xA and/or xT won't reflect this change. Is that what you want ? Finally, and if I may ask, what is your use-case for subclassing dict ? You don't need this to implement a dict-like object, and it might be simpler in your case to write an ordinary class, then add support for the required subset of the dict interface. My 2 cents... From me at privacy.net Sat Feb 24 11:00:11 2007 From: me at privacy.net (Dan Sommers) Date: Sat, 24 Feb 2007 11:00:11 -0500 Subject: Endianness conversion References: <45e05c49$0$20809$5fc30a8@news.tiscali.it> Message-ID: On Sat, 24 Feb 2007 15:39:53 +0000, Toby wrote: > As part of a program I'm writing, I need to save to disk big amounts of > data (hundreds of MB, in 8kB chunks) swapping every couple of bytes. > > I obviously cannot do it in a Python loop. > > Is there a function I could use in the standard library, or do I have to > write my own C extension? You could try the struct module. If your input comes in fixed sized chunks, just call struct.unpack and struct.pack once per chunk. HTH, Dan -- Dan Sommers Atoms are not things. -- Werner Heisenberg. From grante at visi.com Thu Feb 22 09:58:41 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 22 Feb 2007 14:58:41 -0000 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172103048.160783.309470@l53g2000cwa.googlegroups.com> <12tq4rvmb0ke0a4@corp.supernews.com> Message-ID: <12trbt1high535c@corp.supernews.com> On 2007-02-22, Grant Edwards wrote: > On 2007-02-22, Ganesan Rajagopal wrote: > >>> I am hoping to have it show up some weird un-readable text. >>> And then of course be able to convert it right back to a >>> string. Is this even possible? >> >> Looks like you just want to obfuscate the string. How about >> this? >> >> import base64 >> text = 'supercalifragilisticexpialidocius' >> open('sambleb.conf', 'w').write(base64.encodestring(text)) >> >> print base64.decodestring(open('sambleb.conf', 'r').read()) > > It'll only remain obfuscated for about 30 seconds after even a > mildly curious user looks at the file. I should add that even "strong" encryption will only slow down a curious user by 10 minutes if the encryption/decryption key is embedded in the program... Trying to hide things from users is usually futile unless you want put a lot of work into it... -- Grant Edwards grante Yow! Do you have exactly at what I want in a plaid visi.com poindexter bar bat?? From gagsl-py at yahoo.com.ar Mon Feb 19 00:15:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 02:15:42 -0300 Subject: What is more efficient? References: Message-ID: En Mon, 19 Feb 2007 00:17:54 -0300, Karlo Lozovina <_karlo_ at _mosor.net_> escribi?: > Let's say I have a class with few string properties and few integers, and > a lot of methods defined for that class. > > Now if I have hundreds of thousands (or even more) of instances of that > class - is it more efficient to remove those methods and make them > separate functions, or it doesn't matter? I'm not sure what you mean, but normal methods are attached to the class, not to its instances. It doesn't matter whether you have 0 or a million instances, methods do not occupy more memory. -- Gabriel Genellina From istvan.albert at gmail.com Fri Feb 2 10:04:09 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 2 Feb 2007 07:04:09 -0800 Subject: Writing "pythonish" code In-Reply-To: References: Message-ID: <1170428649.169634.230780@s48g2000cws.googlegroups.com> On Feb 2, 6:20 am, Mizipzor wrote: > Now, the thing that bothers me the most. When I write python modules I > write one class per file, and the file and the class has a common > name. Maybe this is due to c++ habits. Python modules typically contain multiple classes and module level functions as well. That way having to deal with redundant names such as foo.foo comes up less often. Also it is a good habit to make capitalize class names, that way writing: from foo import Foo, bar makes it clear that one is a class the other a function. i. PS: here is my personal pet peeve ... say it out loud ... I love the functionality it offers and saved me a lot of work, yet I have to make his conscious effort to keep these names: package, module, class apart. from elementtree.ElementTree import ElementTree From jstroud at mbi.ucla.edu Wed Feb 28 06:15:39 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 28 Feb 2007 11:15:39 GMT Subject: Curses sorely lacking an event loop? In-Reply-To: <1172583555.352109.258520@m58g2000cwm.googlegroups.com> References: <1172583555.352109.258520@m58g2000cwm.googlegroups.com> Message-ID: Michele Simionato wrote: > On Feb 27, 1:27 pm, James Stroud wrote: >> Hello, >> >> Is curses really lacking an event loop? Do I have to write my own? I >> infer from the docs that this is the case. For example, I want the >> screen to be updated with resize but I find myself waiting for getch() >> if I want user input, and so the screen must remain ugly until the user >> presses a key. What am I missing? >> >> Also, does anyone have boilerplate for handling mouse events? getmouse() >> returns an "ERR" of no particular description and also appears to >> require a preceding getch() and hence does not seem to be wired at all >> for clicks, although allusion to clicks is found in the descriptions for >> mouseinterval() and mousemask(). >> >> Here is the error message for getmouse() in case anyone wants details: >> "_curses.error: getmouse() returned ERR". This is much less informative >> than one might hope. >> >> Thanks in advance for any help. >> >> James > > Did you check Urwid? http://excess.org/urwid > > Michele Simionato > Perfect. Just what I was looking for. Thank you. James From felipe.lessa at gmail.com Wed Feb 7 22:17:14 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 8 Feb 2007 01:17:14 -0200 Subject: help on packet format for tcp/ip programming In-Reply-To: <1170904453.625206.54970@l53g2000cwa.googlegroups.com> References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> Message-ID: On 7 Feb 2007 19:14:13 -0800, rattan at cps.cmich.edu > struct module pack and unpack will only work for fixed size buffer : > pack('>1024sIL', buffer, count. offset) but the buffer size can vary > from one packet to the next :-( Then send the size of the buffer before the buffer, so the recipient can expect that many bytes. -- Felipe. From robert.kern at gmail.com Thu Feb 8 17:24:48 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 08 Feb 2007 14:24:48 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> References: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> Message-ID: W. Watson wrote: > Robert Kern wrote: >> W. Watson wrote: >> >>> I did a search in the python24 folder for sys.exec* (in c:\python24), but >>> came up with nothing. [nothing in a search of c:--sys.exec*] I have two >>> python folders, c:\python24 and c:\python25. The contents of both folders >>> look fairly similar and each have a python.exe. I do not use a PIL or >>> Numeric in 2.5. >> I'm sorry. sys is a module. I meant for you to execute the following Python code: >> >> import sys >> print sys.executable >> > I'm savvy about a number of languages, but not yet about Python. What py > file will allow this to be executed? Just the lines between the comments here: #### import sys print sys.executable #### I recommend going through the tutorial first, before worrying about Numeric or PIL. Here is the URL for the 2.4.4 version: http://www.python.org/doc/2.4.4/tut/tut.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jm.suresh at gmail.com Tue Feb 13 03:44:39 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 13 Feb 2007 00:44:39 -0800 Subject: Templates for epydoc Message-ID: <1171356279.397988.175600@m58g2000cwm.googlegroups.com> Hello, I am looking for a good css template to be used with epydoc . Google did not help. Any links would be helpful. - Suresh From deets at nospam.web.de Mon Feb 5 12:35:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Feb 2007 18:35:28 +0100 Subject: get objects referencing another one References: Message-ID: <52p870F1pg9igU2@mid.uni-berlin.de> Olivier Feys wrote: > I'm working on a tree and I have refcounting problems. > Is it possible from an object, to get the list of objects referencing it ? The gc-module might help, but it is somewhat overwhelming. Diez From skip at pobox.com Wed Feb 14 17:13:28 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 14 Feb 2007 16:13:28 -0600 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <17875.35208.373056.764333@montanaro.dyndns.org> Concatenating tuples and lists seems logical if you think of tuples as sequences. If you think of them more like Pascal records or C structs instead (I believe that's Guido's perspective on tuples) then it makes no sense at all. Skip From tiedon_jano at hotmail.com Tue Feb 27 10:54:24 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 27 Feb 2007 15:54:24 GMT Subject: Help on object scope? In-Reply-To: <1172576724.580582.65890@z35g2000cwz.googlegroups.com> References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> <1172576724.580582.65890@z35g2000cwz.googlegroups.com> Message-ID: bmaron2 at hotmail.com kirjoitti: > > global names seemed to be the best idea. The only problem is now I > have to type common.r.t instead of just r.t. If I put common in the / > lib directory, it is even worse and I have to type lib.common.r.t. I > like that it is explicit and perhaps this is the Python way, but it is > annoying and produces ugly code to see all those fully-qualified names > when all I'd really like to use is r.t throughout the program. > > Is there a way to import lib.common but then re-bind its attributes to > the local space without breaking the linkage? > > See section "6.12 The import statement" in the "Python Reference Manual". (Hint the part "as name" is what you want) HTH, Jussi From bwooster47 at gmail.com Wed Feb 21 13:36:03 2007 From: bwooster47 at gmail.com (bwooster47 at gmail.com) Date: 21 Feb 2007 10:36:03 -0800 Subject: datetime - easy way to make it use local timezone? Message-ID: <1172082963.443525.286060@p10g2000cwp.googlegroups.com> Is there an easy way to have an automatically constructed local time zone tzinfo object be used with datetime? Following code shows the problem - the time module works fine mostly (%Z works, but %z does not, but that may be the way it is), uses # The following python code outputs: note the time() modules print EST and EDT (daylight savings), # but datetime does not. #----------- t = time.time() = 1172170000 # t tuple = (2007, 2, 22, 13, 46, 40, 3, 53, 0) %Z%z = EST+0000 # dt tuple = (2007, 2, 22, 13, 46, 40, 3, 53, -1) %Z%z = #----------- t = time.time() = 1177340000 # t tuple = (2007, 4, 23, 10, 53, 20, 0, 113, 1) %Z%z = EDT+0000 # dt tuple = (2007, 4, 23, 10, 53, 20, 0, 113, -1) %Z%z = ---- python code------------------------- import time from datetime import datetime t = 1172170000 # Feb 22 t_tuple = time.localtime(t) dt = datetime.fromtimestamp(t) dt_tuple = dt.timetuple() print "#-----------", "t = time.time() = ", t print "# t tuple = ", t_tuple, " %Z%z = ", time.strftime("%Z%z", t_tuple) print "# dt tuple = ", dt_tuple, " %Z%z = ", dt.strftime("%Z%z") t += 5170000 # Apr 23 t_tuple = time.localtime(t) dt = datetime.fromtimestamp(t) dt_tuple = dt.timetuple() print "#-----------", "t = time.time() = ", t print "# t tuple = ", t_tuple, " %Z%z = ", time.strftime("%Z%z", t_tuple) print "# dt tuple = ", dt_tuple, " %Z%z = ", dt.strftime("%Z%z") From http Tue Feb 13 15:49:46 2007 From: http (Paul Rubin) Date: 13 Feb 2007 12:49:46 -0800 Subject: Undo os.remove References: <1171398956.060378.215530@q2g2000cwa.googlegroups.com> Message-ID: <7xps8dpytx.fsf@ruckus.brouhaha.com> chris.peressotti at gmail.com writes: > Hi. I just used os.remove to get rid of some files -- unfortunately, > I realized afterward that I didn't really want to get rid of them. It > isn't life-or-death, here, but is there any way for me to get these > files back? Try a websearch for file recovery utilities, nothing to do with Python especially. "Directory Snoop" by Kent Briggs is supposedly pretty good if you run Windoze. One thing you should do is shut off your computer right away if it's the same one where you deleted those files. If the freed disk sectors get re-used by other files they are unrecoverable, and Windows is always doing stuff that eats up disk sectors. Use a different computer to search for recovery programs. From charleshixsn at earthlink.net Sun Feb 25 13:29:24 2007 From: charleshixsn at earthlink.net (Charles D Hixson) Date: Sun, 25 Feb 2007 10:29:24 -0800 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) Message-ID: <45E1D584.8090703@earthlink.net> Toby wrote: > Charles D Hixson wrote: > >> a class whose sub-classes automatically have unique class variables of >> a determined form such that I can do a hierarchical search through them >> > > Something like this? > (scroll down to see the results) > > > # --- begin --- > > class AttrSearch(object): > @classmethod > def getclassattrset(cls, name): > s = set() > if name in cls.__dict__: > s.add((cls.__name__, cls.__dict__[name])) > for base in cls.__bases__: > try: > s.update(base.getclassattrset(name)) > except AttributeError: > pass > return s > > def getattrset(self, name): > s = set() > try: > s.add((None, self.__dict__[name])) > except KeyError: > pass > s.update(self.__class__.getclassattrset(name)) > return s > > def __getattribute__(self, name): > if name.startswith('__'): #XXX not pretty > return object.__getattribute__(self, name) > found = AttrSearch.getattrset(self, name) > print 'Looking for "%s" in a %s instance, found %d candidates:' \ > % (name, self.__class__.__name__, len(found)) > print '\n'.join([ ' %-4s %s' % x for x in found ]) > print '(now choose wisely what to return)' > > class A(AttrSearch): > a = 1 > > class B(A): > a = 2 > > class C(A): > a = 3 > > class D(B, C): > a = 4 > > > D().a > > # --- end --- > > > Results: > > Looking for "a" in a D instance, found 4 candidates: > A 1 > B 2 > C 3 > D 4 > (now choose wisely what to return) > > > Toby > Yes, thank you. (I'd come up with a kludge, but this is much nicer.) From gagsl-py at yahoo.com.ar Wed Feb 14 20:36:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 22:36:26 -0300 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: En Wed, 14 Feb 2007 10:41:53 -0300, Neil Cerutti escribi?: > On 2007-02-14, Gabriel Genellina wrote: >> Python does not do "tail recursion optimization" (at >> least, I'm not aware of that). > > To be just a little pedantic, it's "tail call optimization". Any > tail call can be optimized, not just recursive ones. Maybe, but I didn't invent the term: http://computing-dictionary.thefreedictionary.com/tail%20recursion%20optimisation It's true that tail recursion is a special case of tail call - but it's just the case that can be managed by hand, no special support on the language -trampoline or whatever- is required (just a loop, "GOTO 1"). >> But even if it could do that, in this case you have recursive >> calls between two functions, and that's a bit harder. > > So the effect is that mutual recursion isn't actually any harder. But some kind of language support is required in this case. At least I don't know how to handle mutual recursion (apart from inlining one function inside the other...). But I'm certainly not a "program transformation guru" (neither a novice!) so I would not be surprised if someone says it can be done... -- Gabriel Genellina From mccredie at gmail.com Tue Feb 20 19:00:56 2007 From: mccredie at gmail.com (Matimus) Date: 20 Feb 2007 16:00:56 -0800 Subject: How to do a Decorator Here? In-Reply-To: References: Message-ID: <1172016056.108359.67930@a75g2000cwd.googlegroups.com> On Feb 20, 12:20 pm, "Gregory Pi?ero" wrote: > Need some decorator help. > > I have a class. And I want to add behavior to one of this class's > methods to be run before the class runs the actual method. Is this > what decorators are for? > > So the class I want to work with is string.Template > > Let's say I have this: > from string import Template > a=Template("$var1 is a test") > > def preprocess(var1): > #Real code here will be more complicated, just an example > var1=var1.upper() > > a.substitute(var1="greg") > > So how can I have preprocess run before substitute is run? I want the > user to be able to call a.substitute and have preprocess run > automatically. > > Or is this not what decorators do? I'm trying to avoid subclassing if I can. > > Thanks in advance for the help. > > -Greg You could just overload Template and put your own version of substitute in there. I'm not sure a decorator is appropriate in this case. Here is an overloading example: [code] from string import Template # this assumes you are only interested in keyword arguments # the form substitute(map) will not work class MyTemplate(Template): def substitute(self,**kwargs): for k,v in kwargs.iteritems(): kwargs[k] = v.upper() return super(MyTemplate,self).substitute(self,**kwargs) if __name__ == "__main__": a = MyTemplate("$var1 is a test") print a.substitute(var1 = "greg") [/code] From gagsl-py at yahoo.com.ar Tue Feb 6 16:30:21 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 18:30:21 -0300 Subject: Running long script in the background References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170769014.352466.135280@h3g2000cwc.googlegroups.com> <1170776253.027044.253050@q2g2000cwa.googlegroups.com> <1170791092.333254.279680@q2g2000cwa.googlegroups.com> Message-ID: En Tue, 06 Feb 2007 16:44:52 -0300, wattersmt at gmail.com escribi?: > On Feb 6, 2:02 pm, Dennis Lee Bieber wrote: >> On 6 Feb 2007 07:37:33 -0800, "watter... at gmail.com" >> declaimed the following in comp.lang.python: >> >> > Everything works fine until I call the popen function, then it >> > freezes. What I want is to print the output in real time, just like >> > it does when I run it from a shell. >> >> And you want /this/ in a web page? >> >> I don't think HTTP is designed for that... As I understand it, >> it >> expects to get a complete page back and then the transaction is complete >> and forgotten (except for the presence of session cookies). To report If the response does not include a Content-Length header, and has a Transfer-Encoding: chunked header, then it is sent in chunks (blocks) and the client is able to process it piece by piece. See the server docs on how to enable and generate a chunked response. On Zope 2, by example, it's enough to use response.write(). > Web pages can show output as it's sent. For testing I created a > script on the server that untars a 600 meg volume, I can see each file > name show up in my browser instantly, just like it should. The other > script I'm trying to run won't show anything until the entire process > is complete and it's just a bunch of echo statements in a for loop, > I'm not sure why they behave differently. Are you sure the other process is executing? and not buffered? and you're reading its output line by line? -- Gabriel Genellina From greg at cosc.canterbury.ac.nz Sat Feb 10 04:23:14 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 10 Feb 2007 22:23:14 +1300 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> <1171016992.962017.10540@m58g2000cwm.googlegroups.com> Message-ID: <535hc1F1r96ihU1@mid.individual.net> Alexander Schmolck wrote: > how would you code a program that gives the following > output ('skewed' sierpinski-triangle) in python? > > > * > ** > * * > **** > * * > ** ** > * * * * > ******** > * * > ** ** > * * * * > **** **** > * * * * > ** ** ** ** > * * * * * * * * > **************** ############################################################### def print_sierpinski(order): size = 4 * 2 ** order buffer = [size * [" "] for i in range(size)] put_sierpinski(buffer, size, 0, 0) for line in buffer: print "".join(line) def put_sierpinski(buffer, size, x, y): if size == 4: put_triangle(buffer, size, x, y) else: size2 = size / 2 put_sierpinski(buffer, size2, x, y) put_sierpinski(buffer, size2, x, y + size2) put_sierpinski(buffer, size2, x + size2, y + size2) def put_triangle(buffer, size, x, y): for i in range(3): buffer[y + i][x] = buffer[y + i][x + i] = "*" for i in range(4): buffer[y + 3][x + i] = "*" print_sierpinski(2) ############################################################### By making the recursion explicit, I think this brings out the self-similarity better than any of the other solutions posted, which are very clever but not what I would call "lucid". -- Greg From ryankaskel at gmail.com Wed Feb 28 19:58:25 2007 From: ryankaskel at gmail.com (Ryan K) Date: 28 Feb 2007 16:58:25 -0800 Subject: text wrapping help In-Reply-To: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> References: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> Message-ID: <1172710705.158010.204480@m58g2000cwm.googlegroups.com> Okay, I was a little vague in my last post...the matrix is like a Wheel of Fortune board and it knows nothing about newlines. After 24 characters it spills over onto the next line. Here is what I came up with:
## Wrap Text

def wrap_text(in_str, chars_line):
    """ wrap text """
    spaces = 0
    new_str = ""
    tmp_str = ""
    while True:
        tmp_str = in_str[:chars_line]
        if tmp_str[chars_line-1].isspace():
            new_str += tmp_str
        else:
            spaces = 0
            for ch in reversed(tmp_str):
                if ch.isspace():
                    break
                spaces += 1
            tmp_str = tmp_str[:chars_line-spaces]
            tmp_str += " " * spaces
            new_str += tmp_str
            in_str = in_str[chars_line-spaces:]
        if len(in_str) <= chars_line:
            new_str += " " + in_str
            break
    return new_str


if __name__ == '__main__':

    sample_text = """Personal firewall software may warn about the
connection IDLE makes to its subprocess using this computer's internal
loopback interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet."""
    print wrap_text(sample_text, 24)

It doesn't even run but when I go through it interactively it seems okay. Once again, any help is appreciated. On Feb 28, 7:06 pm, "Ryan K" wrote: > I'm trying to text wrap a string but not using the textwrap module. I > have 24x9 "matrix" and the string needs to be text wrapped according > to those dimensions. Is there a known algorithm for this? Maybe some > kind of regular expression? I'm having difficulty programming the > algorithm. Thanks, > Ryan From robert.kern at gmail.com Wed Feb 28 15:18:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 28 Feb 2007 14:18:10 -0600 Subject: f2py and Fortran90 gfortran_filename error In-Reply-To: References: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> <1172670915.478334.48510@j27g2000cwj.googlegroups.com> Message-ID: Robert Kern wrote: > Beliavsky wrote: >> I wish the Google Groups interface to the list http://groups.google.com/group/Numpy-discussion >> worked. When I use it to post my messages bounce, but messages from >> the list do show up on Google Groups. The "bounces" say >> >> "This mailing list is now defunct. Please use >> numpy-discussion at scipy.org to discuss NumPy, Numeric, and numarray. >> >> http://projects.scipy.org/mailman/listinfo/numpy-discussion" >> >> Yes, I know I could follow these instructions, but I prefer to use >> Google Groups. > > Well, you'll have to find out who set up that interface or whoever at Google is > in charge of maintaining such gatewayed groups to let them know that the mailing > list has migrated. I used the "Send email to the owner" link, but I have no idea > who that is supposed to go to. It worked. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From michaelbohansen at gmail.com Wed Feb 7 05:22:44 2007 From: michaelbohansen at gmail.com (Michael Bo) Date: 7 Feb 2007 02:22:44 -0800 Subject: Watch folder for new file and execute extern program In-Reply-To: References: <1170682938.056015.238000@p10g2000cwp.googlegroups.com> Message-ID: <1170843764.897144.130830@p10g2000cwp.googlegroups.com> > BTW-It helps us out here if you let us know what platform you > are running on (e.g. Windows, Linux, Mac, etc.). > > -Larry Sorry... I'm running on windows XP. - Michael From deets at nospam.web.de Wed Feb 7 08:44:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Feb 2007 14:44:52 +0100 Subject: outlook bar References: <1170851533.659485.248830@v33g2000cwv.googlegroups.com> Message-ID: <52u3ekF1phk22U1@mid.uni-berlin.de> yvesd wrote: > Hello, > I'm trying to make an outlook bar like in python but i'm not at all > familiar with ms-outlook and i'm > a bit too weak and in early stage of python learning. > Has somebody already made or seen the code IN TKINTER(/)PMW for a bar > like that ? I've not done such a thing, however I investigated the possibility to create an IE-Bar - and based on that I assume you can't do that in Tkinter at all. You need native windows controls for that, and some COM-stuff for registering and interacting. So at least you need the win32-extensions from Mark Hammond, but maybe quite a bit more. Diez From bearophileHUGS at lycos.com Wed Feb 14 18:20:25 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Feb 2007 15:20:25 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: <45d3403a$0$337$e4fe514c@news.xs4all.nl> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <45d3403a$0$337$e4fe514c@news.xs4all.nl> Message-ID: <1171495225.405531.202090@v33g2000cwv.googlegroups.com> Martin P. Hellwig > for me (personal) being Pythonic means that I should > separate the logic and variables, etc... Well, for me me Pythonic means using built-in functionalities as much as possible (like using encode("rot13") or translate), and to write less code, (avoiding overgeneralizations from the start too). It means other things too. Bye, bearophile From duncan.booth at invalid.invalid Mon Feb 12 07:59:46 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Feb 2007 12:59:46 GMT Subject: Formatting milliseconds to certain String References: Message-ID: Deniz Dogan wrote: > I want to make a function which takes an integer representing some > time in milliseconds and returns the same time but formatted as > "hours:minutes:seconds,milliseconds" with leading zeros whenever > possible. > > E.g. I input 185804 to the function and it returns 00:03:05,804. If you don't have to worry about more than 24 hours you could use strftime: import time def fmt(t): return time.strftime("%H:%M:%S", time.gmtime(t/1000)) + ',%03d' % (t%1000) print fmt(185804) If you do, then much as you had it but using a format string and floor division: def fmt(t): SEC = 1000 MIN = SEC * 60 HOUR = MIN*60 return "%02d:%02d:%02d,%03d" % ( t//HOUR, (t%HOUR)//MIN, (t%MIN)//SEC, t%SEC) Why did you write a function which returns a string normally and a number when it failed? Use an exception to indicate an error condition, not a number which you'll forget to check for. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 28 21:30:39 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 03:30:39 +0100 Subject: Extract String From Enclosing Tuple References: <87slcqvskr.fsf@benfinney.id.au> Message-ID: <54ms6fF21c6h3U2@mid.individual.net> Ben Finney wrote: > A tuple implies a meaning associated with each position in the > sequence (like a record with a positional meaning for each field), > a list implies the opposite (a sequence with order but not meaning > associated with each position). Explain. I know tuples as immutable lists ... BTW, don't confuse python tuples with tuples from mathematics. Regards, Bj?rn -- BOFH excuse #214: Fluorescent lights are generating negative ions. If turning them off doesn't work, take them out and put tin foil on the ends. From http Tue Feb 27 21:55:11 2007 From: http (Paul Rubin) Date: 27 Feb 2007 18:55:11 -0800 Subject: Yet another unique() function... References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <7x8xej80a5.fsf@ruckus.brouhaha.com> Message-ID: <7xzm6z6lf4.fsf@ruckus.brouhaha.com> Paul Rubin writes: > def unique(seq, keepstr=True): > t = type(seq) > if t==str: > t = (list, ''.join)[bool(keepstr)] > seen = [] > return t(c for c in seq if (c not in seen, seen.append(c))[0]) Preferable: def unique(seq, keepstr=True): t = type(seq) if t==str: t = (list, ''.join)[bool(keepstr)] seen = [] return t(c for c in seq if not (c in seen or seen.append(c))) From steve at holdenweb.com Thu Feb 15 17:07:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 17:07:30 -0500 Subject: Automated resizing of JPEG image + making slices? In-Reply-To: <11493D4C-C9E0-46DC-A9F9-B664416460FA@thingmajig.org> References: <11493D4C-C9E0-46DC-A9F9-B664416460FA@thingmajig.org> Message-ID: Michiel Sikma wrote: > Hello everybody. > > I'm currently involved in a site building project in which we're > going to use the Google Maps API. The user will be able to browse the > site by looking over a really large image, similar to how Google Maps > itself works, except with the design of the site on the background > rather than a map of the world. > > I initially hired someone to do it in PHP (don't bite, please :-) but > it seems that I forgot about one thing: the people updating the site > would have been able to upload a huge 30 MB JPEG image, which PHP > would then resize to various sizes and cut them into 200x200 pieces, > which would be fed to the Google Maps API. However, this costs a lot > of memory, and PHP by default only has 8 MB. > > The programmer offered to do a C++ image manipulator, but he uses > Windows and the people who update the site use Mac OS X. It would be > tedious. Then I thought that Python might solve me the head-ache. > > I know some Python (but not much since I've never actually written > that many things in it), and with some effort I could probably make a > simple image manipulator frontend in it, but only if I can find a > good library for doing the actual manipulation. Do any of you know > such libraries? > PIL, the Python Imaging Library, would seem to be the ideal candidate. See http://www.pythonware.com/products/pil/ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From ptmcg at austin.rr.com Thu Feb 22 04:55:43 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 22 Feb 2007 01:55:43 -0800 Subject: Finding a tuple in a tuple In-Reply-To: <7xd5427ebd.fsf@ruckus.brouhaha.com> References: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> <7xd5427ebd.fsf@ruckus.brouhaha.com> Message-ID: <1172138143.526067.208750@k78g2000cwa.googlegroups.com> On Feb 22, 3:05 am, Paul Rubin wrote: > b... at yahoo.com writes: > > Lists say I have the following tuple - > > t1 = ("ONE","THREE","SIX") > > t2 = ("ONE","TWO","THREE") > > t3 = ("TWO","FOUR","FIVE","SIX") > > t4 = ("TWO",) > > t5 = ("TWO","FIVE") > > > What I want to do is return true if any member of tuple t1 is found in > > the remaining tuples. > > Convert them into sets and use the set intersection (&) operator, > then convert to bool to represent whether the intersection is empty. > > print bool(set(t1) & set(t2)) > print bool(set(t1) & set(t3)) > print bool(set(t1) & set(t4)) > print bool(set(t1) & set(t5)) A step further: use union to make a superset of t2-tN, then use & on this superset. setlist = [t2,t3,t4,t5] superset = reduce(set.union, map(set,setlist) ) print bool(t1 & superset) -- Paul From silverbeach06 at gmail.com Sun Feb 11 19:55:35 2007 From: silverbeach06 at gmail.com (susan) Date: 11 Feb 2007 16:55:35 -0800 Subject: No module named pyExcelerator Error Message-ID: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> Hi, I'm new of Python, and this problem stucked me whole day but can't be solved. I use python 2.4.3, which is download from cygwin packages. Then I downloaded pyexcelerator-0.5.3a, unzip it, $ python ./pyExcelerator/setup.py install running install running build running build_py package init file 'pyExcelerator/__init__.py' not found (or not a regular file) copying pyExcelerator/setup.py -> build/lib/pyExcelerator package init file 'pyExcelerator/__init__.py' not found (or not a regular file) running install_lib copying build/lib/pyExcelerator/setup.py -> /usr/lib/python2.4/site- packages/pyE xcelerator byte-compiling /usr/lib/python2.4/site-packages/pyExcelerator/setup.py to setup. pyc But 'pyExcelerator/__init__.py' is absolutely there, I don't know why I got the warning. Then I tried to import pyExcelerator, >>> import pyExcelerator Traceback (most recent call last): File "", line 1, in ? ImportError: No module named pyExcelerator anybody can tell me where's wrong please? Thanks in advance! From nogradi at gmail.com Mon Feb 26 15:30:11 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 26 Feb 2007 21:30:11 +0100 Subject: gmpy moving to code.google.com In-Reply-To: References: Message-ID: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> > If you're interested in gmpy (the Python wrapper of GMP, for > unlimited-precision arithmetic, rationals, random number generation, > number-theoretical functions, etc), please DO check out > http://code.google.com/p/gmpy/ -- gmpy 1.02 is there (as far as I can > tell) in a workable state. Source on Subversion (and a prerelease > zipfile too), downloadable binaries for MacOSX (download and read the > README file first!) and Windows (for Python 2.4 and 2.5 only, built and > minimally tested on a shaky Win2K+mingw -- on -- Parallels/MacOSX > setup... I have no other Windows machine to check 'em out...!). > > Please help me check that the move-and-upgrade went OK -- download some > or all of the pieces (including an svn checkout of the sources), build, > install, test, try it out. I will HEARTILY welcome feedback (mail > aleaxit at gmail.com) telling me what worked and/or what didn't so I can > finalize this release -- and hopefully move on to a future 1.03 (I won't > aim to 1.03 until I'm convinced that 1.02 is OK...). > > > Thanks in advance, > > Alex Svn checkout, compilation and installation went okay but some tests failed, this is the output of 'python test_gmpy.py': Unit tests for gmpy 1.02 release candidate on Python 2.5 (r25:51908, Nov 1 2006, 11:42:37) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] Testing gmpy 1.02 (GMP 4.1.4), default caching (20, 20, -2..11) gmpy_test_cvr 270 tests, 0 failures gmpy_test_rnd 26 tests, 0 failures gmpy_test_mpf 155 tests, 0 failures gmpy_test_mpq 264 tests, 0 failures ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_mpz.py", line ?, in gmpy_test_mpz.__test__.number Failed example: _memsize()-_siz Expected: 0 Got: -4 ********************************************************************** 1 items had failures: 2 of 132 in gmpy_test_mpz.__test__.number ***Test Failed*** 2 failures. gmpy_test_mpz 388 tests, 2 failures ********************************************************************** 1 items had failures: 2 of 132 in gmpy_test_mpz.__test__.number ***Test Failed*** 2 failures. gmpy_test_dec 16 tests, 0 failures 7 items had no tests: gmpy_test_cvr._test gmpy_test_dec._test gmpy_test_mpf._test gmpy_test_mpq._test gmpy_test_mpz._memsize gmpy_test_mpz._test gmpy_test_rnd._test 30 items passed all tests: 6 tests in gmpy_test_cvr 12 tests in gmpy_test_cvr.__test__.misc_stuff 252 tests in gmpy_test_cvr.__test__.user_errors 1 tests in gmpy_test_dec 15 tests in gmpy_test_dec.__test__.elemop 1 tests in gmpy_test_mpf 32 tests in gmpy_test_mpf.__test__.binio 33 tests in gmpy_test_mpf.__test__.cmpr 49 tests in gmpy_test_mpf.__test__.elemop 34 tests in gmpy_test_mpf.__test__.format 6 tests in gmpy_test_mpf.__test__.newdiv 2 tests in gmpy_test_mpq 26 tests in gmpy_test_mpq.__test__.binio 62 tests in gmpy_test_mpq.__test__.cmpr 66 tests in gmpy_test_mpq.__test__.elemop 54 tests in gmpy_test_mpq.__test__.format 12 tests in gmpy_test_mpq.__test__.newdiv 18 tests in gmpy_test_mpq.__test__.power 24 tests in gmpy_test_mpq.__test__.qdiv 4 tests in gmpy_test_mpz 34 tests in gmpy_test_mpz.__test__.binio 62 tests in gmpy_test_mpz.__test__.bitops 48 tests in gmpy_test_mpz.__test__.cmpr 42 tests in gmpy_test_mpz.__test__.elemop 36 tests in gmpy_test_mpz.__test__.format 14 tests in gmpy_test_mpz.__test__.index 12 tests in gmpy_test_mpz.__test__.newdiv 4 tests in gmpy_test_mpz.factorize 1 tests in gmpy_test_rnd 25 tests in gmpy_test_rnd.__test__.rand ********************************************************************** 1 items had failures: 2 of 132 in gmpy_test_mpz.__test__.number 1119 tests in 38 items. 1117 passed and 2 failed. ***Test Failed*** 2 failures. HTH, Daniel From edreamleo at charter.net Fri Feb 16 06:54:57 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 05:54:57 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> Message-ID: > In short, if you need to support 2.3, you're not ready to be looking at > 3.0. I hope this turns out not to be true. As a developer, I have no way to force people to 3.0, and no reason to want to. For me, maintaining two incompatible code bases is out of the question. It will be interesting to see how this plays out. Users, not developers, will determine when Python 2.x becomes extinct. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From skip at pobox.com Sun Feb 25 07:26:51 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 25 Feb 2007 06:26:51 -0600 Subject: CSV(???) In-Reply-To: References: Message-ID: <17889.32907.980331.764942@montanaro.dyndns.org> David> Is there a csvlib out there somewhere? ... David> ...Believe it or not I'm _still_ using python 1.5.7.... You might see if someone has written a pure Python version of the csv module for use in PyPy. Skip From http Sun Feb 11 23:18:06 2007 From: http (Paul Rubin) Date: 11 Feb 2007 20:18:06 -0800 Subject: Help with Optimization of Python software: real-time audio controller References: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> Message-ID: <7x1wkw6mbl.fsf@ruckus.brouhaha.com> craiglewiston at gmail.com writes: > So, for a music-based application where it's crucial to have real-time > execution of serial writeouts and audio, as well as keeping a > continual poll on the input from the same port....can this be done > successfully in Python? Does using Tkinter have anything to do with > my timing issues? Would it benefit me to move over to wxPython > (something I've been considering doing)? As for the metronome, should > I incorporate the metronome thread into the "song processing" thread, > since both are dealing with events whose timing is crucial? I think you can't really do that, not just because of Python but also as a result of using a multitasking OS that's not especially designed for real time. You have to rely on some buffering in the audio hardware, so you don't have to be sample-accurate with the timings. From eric_brunel at despammed.com Fri Feb 2 10:26:02 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 02 Feb 2007 16:26:02 +0100 Subject: Tkinter Scrolling References: <1170333328.141317.275130@q2g2000cwa.googlegroups.com> <2007020112161316807-bob@passcalnmtedu> <1170357968.405171.14410@h3g2000cwc.googlegroups.com> Message-ID: On Thu, 01 Feb 2007 20:26:08 +0100, D wrote: > Bob Greschke wrote: >> The typical way to do it is to make a scrolling canvas and >> pack the buttons and other stuff into an empty Frame() and then pack >> the frame on to the canvas, which I haven't had to do yet. >> >> Bob > Thanks, Bob - have you seen any examples of the latter approach (using > a canvas and frame)? Sounds rather confusing, but it definitely seems > like the approach I need to take. Thanks again. Here you are: ----------------------------------------------------------- from Tkinter import * ## Main window root = Tk() ## Grid sizing behavior in window root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) ## Canvas cnv = Canvas(root) cnv.grid(row=0, column=0, sticky='nswe') ## Scrollbars for canvas hScroll = Scrollbar(root, orient=HORIZONTAL, command=cnv.xview) hScroll.grid(row=1, column=0, sticky='we') vScroll = Scrollbar(root, orient=VERTICAL, command=cnv.yview) vScroll.grid(row=0, column=1, sticky='ns') cnv.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll.set) ## Frame in canvas frm = Frame(cnv) ## This puts the frame in the canvas's scrollable zone cnv.create_window(0, 0, window=frm, anchor='nw') ## Frame contents for i in range(20): b = Button(frm, text='Button n#%s' % i, width=40) b.pack(side=TOP, padx=2, pady=2) ## Update display to get correct dimensions frm.update_idletasks() ## Configure size of canvas's scrollable zone cnv.configure(scrollregion=(0, 0, frm.winfo_width(), frm.winfo_height())) ## Go! root.mainloop() ----------------------------------------------------------- HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From wojciech_mula at poczta.null.onet.pl.invalid Wed Feb 7 08:10:15 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Wed, 7 Feb 2007 13:10:15 +0000 (UTC) Subject: Vim search under cursor References: <1170846259.673825.26420@a34g2000cwb.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > Hi, I am using gvim to edit python source files. When I press "*" or > "#", I would want to search for the attribute name under the cursor > and not the entire string. > For example, If I have os.error and pressing * on top of error > searches for os.error rather than error. How to set this, any Idea? Press / then Ctrl-R-A then enter -- of course you should recored it as a macro. w. From lionchao at gmail.com Sun Feb 4 06:10:13 2007 From: lionchao at gmail.com (Eric CHAO) Date: Sun, 4 Feb 2007 19:10:13 +0800 Subject: when will python 2.5 take in mainstream? Message-ID: A lot of application based on python claim that python 2.3 or 2.4 is needed not 2.5, ie. mysqldb. I've been using python for months. I don't care about 2.4 or 2.5. But I like the default icons of python in 2.5. So I just use that, but some scripts can't work on that. When will all these applications support 2.5? Thanks. From widgeteye at yahoo.com Sat Feb 24 10:45:16 2007 From: widgeteye at yahoo.com (Schnizalfritz) Date: 24 Feb 2007 07:45:16 -0800 Subject: INSTALL ODDITIES Message-ID: <1172331916.071459.324490@k78g2000cwa.googlegroups.com> When I built python 2.5 for linux I did the normal: configure make make install Everything went fine til the "make install" part. It dies with no error. just says "install failed" after this: Compiling /usr/local/lib/python2.5/zipfile.py That part built fine but the next part failed. So what I did being the industrious fellow that I am I did: make -n install > out Took the out file and did: sh out That installed python without failure. Now if I do "make install" everything works fine. Weird eh? From http Fri Feb 2 14:53:59 2007 From: http (Paul Rubin) Date: 02 Feb 2007 11:53:59 -0800 Subject: more examples on lamba References: <2006330.mqpy8evNZf@teancum> Message-ID: <7xmz3w9vzc.fsf@ruckus.brouhaha.com> David Bear writes: > Can anyone point me to more web stuff that describes more deeply > lamba's and making high order functions -- functional programming > styles. I suggest Abelson and Sussman's book Structure and Interpretation of Computer Programs. The text is online here: http://mitpress.mit.edu/sicp/ This is a full length textbook but if you get all the way through it you'll really understand some stuff. From uymqlp502 at sneakemail.com Wed Feb 21 19:53:24 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 21 Feb 2007 16:53:24 -0800 Subject: jython import search path In-Reply-To: References: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> Message-ID: <1172105604.157543.191450@k78g2000cwa.googlegroups.com> On Feb 21, 4:15 pm, Larry Bates wrote: > Russ wrote: > > I have a Python program that I want to run in Jython so I can get Java > > bytecode output. The program runs fine in Python, but when I change > > the first line of the main program to make it run in Jython, it fails > > to find some of the imported modules. These are just plain Python > > imports of code I wrote myself in another directory. > > > Apparently Jython does not use the PYTHONPATH environment variable. I > > created an environment variable called JYTHONPATH just to see what > > would happen, but it didn't work either. How am I supposed to tell > > Jython where to search for imported modules? Thanks. > > Maybe Jython expert has the perfect answer but til then. > > Did you try: > > sys.path.append('path to search') > > Usually this works if nothing else does. > > -Larry Thanks. That's a good workaround, but I would like to know the "correct" way to do it too if anyone out there knows. From python at hope.cz Sat Feb 17 06:08:25 2007 From: python at hope.cz (Johny) Date: 17 Feb 2007 03:08:25 -0800 Subject: HTTP_REFERER value In-Reply-To: References: <1171701486.540940.151990@h3g2000cwc.googlegroups.com> Message-ID: <1171710505.115388.211900@t69g2000cwt.googlegroups.com> On Feb 17, 10:21 am, Roel Schroeven wrote: > Johny schreef: > > > Is HTTP_REFERER value transfered between different domains? > > For example if I come to a website , say,www.python.org, from > > website www.microsoft.com > > willwww.python.orgfinds that I came there fromwww.microsoft.com? > > If you get fromwww.microsoft.comtowww.python.orgby clicking a link > on Microsoft's website, yes. If you get towww.python.orgby manually > typing in the URL or by using a bookmark, no. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven Thank you both for help. L From michaelbohansen at gmail.com Mon Feb 5 08:42:18 2007 From: michaelbohansen at gmail.com (Michael Bo) Date: 5 Feb 2007 05:42:18 -0800 Subject: Watch folder for new file and execute extern program Message-ID: <1170682938.056015.238000@p10g2000cwp.googlegroups.com> Hi. Can anyone guide me on how to minitor a folder for new files? And when they appear I need to run and externe program with the file just created (buy a 3rd program). - Michael Bo From grante at visi.com Mon Feb 12 13:29:53 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 12 Feb 2007 18:29:53 -0000 Subject: can't find a way to display and print pdf through python. References: <12t17gsjh6vgh94@corp.supernews.com> Message-ID: <12t1ch1n8hj9n69@corp.supernews.com> On 2007-02-12, Larry Bates wrote: > On 2007-02-12, Larry Bates wrote: >> >>>> I at least need the code for useing some library for >>>> connecting to acrobat reader and giving the print command on >>>> windows and some thing similar on ubuntu linux. >> >>> Just let the registered .PDF viewer do it for you. >>> >>> os.start('myfile.pdf') >> >> Eh? I don't see os.start() it either 2.5 or 2.44 >> documentation, and it's sure not there in 2.4.3: > > My bad. os.system() That doesn't work either: $ ls -l user.pdf -rw------- 1 grante users 35640 2005-11-21 14:33 user.pdf $ python Python 2.4.3 (#1, Dec 10 2006, 22:09:09) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.system('user.pdf') sh: user.pdf: command not found 32512 >>> -- Grant Edwards grante Yow! Eisenhower!! Your at mimeograph machine upsets visi.com my stomach!! From joshua at eeinternet.com Mon Feb 26 19:59:45 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 26 Feb 2007 15:59:45 -0900 Subject: getting terminal display size? References: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> <12u4g4ci5gqu46c@corp.supernews.com> <12u4gbepet1ek62@corp.supernews.com> <1172537489.610807.288630@p10g2000cwp.googlegroups.com> Message-ID: <45e375f2$0$16394$88260bb3@free.teranews.com> jeff wrote: > I don't really understand any of that; can you right me a function > that'll return the size as a tuple? Did you even *try* his code? I ran this: import termios, fcntl, struct, sys s = struct.pack("HHHH", 0, 0, 0, 0) fd_stdout = sys.stdout.fileno() x = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s) print '(rows, cols, x pixels, y pixels) =', print struct.unpack("HHHH", x) And got this result: (36, 96, 0, 0) Looks like a tuple to me. return 'return' instead of 'print' the result. We don't mind helping, but it's nice to know that the user has made some attempt to understand what is going on before asking for free work to be done. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From tleeuwenburg at gmail.com Sun Feb 4 18:23:37 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 4 Feb 2007 15:23:37 -0800 Subject: when will python 2.5 take in mainstream? In-Reply-To: <4Rrxh.18423$pQ3.12414@newsread4.news.pas.earthlink.net> References: <4Rrxh.18423$pQ3.12414@newsread4.news.pas.earthlink.net> Message-ID: <1170631417.253200.136330@h3g2000cwc.googlegroups.com> When they have to ... One of the big things about Python is that its penetration slows it down. There's more legacy code and interdependant systems around now that Python is more successful and more mature. Here's a thought -- perhaps it would be worth having some good ways to interact with Python from Python. Suppose you have some 2.4 code someplace, interacting with your mysqldb or whatever, and you don't want to rewrite it. So long as you have some kind of object broker, you could (plausibly) leave your 2.4 apps running with the old interpreter, but wrap them for Python 2.5 and use that in your new development. Ditto 3.0. Rather than having to re-write every interacting component, maybe it could be straightforward to all Python2.4 from Python2.5 to execute particular library calls. I'm not an expert, I don't know how you'd build such a system, but I do know that re-writing stuff is a real pain. Perhaps APIs for 2.5 and 3.0 could have a special version flag, and if not present or not compatible, a 2.4 interpreter could be called instead... Cheers, -T On Feb 5, 8:01 am, Dennis Lee Bieber wrote: > On Sun, 4 Feb 2007 19:10:13 +0800, "Eric CHAO" > declaimed the following in comp.lang.python: > > > When will all these applications support 2.5? > > cynical answer: when you download the sources and build them against > the 2.5 headers > > In the case of MySQLdb, one problem is that, as I recall, the > primary author does not have a Windows compatible build environment and > essentially relies upon others doing the Linux port to Windows and > releasing pre-built installers. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From Garrick.Peterson at zootweb.com Fri Feb 2 16:00:16 2007 From: Garrick.Peterson at zootweb.com (Garrick.Peterson at zootweb.com) Date: Fri, 2 Feb 2007 14:00:16 -0700 Subject: division by 7 efficiently ??? In-Reply-To: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: >How to divide a number by 7 efficiently without using - or / operator. >We can use the bit operators. I was thinking about bit shift operator >but I don't know the correct answer. It may not be efficient, but the easiest solution (without using tricks from a particular languages) is to increment a value within a while loop which checks it against the target value. More efficient may be to pick an arbitrary value, and check for greater than or less than, modifying the range based off your results (much like a recursive search). However, having done a tour with EA, I would have to say that you're probably better off not making it. Though they're getting better. =) Garrick M. Peterson Quality Assurance Analyst Zoot Enterprises, Inc. Copyright ? 2007 Zoot Enterprises, Inc. and its affiliates. All rights reserved. This email, including any attachments, is confidential and may not be redistributed without permission. If you are not an intended recipient, you have received this message in error; please notify us immediately by replying to this message and deleting it from your computer. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nulla.epistola at web.de Mon Feb 12 09:12:06 2007 From: nulla.epistola at web.de (Hertha Steck) Date: Mon, 12 Feb 2007 15:12:06 +0100 Subject: interacting with shell - another newbie question In-Reply-To: <%hfzh.53050$QU1.17723@newssvr22.news.prodigy.net> References: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> <0e2dnUM6nIWq41DYRVnzvA@telenor.com> <%hfzh.53050$QU1.17723@newssvr22.news.prodigy.net> Message-ID: James Stroud schrieb: > > Yes, and finding ways to have employees pointlessly waste time is equal > to simply removing them. Not as long as they are paid for the wasted time. From ruan at jcmills.com Wed Feb 7 13:00:09 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Wed, 7 Feb 2007 13:00:09 -0500 Subject: Why doesn't my heapify work? Message-ID: I want to turn an Array into a heap, but my code just doesn't work: no change after execution. A=[3,5,4,9,6,7] m=len(A)-1 for i in range(m,1): t=(i-1)/2 if A[i]>A[t]: A[i],A[t]=A[t],A[i] From troy.melhase at gmail.com Mon Feb 19 07:49:07 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Mon, 19 Feb 2007 03:49:07 -0900 Subject: ANN: java2python 0.2 In-Reply-To: <1171876979.192320.271500@q2g2000cwa.googlegroups.com> References: <1171876979.192320.271500@q2g2000cwa.googlegroups.com> Message-ID: > Hi Troy. What is the rationale for your project? Hi Kay, I maintain a python port of a java library. It finally got too complicated to do by hand, so I wrote java2python to make my life easier. I wrote more extensively about the library and this tool in my blog: http://blog.melhase.net/articles/2007/02/15/automated-translation-of-java-to-python I haven't documented the tool and all of it's configuration options in detail; please let me know if I can explain something further. From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 16:01:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 22:01:54 +0100 Subject: Sorting a list In-Reply-To: <45c245e1$0$31965$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> Message-ID: <45c24e49$0$29592$426a74cc@news.free.fr> John Salerno a ?crit : > Bruno Desthuilliers wrote: > >> John Salerno a ?crit : >> >>> Hi everyone. If I have a list of tuples, and each tuple is in the form: >>> >>> (year, text) as in ('1995', 'This is a citation.') >>> >>> How can I sort the list so that they are in chronological order based >>> on the year? >> >> >> Calling sort() on the list should just work. > > > Amazing, it was that easy. :) A very common Python idiom is "decorate/sort/undecorate", which is just what you've done here. It's usually faster than passing a custom comparison callback function (cf a recent thread named "Sorting a List of Lists, where Paddy posted a link to a benchmark). From deets at nospam.web.de Thu Feb 22 06:53:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 12:53:11 +0100 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> Message-ID: <545eh7F1veg84U1@mid.uni-berlin.de> openopt at ukr.net wrote: > I don't know to which forum should I post the message > I hope someone related to the Python kernel development will read & > consider the idea > I'm (a former? meanwhile not sure) MATLAB user & it's very annoing > typing each time for example > while i: > print i > ... > instead of > while i > print i > ... > of course if all is written in a single line ':' I guess should not be > omited Won't happen. There have been plenty of discussions about this, and while technically not necessary, the colon is usually considered "optically pleasing". So - it will stay. See - one of a bazillion - discussions here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d3784563657ad18b/35581ad9698e28f5?lnk=st&q=python+colon+remove&rnum=1#35581ad9698e28f5 Diez From malaclypse2 at gmail.com Fri Feb 23 18:34:32 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 23 Feb 2007 18:34:32 -0500 Subject: Having multiple instances of a single application start a single instance of another one In-Reply-To: <45df6b91$0$487$cc7c7865@news.luth.se> References: <45df6400$0$489$cc7c7865@news.luth.se> <45df6b91$0$487$cc7c7865@news.luth.se> Message-ID: <16651e80702231534h57bd383fma3af04f8d4473fcb@mail.gmail.com> On 2/23/07, buffinator wrote: > 2. How do I check if a process ID is bound to a running application. Under windows, this should work: >>> import win32process >>> running_pids = win32process.EnumProcesses() >>> running_pids (0, 4, 1048, 1496, 1656, 1836, 1896, 756, 988, 1712, 220, 1156, 240, 1600, 1932, 428, 1100, 1880, 1152, 1444, 296, 624, 536, 412, 1812, 3384, 2064, 2164, 2344, 2516, 2816, 2992, 3412, 3628, 2836, 3168, 3420, 3408, 816, 1676, 504, 3244, 2404, 452, 1624, 3924, 2660, 3736, 3608, 1304) -- Jerry From steve at holdenweb.com Sun Feb 11 02:14:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 07:14:08 +0000 Subject: pygame and python 2.5 In-Reply-To: <1171146974.180146.292500@l53g2000cwa.googlegroups.com> References: <17868.46349.59089.178486@montanaro.dyndns.org> <013b01c74cd8$8d913860$03000080@hendrik> <1171146974.180146.292500@l53g2000cwa.googlegroups.com> Message-ID: Ben Sizer wrote: > On Feb 10, 8:42 am, Steve Holden wrote: >> Hendrik van Rooyen wrote: >>> wrote: >>> "Ben Sizer" wrote: >>>> Ben> Python extensions written in C require recompilation for each new >>>> Ben> version of Python, due to Python limitations. >>>> Can you propose a means to eliminate this limitation? >>> Yes. - Instead of calling something, send it a message... >> I suppose you are proposing to use the ISO 19999.333 generic >> message-passing interface for this? The one that doesn't actually call a >> function to pass a message? > > I'm assuming you're being facetious here..? > You're right. > Of course, functions get called at the ends of the message passing > process, but those functions can stay the same across versions while > the messages themselves change. The important part is reducing the > binary interface between the two sides to a level where it's trivial > to guarantee that part of the equation is safe. > > eg. > Instead of having PySomeType_FromLong(long value) exposed to the API, > you could have a PyAnyObject_FromLong(long value, char* > object_type_name). That function can return NULL and set up an > exception if it doesn't understand the object you asked for, so Python > versions earlier than the one that implement the type you want will > just raise an exception gracefully rather than not linking. > > The other issue comes with interfaces that are fragile by definition - > eg. instead of returning a FILE* from Python to the extension, return > the file descriptor and create the FILE* on the extension side with > fdopen. > I agree that the coupling is rather tight at the moment and could do with being loosened to the degree you suggest. My previous post was a knee-jerk reaction to the suggestion that substituting one mechanism for another equivalent one would, by itself, solve anything. I am staying away from the Py3.0 discussions at the moment - does anybody know whether this problem is being addresses there? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From paddy3118 at googlemail.com Sun Feb 25 13:00:31 2007 From: paddy3118 at googlemail.com (Paddy) Date: 25 Feb 2007 10:00:31 -0800 Subject: Nested Parameter Definitions Message-ID: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> I blogged on finding a new-to-me feature of Python, in that you are allowed to nnest parameter definitions: >>> def x ((p0, p1), p2): ... return p0,p1,p2 ... >>> x(('Does', 'this'), 'work') ('Does', 'this', 'work') >>> Ruben commented that there was a poll on this features continued existence taken at PyCon and it could go. Just as I found it, it could go I wondered if those of you with some Python experience new of nested parameters and don't use them; or just forgot/don't know it is possible? - Paddy. Oh - the blog entry is at http://paddy3118.blogspot.com/2007/02/pythons-function-nested-parameter.html From bjourne at gmail.com Sun Feb 11 20:42:56 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 12 Feb 2007 02:42:56 +0100 Subject: compound statement from C "?:" In-Reply-To: <1171241827.381736.31580@s48g2000cws.googlegroups.com> References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> <1171232208.939808.33890@j27g2000cwj.googlegroups.com> <1171241827.381736.31580@s48g2000cws.googlegroups.com> Message-ID: <740c3aec0702111742u5bffb1dbx7bf1c49434f092af@mail.gmail.com> On 11 Feb 2007 16:57:07 -0800, Carl Banks wrote: > You don't need any ternary operator to avoid repetition, anyways. You > could factor the common parts out like this: > > if n == 1: > what = "a car" > else: > what = "%d cars" % n > print "I saw %s" % what Or even better (IMHO): what = "%d cars" % n if n == 1: what = "a car" print "I saw %s" % what One less line and just as readable. > but what's the point? It's just a few repeated characters two lines > apart. Peter's version is the most easily read version here, > including the one using the official ternary operator. Agreed. -- mvh Bj?rn From bj_666 at gmx.net Sun Feb 4 04:04:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 04 Feb 2007 10:04:37 +0100 Subject: confused about resizing array in Python References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: In , Dongsheng Ruan wrote: > This seems to be clever to use reference for list. > > Is it unique to Python? No of course not. Java is very similar in only passing references around for objects. And `ArrayList` and `Vector` behave similar to Python lists. > How about the traditional programming languages like C, Pascal or C++? For a start they don't have a built in list type. C and Pascal don't even have one in the standard library. C++ has STL vectors and if you, the programmer, decide to store pointers in it instead of structures or objects then you have something like Python's list type. Ciao, Marc 'BlackJack' Rintsch From kooch54 at gmail.com Wed Feb 7 13:27:04 2007 From: kooch54 at gmail.com (kooch54 at gmail.com) Date: 7 Feb 2007 10:27:04 -0800 Subject: Group Membership in Active Directory Query In-Reply-To: References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> <1170859017.416570.247920@v33g2000cwv.googlegroups.com> Message-ID: <1170872824.710879.272830@v45g2000cwv.googlegroups.com> On Feb 7, 11:56 am, Uwe Hoffmann wrote: > kooc... at gmail.com schrieb: > > > ldap_obj = ldap_obj.simple_bind_s('usern... at domain.company.com', > > 'password') > > > AttributeError: 'NoneType' object has no attribute 'search_Ext_s' > > dummy = ldap_obj.simple_bind_s('usern... at domain.company.com', > 'password') > or better simply > ldap_obj.simple_bind_s('usern... at domain.company.com', > 'password') First and foremost thanks for the feedback. Although I don't appreciate the slight dig at me. dummy = ldap_obj.simple_bind...... I tried your second recommendation of using ldap_obj.simple_bind_s('usern... at domain.company.com','password') Now I get the following error even after the bind operation seems to complete successfully. result = func(*args,**kwargs) OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C0905FF, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'} Thanks again... From deets at nospam.web.de Thu Feb 1 12:27:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Feb 2007 18:27:11 +0100 Subject: LDAP/LDIF Parsing References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> Message-ID: <52em7fF1o07g9U1@mid.uni-berlin.de> > > I was wondering the best way to do this? I have installed and used the > python-ldap libraries and these allow me to access and search the > server, but the searches always return a horrible nesting of lists, > tuples and dictionaries, below is an example of returning just one > record - > > ('dc=example,dc=com', {'objectClass': ['top', 'dcObject', > 'organization'], 'dc': ['example'], 'o': ['Example Organisation']}) But this is exactly what your LDAP-record contains. What else should there be? And no, you don't need a parser, as the above _is_ the parsed result. No parser can possibly give you anything else. You can of course create wrapper-objects, that you instantiate based on the values in 'objectClass', and that allow convenient access to certain properties. Yet this is entirely up to you, as there is no one else who can forsee how things should look and work like in _your_ application. Diez From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 15:33:51 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 21:33:51 +0100 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: <1172519353.960277.232450@t69g2000cwt.googlegroups.com> References: <1172519353.960277.232450@t69g2000cwt.googlegroups.com> Message-ID: Ziga Seilnacht wrote: > The second example uses your approach and is a bit more cumbersome, > but still works. Could you post your current version of the code? > I don't understand where your problem could be. I think, there's no need to. Now I understand :) > if (!PyArg_ParseTuple(args, "Oid", &coord, > &iteration_number, &bailoutsquare)) There was no ampersand in my version before coord. I thought that as coord is already a pointer, PyArg_ParseTuple will want it, not the pointer to the pointer. Now it works, but I will of course change it to get the simpler parenthesised version as in your Example 1. Great thanks :D zefciu From sturlamolden at yahoo.no Mon Feb 19 06:22:20 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 19 Feb 2007 03:22:20 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> Message-ID: <1171884140.039778.142400@l53g2000cwa.googlegroups.com> On Feb 17, 1:34 am, Stef Mientki wrote: > - designing the GUI will cost me about 2 .. 3 times as much in Python Use a design tool like GLADE for PyGTK, wxGlade for wxPython or Komodo for tkinter. The more of the GUI code you can remove from your functional code the better. GUI code tends to clutter up the functional code. Have you ever tried to make changes in an MFC project? The optimal solutions are Microsoft's 'Avalon' and GTK/ libglade, where all GUI code are placed inside an XML resource. The second thing is that GUIs are made very differently in Python and traditional Windows tools like Delphi and VS.NET. Most Python toolkit have a concept of 'layout managers' that will size and lay out the widgets for you. In Delphi and VB you will typically drag and drop controls on a form, and use anchors and docking and manually size the controls. You are therefore much more dependent on graphical GUI design in these environments. In Python toolkits, the layout manager do all this work for you. Layout managers are also found in Java toolkits like Swing and SWT. In order to make effective GUIs in Python you must learn to use these, and forget about all the bad habits Delphi thought you. Try to imagine the GUI as a tree of containers, where the widgets reside on the leafs, instead of controls dropped on a form. When you can do that in your head, you can make GUIs more quickly in Python than VB or Delphi. The main advantages to using layout managers are: GUIs are less tedious to develop, you don't have to worry about resizing and adapting to different screen sizes, and large projects become easier to maintain. > - Python is not capable of doing everything I need > (almost all interactive actions are very primitive and crashes a lot) > - designing my other functional code in Python, > will reduce the development time with an estimated factor of 2 > So the combination of Delphi (or VB) and Python seems the optimal combination for heavily GUI's. > - one of the big problems with Python is the version differences (compatibility) > > In one of the other threads, Dabo was meant as a GUI designer, > I tried it yesterday, > and although it looks very promising, > at the moment this is not a graphical design environment, > just a complex (compared to Delphi) design environment with graphical feedback. > Just my 2 cents ;-) > > > > >> (although others in this group will definitely have a different opinion), > >> the beautiful thing about Python is, > >> that you can easily embed /encapsulate it in VB, > >> giving you the best of both worlds. > > > Why would one go thru the pain of "embedding" Python in VB (if that's > > even possible) when Python can directly access the Win32 API and all COM > > components and have bindings for GUI toolkits like wxWidgets ? > > "Pain of embedding" ? > About 10 lines of code, which you find ready to use on the web ;-) > And the performance is fantastic ! > (I even use it for realtime, as a complete replacement for MatLab and LabView) > > Bruno, I think we've a different audience / target application, > and at the moment we'll never agree about GUI, > but I promise that'll try the different Python graphics in the future, > and you will be the first to hear if my current conclusions are wrong. > > cheers, > Stef From chris.cavalaria at free.fr Tue Feb 27 05:29:47 2007 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 27 Feb 2007 11:29:47 +0100 Subject: Pep 3105: the end of print? In-Reply-To: <45E3B892.2040007@v.loewis.de> References: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> <45E3B892.2040007@v.loewis.de> Message-ID: <45e40823$0$14158$426a34cc@news.free.fr> Martin v. L?wis a ?crit : > Neil Cerutti schrieb: >> On 2007-02-23, I V wrote: >>> While that's true, C++ compiler vendors, for example, take >>> backwards compatibility significantly less seriously, it seems >>> to me. >> Compiler vendors usually take care of their customers with >> compiler switches that enable backwards compatibility. > > That's a bold statement, after I V already gave two examples > (g++ and MSVC 2005) of compilers that broke backwards compatibility > without providing compiler switches to bring it back. These two > aren't "minor" compilers. In C++ land, people are expected to fix their code and not use broken compilers in such situations. They have some kind of moral high ground because they do not break compatibility just for that but to be more standards compliant. And the fact that all the C++ code I've written with g++ recently compiled perfectly on Visual 2005 without a single change ( except fixing new warnings ) shows that standard compliance in C++ compilers is a good thing to have. That same code had some major and very annoying breakage with Visual 6. The fix? Updating that outdated compiler. From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 15:28:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 21:28:55 +0100 Subject: Can somebody give me a python code for this? In-Reply-To: References: Message-ID: <45ca2f62$0$1620$426a74cc@news.free.fr> John a ?crit : > Given an array of elements, look at it as a binary tree. Start at the last > interior node, and downheap it. Then downheap the previous interior node, > and continue in this fashion, up to the root. > > http://www.catb.org/~esr/faqs/smart-questions.html#homework From gert.cuykens at gmail.com Thu Feb 8 17:17:42 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Thu, 8 Feb 2007 23:17:42 +0100 Subject: def obj() In-Reply-To: <45cb9d24$0$6842$4d3efbfe@news.sover.net> References: <45cb9d24$0$6842$4d3efbfe@news.sover.net> Message-ID: On 2/8/07, Leif K-Brooks wrote: > def obj(): > result = {'data': 'hello'} > result['add'] = adder(result) > return result > > def adder(obj): > def add(value): > obj['data'] += value > return add > > if __name__ == '__main__': > test = obj() > test['add']('world') > print test['data'] Nice :) Does anybody know how this would look in c code ? From david at boddie.org.uk Mon Feb 12 17:07:43 2007 From: david at boddie.org.uk (David Boddie) Date: Mon, 12 Feb 2007 23:07:43 +0100 Subject: irclib problems References: <28idnXfKwMtLTlPYRVnzvA@telenor.com> Message-ID: <6f633$45d0e531$54d1d767$458@news.chello.no> On Sunday 11 February 2007 09:29, Tina I wrote: > I'm playing around with the 'irclib' library working with the first > example at > http://www.devshed.com/c/a/Python/IRC-on-a-Higher-Level-Concluded/ > > When copying the example verbatim and running it from a console it works > flawlessly. It connects to the server, join the channel and sits there > 'forever'... OK. So it works on its own. > However, I want to use it in a PyQt application and have done the > following. I have created a module named 'irclibtest.py' that looks like > this: [...] class Conn: ?????def?__init__(self): ?????????#?Network?information ?????????self.network?=?'192.x.x.x' ?????????self.port?=?6667 ?????????self.channel?=?'#test' ?????????self.nick?=?'IRClibt' ?????????self.name?=?'Python?Test' ?????????#?Subclass?SimpleIRCClient ?????????class?ClientClass?(?irclib.SimpleIRCClient?): ?????????????pass ?????????#?Create?an?instance?of?ClientClass?and?connect. ?????????self.client?=?ClientClass() ?????????self.client.connect?(?self.network,?self.port,?self.nick, ircname = self.name ) ?????????self.client.connection.join?(?self.channel?) [...] > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > f = TircMain() > f.show() > sys.exit(app.exec_()) > ### Main application end ## > > The problem is that this pings out (PING timeout). As far as I > understand it rclib.SimpleIRCClient is supposed to handle PING-PONG with > the server so I don't understand why it does not in my Qt test, but it > does 'raw'. You don't call self.client.start() anywhere. Even if you did, you would still have problems because you need to call app.exec_(), and this would only happen after self.client.start() returns - if ever. > I can send to the channel right up to the point it times out by the way. I think this is just a result of the way the IRC protocol works. > Anyone know what I'm missing here? You have an application with two event loops, and you can't run them both in the usual way. If SimpleIRCClient has a method that only processes pending events and returns immediately afterwards, you could create a QTimer, connect its timeout() signal to that method, and make it fire every half a second or so, to ensure that the client doesn't time out. There may be other solutions with threads, but things could get quite complicated. Making one event loop play well with the other is probably the best approach to take. David From rshepard at nospam.appl-ecosys.com Wed Feb 7 23:01:38 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 8 Feb 2007 04:01:38 GMT Subject: 'IF' Syntax For Alternative Conditions Message-ID: All my python books and references I find on the web have simplistic examples of the IF conditional. A few also provide examples of multiple conditions that are ANDed; e.g., if cond1: if cond2: do_something. However, I cannot find, nor create by trial-and-error, the syntax for alternative conditions that are ORed; e.g., if cond1 OR if cond2: do_something. I've tried using the C syntax for OR (||) but python complained. I'm sure there's a way to do this rather than using if cond1: elif cond2: both with the same code to execute. Please pass me a pointer so I can learn how to correctly write this. Rich From exarkun at divmod.com Thu Feb 8 11:29:23 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 8 Feb 2007 11:29:23 -0500 Subject: postgres backup script and popen2 In-Reply-To: <1170951829.472924.65040@q2g2000cwa.googlegroups.com> Message-ID: <20070208162923.25807.2124126750.divmod.quotient.14646@ohm> On 8 Feb 2007 08:23:49 -0800, Gabriel Genellina wrote: >On 8 feb, 10:27, Ma?l Benjamin Mettler wrote: > >> flupke schrieb: >> > i made a backup script to backup my postgres database. >> > Problem is that it prompts for a password. It thought i >> > could solve this by using popen2. >> >> Use pexpect:http://pexpect.sourceforge.net/ > >pexpect could work. But a better way would be to supply the password >on the command line. So that it shows up in `ps' output to anyone on the system? :) Jean-Paul From bruno.desthuilliers at gmail.com Tue Feb 13 05:04:56 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 13 Feb 2007 02:04:56 -0800 Subject: Newbie Question In-Reply-To: <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> Message-ID: <1171361096.528759.231380@a34g2000cwb.googlegroups.com> On 12 f?v, 15:59, Stef Mientki wrote: > bruno.desthuilli... at gmail.com wrote: > > On 9 f?v, 14:06, Stef Mientki wrote: > >>>> will explain the rest > >>> Delphi is a (dying) proprietary, MS-Windows-only[1] software relying > >>> on a low-level language. > >> Well it may be dying, > >> but for the moment it beats Python with a factor of 10, > >> when it comes to user (the majority of PC users) friendly GUI ;-) > > > Would you mind explaining yourself and backing your above assertion ? > > Like, ie, on which points does Delphi "beats" Python wrt/ GUIs, what > > special magic would make so that GUIs designed with Delphi would be > > more "user-friendly", and where does this "factor 10" comes from ? > > Maybe I should have written it in quotes "factor of 10" ;-) > But here are a few points > - in Delphi the GUI design itself is done in a graphical environment, Ever heard of Glade, wxGlade, QTDesigner etc ? Please stop confusing language, GUI Toolkit, and GUI Designer... > making it much easier and faster making it much easier to get a quick prototype. Then, hacking the source may become *much* more "easy and faster"... (my experience with other windows clickodromes). > - auto-scaling of components on a form is very easy (so if the user changes form size ..) And ? > - even making everything on a form movable by the end-user is just 1 mouse-click I wouldn't like to make "everything movable by the end-user"... > - using the designers style, or the user style is just 1 click > - very good feedback, so creating interactive graphs is very easy, cross-hair, slopes, region of > interest etc. > - a very huge collection of controls is standard available > - print / clipboard / export to almost any graphical file format, just 1 line of code > > but to be honest ... > ... I never even tried to write a GUI in Python, ... Seems quite obvious. > ... just looked at others examples, > ... and still not seen what I can perform in Delphi ;-) IOW, you assert things just based on your experience with Delphi and your lack of experience with any of the major GUI toolkits availables from Python. To be true, I don't know if any of these toolkits (GTK, wxWindows, QT) and their GUIDesigners have the features you like in Delphi. What I know is that: 1/ these three toolkits have everything *needed* to write serious GUI apps 2/ they are all (more or less) portable 3/ the first two are free software 4/ they are all (more or less) language-independant So talking about GUIs, I think we're really far from "a factor of 10". It may be possible that Delphi has a better GUI *designer* than some other GUI toolkits, but that's far from being a major concern as far a I'm concerned - I wouldn't choose my tools based only on this consideration. From kyosohma at gmail.com Mon Feb 5 14:10:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Feb 2007 11:10:33 -0800 Subject: Unicode formatting for Strings In-Reply-To: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> References: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> Message-ID: <1170702633.369037.90230@a34g2000cwb.googlegroups.com> On Feb 5, 11:55 am, robson.cozendey... at gmail.com wrote: > Hi, > > I?m trying desperately to tell the interpreter to put an '?' in my > string, so here is the code snippet: > > # -*- coding: utf-8 -*- > filename = u"Ataris Aqu?ticos #2.txt" > f = open(filename, 'w') > > Then I save it with Windows Notepad, in the UTF-8 format. So: > > 1) I put the "magic comment" at the start of the file > 2) I write u"" to specify my unicode string > 3) I save it in the UTF-8 format > > And even so, I get an error! > > File "Ataris Aqu?ticos #2.py", line 1 > SyntaxError: Non-ASCII character '\xff' in file Ataris Aqu?ticos #2.py > on line 1 > , but no encoding declared; seehttp://www.python.org/peps/ > pep-0263.html for det > ails > > I don?t know how to tell Python that it should use UTF-8, it keeps > saying "no encoding declared" ! > > Robson I can't tell from your email if you get the message when you try to open or close the file. So, I recommend that you read the following article as it explains the whole unicode business quite well: http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html From Shawn at Milochik.com Sat Feb 10 12:08:15 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Sat, 10 Feb 2007 12:08:15 -0500 Subject: Hacking in python In-Reply-To: References: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> Message-ID: <2dc0c81b0702100908i2353ddd4x6459f100ba63af3@mail.gmail.com> On 2/10/07, hg wrote: > Calvin Spealman wrote: > > > http://en.wikipedia.org/wiki/Hacker_%28disambiguation%29 > > > > Educate yourself on what hacking actually is. We're all hackers, > > because it just means we get the most out of code, enjoy pushing our > > technology to the limit, and generally love programming. The term has > > been abused by the media and you don't do much more than show your own > > naiveness by asking such a question. You also do a great job of > > insulting everyone on this list. > > > > On 2/10/07, enes naci wrote: > >> > >> i would like to know about hacking in python too whether its illegal > >> or not is not the point and anyway it doesn't mean i'm gong to use it. > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > -- > > Read my blog! I depend on your acceptance of my opinion! I am interesting! > > http://ironfroggy-code.blogspot.com/ > > > So that was that weird feeling I felt ... insulted > > hg > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm surprised you all didn't just tell him how to become a hacker. That's what he wants, right? Here's the hacker info. Enjoy! http://www.catb.org/~esr/faqs/hacker-howto.html Shawn From bdesth.quelquechose at free.quelquepart.fr Thu Feb 8 15:20:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 21:20:29 +0100 Subject: default mutable arguments In-Reply-To: References: Message-ID: <45cb7ee0$0$26748$426a74cc@news.free.fr> Gigs_ a ?crit : > I read that this is not the same: > if arg is None: arg = [] > arg = arg or [] > > > def functionF(argString="abc", argList = None): > if argList is None: argList = [] # < this > ... > def functionF(argString="abc", argList=None): > argList = argList or [] # and this > ... > > Why? def test(arg=None): foo = arg or [] print "arg : ", arg, " - foo : ", foo test() test(arg=0) test(arg=False) test(arg=()) test(arg={}) test(arg='') etc... From tomas at fancy.org Thu Feb 1 22:55:55 2007 From: tomas at fancy.org (Tom Plunket) Date: Thu, 01 Feb 2007 19:55:55 -0800 Subject: need help on a data structure problem References: Message-ID: <4cd5s2do6ql0e5anuck8e6bogda8ah7627@4ax.com> Dongsheng Ruan wrote: > Not quite related with Python. But my Data Structure course is experiemented > on python and there is no data structure group, So I have to post here: > > Write a procedure (in pseudocode!) to increase the number of buckets in a > (closed) hash table. Analyze its time and space complexity. What is the question about this problem that you would like to have answered? Certainly you don't want us to actually give you the answers to your homework?!? Here's some Python code to get us started with the discussion: class HashTable: def __init__(self): self.buckets = [ [] ] @staticmethod def Hash(object): return 0 def InsertItem(self, item): self.buckets[Hash(item)].append(item) The more I think about it, the more I realize you could probably just cut'n'paste that code and that should suffice for your answer! Good luck in Computer Science! -tom! -- From paul at boddie.org.uk Sun Feb 4 09:53:27 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Feb 2007 06:53:27 -0800 Subject: Python does not play well with others In-Reply-To: <7xfy9mekxr.fsf@ruckus.brouhaha.com> References: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> Message-ID: <1170600807.504088.80150@m58g2000cwm.googlegroups.com> Paul Rubin wrote: > "Paul Boddie" writes: > > Python should only incorporate functionality in order to offer a > > coherent experience (where the omission of functionality would > > otherwise lead to a flawed experience). For example, having support > > for SSL in the socket module offers a coherent experience because it > > means that urllib and related modules can offer to support SSL-related > > URLs out of the box. > > But they can't, because the built-in socket module SSL interface > doesn't check certificates, causing total security failure if someone > spoofs the remote site. The built-in SSL functionality is broken and > users have to resort to external packages. I was really advocating improvements to the built-in SSL support, anyway, which was also what the complainant was suggesting before people started asking him mistakenly why he thought that Python was weakened by some third party packages (PyOpenSSL, M2Crypto). The choice here involves either improving the built-in support or unbundling SSL-based communications altogether. The former option obviously demands a certain amount of engineering, and then one might ask why there isn't a convenient framework for plugging in other flavours of sockets, for example, although there arguably aren't any as generally important as secure sockets. The latter option needs everyone to think about how you'd plug such stuff back into Python in a nice enough way, and then to get people to work on the right projects to provide something which does the job. > Then you have to ask why the stdlib includes anything like urllib in > the first place, under this "coherent experience" concept (I interpret > that as some kind of minimalist philosophy). Can't users have a > coherent experience if the stdlib doesn't include urllib? My own > answer is the one that I thought that the developers had settled on > years ago, namely "batteries included", i.e. ship a rich set of > libraries that provide a wide variety of useful functions, i.e. the > doctrine of minimalism has been explicitly rejected. Really, we have to ask whether including the batteries would save people a lot of work, not just in whether the end-user has to find out about an external package and then download something, but whether the logistics around developing the code, integrating it with Python, and maintaining it would be easier if people just included the stuff with Python. Here, you need some kind of consensus that feature X needs supporting and there's an approved way of supporting it which a group of people would be happy to maintain. Would it benefit the Python community (including core developers) more if Python shipped with SSL support out of the box, and would the cost of doing so ultimately be less than just pointing people at third party libraries and dealing with their problems? > We then get the question of whether to include any specific function and that's where > comparisons with other languages come in. Would it benefit the Python community more if Python shipped with MySQL support out of the box? Is it likely that a user suddenly finds him/herself needing to connect to a MySQL database? Is it more likely that the user might suddenly find him/herself needing to download from a secure site, particularly if some tool (eg. setuptools) suddenly stumbles across an https URL. Some database systems have a choice of drivers/libraries/modules (PostgreSQL has quite a few, for example): choosing a module for standard library inclusion and integrating the development can be too high a barrier for such questions of inclusion to be resolved trivially. [...] > > So, for the less forward-thinking providers a metapackage would be the > > solution, then? > > I'm not sure what you mean by metapackage but in general the goal is > to minimize the number of places that the hosting provider (or OS > distro maintainer, or whatever) On various distributions you get packages which don't actually contain anything, but which indicate a suite of packages which are to be installed. So, if you install the ubuntu-desktop package on Ubuntu systems, you get the GNOME desktop environment and all the dependencies (and a bunch of other stuff). Perhaps there should be a python-mysql-hosting package for such providers. Paul From bearophileHUGS at lycos.com Mon Feb 26 02:19:22 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Feb 2007 23:19:22 -0800 Subject: Nested Parameter Definitions In-Reply-To: <1172430363.360956.5300@q2g2000cwa.googlegroups.com> References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> <1172430363.360956.5300@q2g2000cwa.googlegroups.com> Message-ID: <1172474362.556181.291970@a75g2000cwd.googlegroups.com> Virgil Dupras: > Without the call example, I would have > had a hard time to try to figure out what these extra brackets are > for. For this reason, I think that an explicit unpack is more > readable, and thus better. I can't agree. Bye, bearophile From rpdooling at gmail.com Tue Feb 6 14:00:35 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 6 Feb 2007 11:00:35 -0800 Subject: How can I access data from MS Access? In-Reply-To: <1170672735.355295.141340@a75g2000cwd.googlegroups.com> References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> <1170672735.355295.141340@a75g2000cwd.googlegroups.com> Message-ID: <1170788435.366284.65000@m58g2000cwm.googlegroups.com> On Feb 5, 4:52 am, "Andy Dingley" wrote: > On 3 Feb, 15:43, Finger.Octo... at gmail.com wrote: > > > How to access data from MS Access? > > First of all check that the DSN is working and connects to the > back end MDB. This might not be Python's problem. > > Secondly check whatever errors you're being returned. Yes, and then move onto something like this: http://www.freelance-developer.com/howto_odbcpy rd "Give a man a fire and keep him warm for a day. Light a man on fire and he will be warm for rest of his life." --Terry Pratchett From wdraxinger at darkstargames.de Tue Feb 20 09:26:53 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Tue, 20 Feb 2007 15:26:53 +0100 Subject: Sorting directory contents References: Message-ID: Jussi Salmela wrote: > I'm not claiming the following to be more elegant, but I would > do it like this (not tested!): > > src_file_paths = dict() > prefix = sourcedir + os.sep > for fname in os.listdir(sourcedir): > if match_fname_pattern(fname): > fpath = prefix + fname > src_file_paths[os.stat(fpath).st_mtime] = fpath > for ftime in src_file_paths.keys().sort(): > read_and_concatenate(src_file_paths[ftime]) Well, both versions, mine and yours won't work as it was written down, as they neglegt the fact, that different files can have the same st_mtime and that .sort() doesn't return a sorted list. However this code works (tested) and behaves just like listdir, only that it sorts files chronologically, then alphabetically. def listdir_chrono(dirpath): import os files_dict = dict() for fname in os.listdir(dirpath): mtime = os.stat(dirpath+os.sep+fname).st_mtime if not mtime in files_dict: files_dict[mtime] = list() files_dict[mtime].append(fname) mtimes = files_dict.keys() mtimes.sort() filenames = list() for mtime in mtimes: fnames = files_dict[mtime] fnames.sort() for fname in fnames: filenames.append(fname) return filenames Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From d.lidell at gmail.com Sat Feb 10 10:55:05 2007 From: d.lidell at gmail.com (d.lidell at gmail.com) Date: 10 Feb 2007 07:55:05 -0800 Subject: wxPython libraries never detected Message-ID: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> Hi, I recently started coding with Python and I've been trying for the past hour or so to determine why, every time I "import wx" (or compile another piece of code that imports wx), Python can never find the libraries. I'm running Ubuntu Edgy 6.10, and, as per http://www.wxpython.org/download.php#sources, updated sources.list with the sources and installed python-wxgtk2.8, python-wxtools and wx2.8-i18n. I compiled the latest Python (as of writing), 2.5, from source. For example, SPE tells me that I "need to install at least wxPython v. 2.5.4.1 to run SPE" and any code that relies on "import wx" reports "ImportError: No module named wx". However, "whereis wx" on the command line reports "wx: /usr/lib/wx /usr/local/lib/wx /usr/include/ wx". What could be wrong here? I can't figure out why wx isn't being detected. Many thanks. From jgodoy at gmail.com Sun Feb 4 10:29:07 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 04 Feb 2007 13:29:07 -0200 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <1170546032.316062.133050@m58g2000cwm.googlegroups.com> <1170598859.290983.136300@j27g2000cwj.googlegroups.com> Message-ID: <874pq23prw.fsf@gmail.com> "Paul Boddie" writes: > And while Python eggs may be useful for people managing additional > software as some unprivileged user, hosting providers (and virtual > private server administrators) will want packages that fit in with the > rest of the software being managed in the hosting environment. And why eggs wouldn't satisfy them? Eggs can be installed globally as well, making the package available to every client of this hosting server (if they mount their libs from a unique NFS server then it would automatically be available for all of their servers). -- Jorge Godoy From tiedon_jano at hotmail.com Fri Feb 2 11:06:59 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Fri, 02 Feb 2007 16:06:59 GMT Subject: coping directories In-Reply-To: References: Message-ID: Gigs_ kirjoitti: > hi people > > I have problem with this example, not actually the problem, but > [code] > class FileVisitor(object): > def __init__(self, data=None): > self.context = data > def run(self, startdir=os.curdir): > os.path.walk(startdir, self.visitor, None) > def visitor(self, data, dirname, filesindir): > self.visitdir(dirname) > for fname in filesindir: > fpath = os.path.join(dirname, fname) > if not os.path.isdir(fpath): > self.visitfile(fpath) > def visitdir(self, dirpath): # override or extend this > method > print dirpath, '...' > def visitfile(self, filepath): # override or extend this > method > print self.fcount, '=>', filepath > # > class CVisitor(FileVisitor): > def __init__(self, fromdir, todir): > self.fromdirLen = len(fromdir) + 1 # here is my problem > self.todir = todir > FileVisitor.__init__(self, fromdir) > def visitdir(self, dirpath): > topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) > os.mkdir(topath) > def visitfile(self, filepath): > topath = os.path.join(self.todir, filepath[self.fromdirLen:]) > cpfile(filepath, topath) #copy contents from filepath to > topath[/code] > > > When I copy contents from C:\IronPython to C:\temp > its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this > self.fromdirLen = len(fromdir) + 1 > but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen > = len(fromdir) i get contents copied to C:\ (actually to parent dir) > > Can anyone explain me that? > > Thanks!!! > :o Why do you want to change a working program anyway? :) The result of your change is that os.path.join does the join differently. Before the change the join is, for example: os.path.join(r'c:\temp', r'AUTOEXEC.BAT') with a result: c:\temp\AUTOEXEC.BAT After your change the join is: os.path.join(r'c:\temp', r'\AUTOEXEC.BAT') with a result: \AUTOEXEC.BAT This is described in the doc: join( path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. HTH, Jussi From inq1ltd at verizon.net Tue Feb 13 11:13:53 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Tue, 13 Feb 2007 11:13:53 -0500 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: <12t2cgssrrbmf1a@corp.supernews.com> Message-ID: <200702131113.54562.inq1ltd@verizon.net> I'm using Suse Linux which has five program that will open a pdf file from a shell command line. Acrobat Reader is one of the five. A right button click on the file should give a list of programs that will open a PDF file. Im using a KDE desktop Open a shell, add the path to the directory where the PDF file lives, and on the command line type; xpdf myfile.pdf ## may also work on a Gnome ## Desktop or any of these for the KDE desktop; kpdf myfile.pdf Kghostview myfile.pdf konqueror myfile.pdf ## my browser + myfile. Acrobat Reader is also listed on my system. It open files as adobe reader using the mouse to open a pdf file but not from the command line with an arg, and I haven't spent the time to figgure out why. You will have to import os and some combination of any of the exec.. args, or the popen, spawn, or system modules. os.execvep() ## or others like execl, execle .... os.spawnv(), os.spawnve(), os.popen() hope this give some direction. jim-on-linux On Tuesday 13 February 2007 03:44, Jussi Salmela wrote: > Grant Edwards kirjoitti: > > On 2007-02-12, Larry Bates wrote: > >> Grant Edwards wrote: > >>> On 2007-02-12, Larry Bates wrote: > >>>> On 2007-02-12, Larry Bates wrote: > >>>>>>> I at least need the code for useing > >>>>>>> some library for connecting to acrobat > >>>>>>> reader and giving the print command on > >>>>>>> windows and some thing similar on > >>>>>>> ubuntu linux. > >>>>>> > >>>>>> Just let the registered .PDF viewer do > >>>>>> it for you. > >>>>>> > >>>>>> os.start('myfile.pdf') > >>>>> > >>>>> Eh? I don't see os.start() it either 2.5 > >>>>> or 2.44 documentation, and it's sure not > >>>>> there in 2.4.3: > >>>> > >>>> My bad. os.system() > >>> > >>> That doesn't work either: > >>> > >>> $ ls -l user.pdf > >>> -rw------- 1 grante users 35640 > >>> 2005-11-21 14:33 user.pdf > >>> > >>> $ python > >>> Python 2.4.3 (#1, Dec 10 2006, 22:09:09) > >>> [GCC 3.4.6 (Gentoo 3.4.6-r1, > >>> ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type > >>> "help", "copyright", "credits" or "license" > >>> for more information. > >>> > >>> >>> import os > >>> >>> os.system('user.pdf') > >>> > >>> sh: user.pdf: command not found > >>> 32512 > >> > >> Works fine on my system. You linux guys > >> just have it hard. The op said "windows". > > > > The posting to which you replied specified > > Linux. > > > >> I can't answer for ubuntu linux but maybe > >> you can help there? > > > > I don't see how. Pdf files just aren't > > executable. > > On Windows, this (where fileName is xyz.PDF, > for example): webbrowser.open(r'file://' + > fileName) starts Acrobat Reader with the > document read in. I have no idea why, because > Acrobat Reader sure ain't my browser;) > > Maybe someone could try this out on Linux. > > Cheers, > Jussi From laurent.pointal at limsi.fr Tue Feb 20 04:08:29 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 20 Feb 2007 10:08:29 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171907766.635204.161240@h3g2000cwc.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <1171907766.635204.161240@h3g2000cwc.googlegroups.com> Message-ID: Mark Morss a ?crit : > On Feb 16, 4:22 pm, ifti_cr... at yahoo.com wrote: >> I am VB6 programmer and wants to start new programming language but i >> am unable to deciced. >> >> i have read about Python, Ruby and Visual C++. but i want to go >> through with GUI based programming language like VB.net >> >> so will you please guide me which GUI based language has worth with >> complete OOPS Characteristics >> >> will wait for the answer >> >> hope to have a right direction from you Programmer > > Good grief. I suppose it is Microsoft to whom we owe the idea that > there could be such a thing as a "GUI based" programming language. Maybe HyperCard (and its language, HyperTalk) come before VB (SuperCard and MetaCard too)... and its Apple... Whatever we - as professional developers - think about these tools/languages - its very nice to allow not-developers people to build the tools they need, even if these are not perfect in a conceptual view, these are software with users' need filled. Note: I agree, in professionnal world with software service during long years, with software growing to manage more and more tasks, some languages and tools are better than others. Different needs, different personal experience, different skills... different languages. L.Pointal. From exarkun at divmod.com Wed Feb 14 09:00:46 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 14 Feb 2007 09:00:46 -0500 Subject: How to print the variable? In-Reply-To: <345345.69488.qm@web39715.mail.mud.yahoo.com> Message-ID: <20070214140046.25807.1655325180.divmod.quotient.21301@ohm> On Wed, 14 Feb 2007 05:47:31 -0800 (PST), Hans Schwaebli wrote: >Hi, > > am am a Python beginner with Java knowledge background. Infact I need to use Jython. > > My first beginner question is how to determine of what type a variable is? > > In program which supports Jython there is a variable called "rc" available. I can use the methods on that variable like rc.logMessage("hello"). But if I try to execute "print "${rc}" it tells me "Invalid variable syntax for attribute 'code' with value 'print "${rc}".' print rc print dir(rc) print type(rc) help(rc) http://python.org/doc/tut/ Jean-Paul From bignose+hates-spam at benfinney.id.au Wed Feb 14 00:36:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Feb 2007 16:36:13 +1100 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> Message-ID: <874ppp8fn6.fsf@benfinney.id.au> "agent-s" writes: > I have a function, generally described as so: > > def function(args): > if condition: > if condition2: > function(args+1) > elif condition3: > print "text" > return True > else: > return False You've simplified this, presumably to make the code more clear. Unfortunately what remains isn't executable, so we can't see the behaviour that confuses you. Please write a minimal example that demonstrates the behaviour you want explained. -- \ "I doubt, therefore I might be." -- Anonymous | `\ | _o__) | Ben Finney From mintern at cse.ohio-state.edu Thu Feb 22 11:17:02 2007 From: mintern at cse.ohio-state.edu (Brandon Mintern) Date: Thu, 22 Feb 2007 11:17:02 -0500 Subject: paths in modules References: Message-ID: On Thu, 22 Feb 2007 11:13:46 -0500, Brandon Mintern wrote: > Of course, the problem with that approach is that it fails because there > is no utility_dir in the CWD... ...and of course by CWD, I actually mean "current working directory", which should have actually been PWD or "present working directory". Anyway, I just wanted to clear up any confusion that might result due to my improper terminology. From bearophileHUGS at lycos.com Wed Feb 21 13:42:03 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Feb 2007 10:42:03 -0800 Subject: Performance project for the SigEx Foundry In-Reply-To: <1172060154.122555.190330@k78g2000cwa.googlegroups.com> References: <1172060154.122555.190330@k78g2000cwa.googlegroups.com> Message-ID: <1172083323.373948.255220@v33g2000cwv.googlegroups.com> Pablo: > I am looking for articles/studies/benchmarks on the subject. It's not easy to test that, you need to be equally expert on all the languages to test them. This may be a starting point for you: http://shootout.alioth.debian.org/ Bye, bearophile From bdesth.quelquechose at free.quelquepart.fr Sun Feb 18 18:54:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Feb 2007 00:54:01 +0100 Subject: Getting a class name In-Reply-To: References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> <1171818881.871094.295870@v33g2000cwv.googlegroups.com> Message-ID: <45d8df9d$0$28886$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > En Sun, 18 Feb 2007 14:14:41 -0300, goodwolf > escribi?: > >> On Feb 18, 9:17 am, "Gabriel Genellina" wrote: >> >>> En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf >>> escribi?: >>> >>> > I suppose that you wont get class name into its code (or before >>> > definition end) but not into a method definition. >>> >>> > import sys >>> >>> > def getCodeName(deap=0): >>> > return sys._getframe(deap+1).f_code.co_name >>> >>> > class MyClass (object): >>> > name = getCodeName() + '!' >>> >>> What's the advantage over MyClass.__name__? >>> >>> -- >>> Gabriel Genellina >> >> >>>>> class C(object): >> >> ... name = C.__name__ >> ... >> Traceback (most recent call last): >> File "", line 1, in ? >> File "", line 2, in C >> NameError: name 'C' is not defined >> >>>>> > > I were asking, why do you want a "name" attribute since "__name__" > already exists and has the needed information. And worst, using an > internal implementation function to do such task. > This might be useful to avoid metaclass hacks when trying to initialize a class attribute that would require the class name. (my 2 cents) From hg at nospam.org Wed Feb 7 08:19:53 2007 From: hg at nospam.org (hg) Date: Wed, 07 Feb 2007 14:19:53 +0100 Subject: Can somebody give me a python code for this? References: Message-ID: John wrote: > Given an array of elements, look at it as a binary tree. Start at the last > interior node, and downheap it. Then downheap the previous interior node, > and continue in this fashion, up to the root. Your teacher ? From arnodel at googlemail.com Tue Feb 27 13:58:49 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 27 Feb 2007 10:58:49 -0800 Subject: finding out the precision of floats In-Reply-To: <1172585380.631673.257410@q2g2000cwa.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> Message-ID: <1172602729.777210.23070@a75g2000cwd.googlegroups.com> On 27 Feb, 14:09, "Bart Ogryczak" wrote: > On Feb 27, 1:36 pm, Facundo Batista wrote: > > > Arnaud Delobelle wrote: > > > (and I don't want the standard Decimal class :) > > > Why? > > Why should you? It only gives you 28 significant digits, while 64-bit > float (as in 32-bit version of Python) gives you 53 significant > digits. Also note, that on x86 FPU uses 80-bit registers. An then > Decimal executes over 1500 times slower. Actually 28 significant digits is the default, it can be set to anything you like. Moreover 53 significant bits (as this is what 53 counts) is about 16 decimal digits. > >>> from timeit import Timer > >>> t1 = Timer('(1.0/3.0)*3.0 - 1.0') > >>> t2 = Timer('(Decimal(1)/Decimal(3))*Decimal(3)-Decimal(1)', > > 'from decimal import Decimal')>>> t2.timeit()/t1.timeit() > > 1621.7838879255889 Yes. The internal representation of a Decimal is a tuple of one-digit strings! This is one of the reasons (by no means the main) why I decided to write my own class. > If that's not enough to forget about Decimal, take a look at this: > > >>> (Decimal(1)/Decimal(3))*Decimal(3) == Decimal(1) > False > >>> ((1.0/3.0)*3.0) == 1.0 > > True OTOH float is not the panacea: >>> 0.1+0.1+0.1==0.3 False >>> 3*0.1==0.3 False Decimals will behave better in this case. Cheers -- Arnaud From bj_666 at gmx.net Mon Feb 5 06:12:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 05 Feb 2007 12:12:18 +0100 Subject: Inheriting str object References: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> Message-ID: In <1170672488.530515.181340 at k78g2000cwa.googlegroups.com>, kungfoobar at gmail.com wrote: > I want to have a str with custom methods, but I have this problem: > > class myStr(str): > def hello(self): > return 'hello '+self > > s=myStr('world') > print s.hello() # prints 'hello world' > s=s.upper() > print s.hello() # expected to print 'hello WORLD', but s is no longer > myStr, it's a regular str! > > What can I do? Return a `myStr` instance instead of a regular `str`: def hello(self): return myStr('hello ' + self) Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Mon Feb 5 12:36:59 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 5 Feb 2007 09:36:59 -0800 Subject: Calling J from Python In-Reply-To: <52p7h2F1pg9igU1@mid.uni-berlin.de> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p7h2F1pg9igU1@mid.uni-berlin.de> Message-ID: <1170697019.612174.270110@s48g2000cws.googlegroups.com> On Feb 5, 12:23 pm, "Diez B. Roggisch" wrote: > Gosi wrote: > > On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: > >> Gosi wrote: > >> > It is quite easy to call J from Python > > >>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... > > >> What is J, and why should we care? > > >> Diez > > > J is in many ways similar to Python. > > > J has very many advanced operations. > > What exactly do you call "similar to python" when the following is a program > written in it? Compared to that, even Perl is a wonder of readability... > > (cryptic gibberish snipped) > > http://www.jsoftware.com/jwiki/Essays/The_Ball_Clock_Problem > > Diez Please avoid posting code looking like garbled profanities in c.l.py. This was outright offensive. George From exarkun at divmod.com Thu Feb 15 09:58:12 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 15 Feb 2007 09:58:12 -0500 Subject: AUX File Writing Error In-Reply-To: Message-ID: <20070215145812.25807.1044433129.divmod.quotient.22557@ohm> On Thu, 15 Feb 2007 10:13:17 -0300, Gabriel Genellina wrote: >En Thu, 15 Feb 2007 03:34:59 -0300, John Machin >escribi?: > >> On Feb 15, 4:03 pm, thewritersc... at gmail.com wrote: >>> Is there any way I can create an "AUX.csv" file without the error? >> >> Probably not. AUX, CON, NUL, PRN, LPT, COM1, COM2 etc (with or without >> an extension) are reserved in Windows for specific devices for >> compatibility with MS-DOS 1.00 programs, which did that for >> compatibility with CP/M. > >(This is OT now) Do you know why "AUX.csv" is invalid too? I can accept >that AUX (without extension) is an invalid filename, but it is quite >different from "AUX.csv" > Many programs unconditionally add an extension to a filename received from user input or elsewhere. To "simplify" dealing with files, the open call accounts for this case, assuming that the program did not really want to open a file on disk, but that it just accidentally added an extension where one was not really necessary. There /is/ a way to open an on-disk file named "AUX" or "AUX.csv", but it requires special spelling. I don't remember the details at present, but presumably if you are interested you can dig it up on MSDN. Jean-Paul From mensanator at aol.com Sun Feb 11 00:35:48 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Feb 2007 21:35:48 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> Message-ID: <1171172148.476017.283170@s48g2000cws.googlegroups.com> On Feb 10, 11:03???pm, s... at pobox.com wrote: > ? ? >> However, the difference between the open-source people and Microsoft > ? ? >> is the the open-source people aren't being paid by you for the use of > ? ? >> their product, so they're not obligated in any way to help you. > > ? ? mensanator> This argument has become tiresome. The Python community > ? ? mensanator> wants Python to be a big fish in the big pond. That's why > ? ? mensanator> they make Windows binaries available. > > I suspect the main reason Windows binaries are produced is because a) > Microsoft doesn't ship Python installed on Windows, and b) your garden > variety Windows user doesn't have the tools necessary to build Python from > source. ? > Not being a Windows user myself I don't understand all the ins and > outs of VC6 v. VC7, legal or technical. ?Is there nothing Microsoft could > have done to make VC7 compatible with the existing VC6-based build > procedure? Ya got me, I'm not a softeware developer, I'm an amateur math researcher. I don't know the ins and outs either. > > Skip From mail at microcorp.co.za Wed Feb 21 00:44:08 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 21 Feb 2007 07:44:08 +0200 Subject: f---ing typechecking References: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Message-ID: <004e01c7557b$4e99f740$03000080@hendrik> "Nick Craig-Wood" wrote: > > Ie > > x += a > > does not equal > > x = x + a > > which it really should for all types of x and a One would hope so , yes. However, I think that the first form is supposed to update in place, while the second is free to bind a new thing to x > > (That is the kind of statement about which I'm sure someone will post > a perfectly reasonable counterexample ;-) > I don't think its reasonable - its just an accident of implementation.. - Hendrik From exarkun at divmod.com Fri Feb 16 09:49:03 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 16 Feb 2007 09:49:03 -0500 Subject: Pep 3105: the end of print? In-Reply-To: Message-ID: <20070216144903.25807.996277675.divmod.quotient.23913@ohm> On Sat, 17 Feb 2007 01:32:21 +1100, Steven D'Aprano > [snip] > >I don't think that follows at all. print is only a problem if you expect >your code to work under both Python 2.x and 3.x. I wouldn't imagine >that many people are going to expect that: I know I don't. I think some people are confused that the language "Python 3.x" has "Python" in its name, since there is already a language with "Python" in its name, with which it is not compatible. Jean-Paul From timr at probo.com Mon Feb 5 02:05:07 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 05 Feb 2007 07:05:07 GMT Subject: COM makepy util finds multiple versions of my COM object References: <1170402915.631400.204000@j27g2000cwj.googlegroups.com> Message-ID: bg_ie at yahoo.com wrote: > >I have a problem where an earlier version of my Com object is being >used by makepy for early binding. In makepy I see - > >MyCom (1.0) >MyCom (1.0) >MyCom (2.0) Is your MyCom object also in Python? The only way this can happen is if you are generating different GUIDs every time you register the thing. If so, you need to unregister the old version before you register a new one. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sjmachin at lexicon.net Thu Feb 22 19:20:18 2007 From: sjmachin at lexicon.net (John Machin) Date: 22 Feb 2007 16:20:18 -0800 Subject: What is the best queue implemetation in Python? In-Reply-To: References: Message-ID: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> On Feb 23, 11:12 am, "John" wrote: > I want to write a code for Breadth First Traveral for Graph, which needs a > queue to implement. > > I wonder that for such a powerful language as Python, whether there is a > better and simpler implementation for a traditional FIFO queue? > Better and simpler than *WHAT*? From B.Ogryczak at gmail.com Thu Feb 1 06:21:42 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 1 Feb 2007 03:21:42 -0800 Subject: SWIG overhead In-Reply-To: References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> Message-ID: <1170328902.611668.271550@k78g2000cwa.googlegroups.com> On Feb 1, 12:12 pm, Phil Thompson wrote: > On Thursday 01 February 2007 10:21 am, Bart Ogryczak wrote: > > > Hi, > > I?m looking for some benchmarks comparing SWIG generated modules with > > modules made directly with C/Python API. Just how much overhead does > > SWIG give? Doing profile of my code I see, that it spends quiet some > > time in functions like _swig_setattr_nondinamic, _swig_setattr, > > _swig_getattr. > > There was a EuroPython paper describing some benchmarks. It's from 2004 so > things have probably changed a bit (SIP is now fully documented for example). > > http://people.web.psi.ch/geus/talks/europython2004_geus.pdf Yeah, found that one googling around. But I haven?t fund anything more up to date. I imagine, that the performance of all of these wrappers has been improved since then. But the performance of Python/C API would too? Anyways, it?s not about exact number, it?s more about taking decision if doing rewrite is worth it?s time. From grante at visi.com Tue Feb 27 19:39:19 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 28 Feb 2007 00:39:19 -0000 Subject: how to convert an integer to a float? References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> <1172621421.575779.206090@k78g2000cwa.googlegroups.com> Message-ID: <12u9jpnh6k9d363@corp.supernews.com> On 2007-02-28, jeff wrote: > On Feb 27, 7:05 pm, "ying... at gmail.com" wrote: >> Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, >> i1)' always return 0, can you please tell me how can i convert it from >> an integer to float? >> >> def compareValue(n1, n2): >> i1 = int(n1) >> i2 = int(n2) >> >> dx = abs(i2 - i1)/min(i2, i1) >> print dx >> return dx < 0.05 > > x = x + 0.0 How, um, perlesque. I rather think that this is a bit more pythonic: x = float(x) -- Grant Edwards grante Yow! I'm a fuschia bowling at ball somewhere in Brittany visi.com From dudaraster at gmail.com Wed Feb 28 18:50:47 2007 From: dudaraster at gmail.com (Aviroce) Date: Wed, 28 Feb 2007 23:50:47 +0000 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST) In-Reply-To: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> References: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Message-ID: On Feb 24, 11:22 am, stj... at rock.com wrote: > Canada anti-terror law is struck down>From the Associated Press > > February 24, 2007 > > OTTAWA - Canada's Supreme Court on Friday unanimously declared it > unconstitutional to detain foreign terrorism suspects indefinitely > while the courts review their deportation orders. > > Five Arab Muslim men have been held for years under the "security > certificate" program, which the Justice Department has said is a key > tool in the fight against global terrorism and essential to Canada's > security. > > The court found that the system violated the Charter of Rights and > Freedoms, Canada's bill of rights. However, it suspended its ruling > for a year to give Parliament time to rewrite the part of the > Immigration and Refugee Protection Act that covers the certificate > process. > > The security certificates were challenged by three men from Morocco, > Syria and Algeria - all alleged by the Canadian Security Intelligence > Service to have ties to terrorist networks. > > The men have spent years in jail while fighting deportation orders. > > They risk being labeled terrorists and sent back to their native > countries, where they say they could face torture. > > The court said the treatment of the suspects was a violation of their > rights. > > "The overarching principle of fundamental justice that applies here is > this: Before the state can detain people for significant periods of > time, it must accord them a fair judicial process," Chief Justice > Beverley McLachlin wrote in a ruling for all nine justices. > > "The secrecy required by the scheme denies the person named in a > certificate the opportunity to know the case put against him or her, > and hence to challenge the government's case," she said. > > The challenged law allows sensitive intelligence to be heard behind > closed doors by a federal judge, with only sketchy summaries given to > defense attorneys. > > The court said the men and their lawyers should have a right to > respond to the evidence used against them by intelligence agents. > > Stockwell Day, the minister of public safety, noted that because the > ruling does not take effect for a year, the certificates would remain > in place. He said the government would address the court's ruling "in > a timely and decisive fashion." > > Two of the men are out on bail and remain under house arrest. Three > others are being held in a federal facility in Ontario. <<<<<<<<<<<"The court said the treatment of the suspects was a violation of their rights. "The overarching principle of fundamental justice that applies here is this: Before the state can detain people for significant periods of time, it must accord them a fair judicial process," Chief Justice Beverley McLachlin wrote in a ruling for all nine justices. "The secrecy required by the scheme denies the person named in a certificate the opportunity to know the case put against him or her, and hence to challenge the government's case," she said. ">>>>>>>>>>>>>>>> THAT IS CALLED PROTECTING CIVIL RIGHTS. IN THE UNITED STATES OF AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE NOT PROTECTED BY THE GENEVA CONVENTION. DR. EVIL, V.P. CHENEY, AND MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION. THIS MEANS ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO. WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER. From olsongt at verizon.net Wed Feb 7 20:00:35 2007 From: olsongt at verizon.net (Grant Olson) Date: Wed, 07 Feb 2007 20:00:35 -0500 Subject: Does the world need another v0.1 python compiler? Message-ID: <001001c74b1c$8b47bb50$ac01a8c0@johnyaya> I'm feeling a little guilty here. I spent a lot of my free time last year working on an x86 compiler for python. I made a reasonable amount of progress, but my interests wandered off into other areas. I basically just got bored and stopped working on the thing maybe 6 months ago. So today, I went to the directory that contains all of my source checkouts, and saw this v 0.1 compiler just sitting out there AGAIN. It's not that I don't want to release the code, but it's just not in quite good enough shape to just throw out there and hope that other people pick up and get things working. I've seen more than a few half-assed compiler implementations out there and part of me thinks I'd just be wasting my time by just zipping up what I have and throwing it out there. Also, I don't really expect any significant speed increases, which seems to be what people want out of a compiler, but was primarily interested in creating standalone .exes without the need for a 'runtime environment' (whatever that means). There might be a little speed increase from unrolling the eval loop, but nothing too serious. The basic approach I took was compiling to bytecode, and then transliterating python bytecode to x86 asm. And it is working a little bit. There is a slightly modified version of the CPython interpreter that introduces xfunction and xcode objects, that basically act the same as function and code objects, but run native code. I've successfully generated some very simple .pyds that can be imported into this interpreter. I also have some tests that test each bytecode on a small scale and they all seem to be working. I can just barely run pystones. The biggest problem right now seems to be that reference counting isn't adding up, resulting in some serious performance degradation. On the downside, right now it's Windows only. There's nothing inherently windows specific, but I don't have anything to build on other platforms. It also assumes you've got the visual studio toolchain. So like I said, I feel a little guilty about keeping this thing hostage on my systems at home. On the other hand, if anyone else is interested, they're going to need to be a VERY early adopter. Does anyone have any serious interest in taking a look? -Grant From bg_ie at yahoo.com Fri Feb 2 02:55:15 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 1 Feb 2007 23:55:15 -0800 Subject: COM makepy util finds multiple versions of my COM object Message-ID: <1170402915.631400.204000@j27g2000cwj.googlegroups.com> Hi, I have a problem where an earlier version of my Com object is being used by makepy for early binding. In makepy I see - MyCom (1.0) MyCom (1.0) MyCom (2.0) I created version 2 of my Com object hoping that this would solve the problem but makepy is still using an earlier version. I can solve the problem by editing the registry, but this problem now exists on a number of computers... Any ideas as to how I might solve this one? I'm using build 210 of pythonwin. Thanks for your help, Barry. From gagsl-py at yahoo.com.ar Sun Feb 18 03:30:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Feb 2007 05:30:26 -0300 Subject: conver string to dictionary References: <849825.29475.qm@web53614.mail.yahoo.com> Message-ID: En Sun, 18 Feb 2007 03:44:47 -0300, mahdieh saeed escribi?: > Hi > I want to convert string to dictionary .what is the best solution for > this ? > for example string is like this: > '{"SalutationID":["primarykey",8388607,0,None],"CompanyID":[0,8388607,0,"index"], > "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]}' > and I want to convert this string to this dictionary: > {"SalutationID":["primarykey",8388607,0,None],"CompanyID":[0,8388607,0,"index"], > "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]} > please help me what is the best solution(faster solution) for this? The simplest way is to use eval(), but only do that if you can trust absolutely the source. To be safe, you can use this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 -- Gabriel Genellina From skip at pobox.com Fri Feb 9 15:03:25 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 9 Feb 2007 14:03:25 -0600 Subject: pygame and python 2.5 In-Reply-To: <45CCCA1F.6050204@vrplumber.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <17868.46349.59089.178486@montanaro.dyndns.org> <45CCCA1F.6050204@vrplumber.com> Message-ID: <17868.54157.249416.534611@montanaro.dyndns.org> Ben> Python extensions written in C require recompilation for each new Ben> version of Python, due to Python limitations. >> Can you propose a means to eliminate this limitation? Mike> Sure, write your wrapper-style extensions in ctypes :). I was think more along the lines of how could the Python extension module API change so that for example, modules compiled for Python 2.6 would continue to work without warning under Python 2.7. Maybe ctypes is the answer, but suspect it addresses a different API than I was thinking of. Skip From donmorrison at gmail.com Wed Feb 7 17:53:49 2007 From: donmorrison at gmail.com (Don Morrison) Date: Wed, 7 Feb 2007 14:53:49 -0800 Subject: string.find for case insensitive search In-Reply-To: References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: > Don Morrison wrote: > > string.find is deprecated as per the official python documentation. > > > but the str.find() method isn't. > > > take a look at the "re" module > > > A possibility. > > regards > Steve Thank you everyone. :) Johny did say "string.find" in his message, not "str.find", but continue to proceed with flogging. thank you! From fatwallet961 at yahoo.com Fri Feb 2 23:45:19 2007 From: fatwallet961 at yahoo.com (fatwallet961 at yahoo.com) Date: Fri, 02 Feb 2007 20:45:19 -0800 Subject: main Message-ID: is the main function in python is exact compare to Java main method? all execution start in main which may takes arguments? like the follow example script - def main(argv): ============================== and what is __name__ __main__ use for in terms of Java? thanks ============================== #!/usr/bin/env python """ Preprocess a file. Command Line Usage: preprocess [...] Options: -h, --help Print this help and exit. -v, --verbose Give verbose output for errors. -o Write output to the given file instead of to stdout. -D Define a variable for preprocessing. can simply be a variable name (in which case it will be true) or it can be of the form =. An attempt will be made to convert to an integer so "-D FOO=0" will create a false value. Module Usage: from preprocess import preprocess preprocess(infile, outfile=sys.stdout, defines={}) The can be marked up with special preprocessor statement lines of the form: where the are the native comment delimiters for that file type. Examples: ... # #if defined('FAV_COLOR') and FAV_COLOR == "blue" ... # #elif FAV_COLOR == "red" ... # #else ... # #endif Preprocessor Syntax: - Valid statements: #define [=] #undef #if #elif #else #endif #error where is any valid Python expression. - The expression after #if/elif may be a Python statement. It is an error to refer to a variable that has not been defined by a -D option. - Special built-in methods for expressions: defined(varName) Return true if given variable is defined. """ import os import sys import getopt import types import re import pprint import logging from contenttype import getContentType #---- exceptions class PreprocessError(Exception): def __init__(self, errmsg, file=None, lineno=None, line=None): self.errmsg = str(errmsg) self.file = file self.lineno = lineno self.line = line Exception.__init__(self, errmsg, file, lineno, line) def __str__(self): s = "" if self.file is not None: s += self.file + ":" if self.lineno is not None: s += str(self.lineno) + ":" if self.file is not None or self.lineno is not None: s += " " s += self.errmsg return s #---- global data log = logging.getLogger("preprocess") # Comment delimiter info. # A mapping of content type to a list of 2-tuples defining the line # prefix and suffix for a comment. _commentGroups = { "Python": [ ('#', '') ], "Perl": [ ('#', '') ], "Tcl": [ ('#', '') ], "XML": [ ('') ], "HTML": [ ('') ], "Makefile": [ ('#', '') ], "JavaScript": [ ('/*', '*/'), ('//', '') ], "CSS": [ ('/*', '*/') ], "C": [ ('/*', '*/') ], "C++": [ ('/*', '*/'), ('//', '') ], "IDL": [ ('/*', '*/'), ('//', '') ], "Text": [ ('#', '') ], } #---- internal support stuff def _evaluate(expr, defines): """Evaluate the given expression string with the given context.""" try: rv = eval(expr, {'defined':lambda v: v in defines}, defines) except Exception, ex: raise PreprocessError(str(ex), defines['__FILE__'], defines['__LINE__']) log.debug("evaluate %r -> %s (defines=%r)", expr, rv, defines) return rv #---- module API def preprocess(infile, outfile=sys.stdout, defines={}): """Preprocess the given file. "infile" is the input filename. "outfile" is the output filename or stream (default is sys.stdout). "defines" is a dictionary of defined variables that will be understood in preprocessor statements. Keys must be strings and, currently, only the truth value of any key's value matters. Returns the modified dictionary of defines or raises PreprocessError if there was some problem. """ log.info("preprocess(infile=%r, outfile=%r, defines=%r)", infile, outfile, defines) # Determine the content type and comment info for the input file. contentType = getContentType(infile) if contentType is None: contentType = "Text" log.warn("defaulting content type for '%s' to '%s'", infile, contentType) try: cgs = _commentGroups[contentType] except KeyError: raise PreprocessError("don't know comment delimiters for content "\ "type '%s' (file '%s')"\ % (contentType, infile)) # Generate statement parsing regexes. stmts = ['#\s*(?Pif|elif|ifdef|ifndef)\s+(?P.*?)', '#\s*(?Pelse|endif)', '#\s*(?Perror)\s+(?P.*?)', '#\s*(?Pdefine)\s+(?P[^\s]*?)(\s+(?P.+?))?', '#\s*(?Pundef)\s+(?P[^\s]*?)'] patterns = ['^\s*%s\s*%s\s*%s\s*$' % (re.escape(cg[0]), stmt, re.escape(cg[1])) for cg in cgs for stmt in stmts] stmtRes = [re.compile(p) for p in patterns] # Process the input file. fin = open(infile, 'r') if type(outfile) in types.StringTypes: if os.path.exists(outfile): os.chmod(outfile, 0777) os.remove(outfile) fout = open(outfile, 'w') else: fout = outfile defines['__FILE__'] = infile SKIP, EMIT = range(2) # states states = [(EMIT, # a state is (, 0, # , 0)] # ) lineNum = 0 for line in fin.readlines(): lineNum += 1 log.debug("line %d: %r", lineNum, line) defines['__LINE__'] = lineNum # Is this line a preprocessor stmt line? for stmtRe in stmtRes: match = stmtRe.match(line) if match: break else: match = None if match: op = match.group("op") log.debug("%r stmt (states: %r)", op, states) if op == "define": if states and states[-1][0] == SKIP: continue var, val = match.group("var", "val") if val is None: val = None else: try: val = eval(val, {}, {}) except: pass defines[var] = val elif op == "undef": if states and states[-1][0] == SKIP: continue var = match.group("var") try: del defines[var] except KeyError: pass elif op in ("if", "ifdef", "ifndef"): if op == "if": expr = match.group("expr") elif op == "ifdef": expr = "defined('%s')" % match.group("expr") elif op == "ifndef": expr = "not defined('%s')" % match.group("expr") try: if states and states[-1][0] == SKIP: # Were are nested in a SKIP-portion of an if-block. states.append((SKIP, 0, 0)) elif _evaluate(expr, defines): states.append((EMIT, 1, 0)) else: states.append((SKIP, 0, 0)) except KeyError: raise PreprocessError("use of undefined variable in "\ "#%s stmt" % op, defines['__FILE__'], defines['__LINE__'], line) elif op == "elif": expr = match.group("expr") try: if states[-1][2]: # already had #else in this if-block raise PreprocessError("illegal #elif after #else in "\ "same #if block", defines['__FILE__'], defines['__LINE__'], line) elif states[-1][1]: # if have emitted in this if-block states[-1] = (SKIP, 1, 0) elif states[:-1] and states[-2][0] == SKIP: # Were are nested in a SKIP-portion of an if-block. states[-1] = (SKIP, 0, 0) elif _evaluate(expr, defines): states[-1] = (EMIT, 1, 0) else: states[-1] = (SKIP, 0, 0) except IndexError: raise PreprocessError("#elif stmt without leading #if "\ "stmt", defines['__FILE__'], defines['__LINE__'], line) elif op == "else": try: if states[-1][2]: # already had #else in this if-block raise PreprocessError("illegal #else after #else in "\ "same #if block", defines['__FILE__'], defines['__LINE__'], line) elif states[-1][1]: # if have emitted in this if-block states[-1] = (SKIP, 1, 1) elif states[:-1] and states[-2][0] == SKIP: # Were are nested in a SKIP-portion of an if-block. states[-1] = (SKIP, 0, 1) else: states[-1] = (EMIT, 1, 1) except IndexError: raise PreprocessError("#else stmt without leading #if "\ "stmt", defines['__FILE__'], defines['__LINE__'], line) elif op == "endif": try: states.pop() except IndexError: raise PreprocessError("#endif stmt without leading #if"\ "stmt", defines['__FILE__'], defines['__LINE__'], line) elif op == "error": if states and states[-1][0] == SKIP: continue error = match.group("error") raise PreprocessError("#error: "+error, defines['__FILE__'], defines['__LINE__'], line) log.debug("states: %r", states) else: try: if states[-1][0] == EMIT: log.debug("emit line (%s)" % states[-1][1]) fout.write(line) else: log.debug("skip line (%s)" % states[-1][1]) except IndexError: raise PreprocessError("superfluous #endif before this line", defines['__FILE__'], defines['__LINE__']) if len(states) > 1: raise PreprocessError("unterminated #if block", defines['__FILE__'], defines['__LINE__']) elif len(states) < 1: raise PreprocessError("superfluous #endif on or before this line", defines['__FILE__'], defines['__LINE__']) if fout != outfile: fout.close() #---- mainline def main(argv): try: optlist, args = getopt.getopt(argv[1:], 'hvo:D:', ['help', 'verbose']) except getopt.GetoptError, msg: sys.stderr.write("preprocess: error: %s" % msg) sys.stderr.write("See 'preprocess --help'.\n") return 1 outfile = sys.stdout defines = {} for opt, optarg in optlist: if opt in ('-h', '--help'): sys.stdout.write(__doc__) return 0 elif opt in ('-v', '--verbose'): log.setLevel(logging.DEBUG) elif opt == '-o': outfile = optarg elif opt == '-D': if optarg.find('=') != -1: var, val = optarg.split('=', 1) try: val = eval(val, {}, {}) except: pass else: var, val = optarg, None defines[var] = val if len(args) != 1: sys.stderr.write("preprocess: error: incorrect number of "\ "arguments: argv=%r\n" % argv) return 1 else: infile = args[0] try: preprocess(infile, outfile, defines) except PreprocessError, ex: sys.stderr.write("preprocess: error: %s\n" % str(ex)) if __name__ == "__main__": sys.exit( main(sys.argv) ) From google at orcon.net.nz Fri Feb 16 19:28:01 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 16 Feb 2007 16:28:01 -0800 Subject: Output to a text window Message-ID: <1171671439.512024.177120@p10g2000cwp.googlegroups.com> Hi, I'm going around in circles so I'm asking for help. I want to read a simple text file and output the contents to a GUI window when I click on a button. I have written a small python program to read the contents of a file when a button is clicked but can only output this to a console window. I'm using the pygtk binding with glade for the gui. I know it must be quiet simple but a mental block has rapidly descended. Any help would be appreciated. From tiedon_jano at hotmail.com Tue Feb 6 09:31:36 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 06 Feb 2007 14:31:36 GMT Subject: Graphs, bar charts, etc In-Reply-To: <45c87a32@griseus.its.uu.se> References: <45c87a32@griseus.its.uu.se> Message-ID: Jan Danielsson kirjoitti: > Hello all, > > I have some data in a postgresql table which I view through a web > interface (the web interface is written in python -- using mod_python > under apache 2.2). Now I would like to represent this data as graphs, > bar charts, etc. > > I know about matplotlib, and it seemed like exactly what I was > looking for. I tried importing it in my script, but it gave me some > error about a home directory not being writable. I'm not sure I like the > idea of it require to be able to write somewhere. Am I using it wrong? > > Is there something else I can use which can produce graphs easily? > I've used PyChart: http://home.gna.org/pychart/ in my Blood Pressure Monitor application: http://personal.inet.fi/cool/operator/BPMDownload.html I found PyChart to be very easy to use and to function as advertised. HTH, Jussi From skip at pobox.com Thu Feb 15 10:35:20 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 15 Feb 2007 09:35:20 -0600 Subject: threading and multicores, pros and cons In-Reply-To: <200702150543.12593.maric@aristote.info> References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> <200702150543.12593.maric@aristote.info> Message-ID: <17876.32184.377924.427526@montanaro.dyndns.org> Maric> Le mercredi 14 f?vrier 2007 16:24, garrickp at gmail.com a ?crit?: >> "Some time back, a group did remove the GIL from the python core, and >> implemented locks on the core code to make it threadsafe. Well, the >> problem was that while it worked, the necessary locks it made single >> threaded code take significantly longer to execute." Maric> Very interesting point, this is exactly the sort of thing I'm Maric> looking for. Any valuable link on this ? Google for "python free threading stein" then click the first link. Skip From bignose+hates-spam at benfinney.id.au Wed Feb 28 22:45:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Mar 2007 14:45:01 +1100 Subject: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple) References: <87slcqvskr.fsf@benfinney.id.au> <54ms6fF21c6h3U2@mid.individual.net> Message-ID: <87d53twrsy.fsf_-_@benfinney.id.au> Bjoern Schliessmann writes: > Ben Finney wrote: > > > A tuple implies a meaning associated with each position in the > > sequence (like a record with a positional meaning for each field), > > a list implies the opposite (a sequence with order but not meaning > > associated with each position). > > Explain. Well, since you ask so politely :-) > I know tuples as immutable lists ... That's a common misconception. Tuples are intended for use as heterogeneous data structures: every index in the sequence *means* something, a semantic meaning applied to the item at that index. It's for this reason that a tuple is immutable: removing items, inserting them in the middle, etc. would imply that the index doesn't have semantic meaning for the structure, which is not true. Lists are intended for use as homogeneous sequences: not that every value is of the same type, but that a particular index in the sequence doesn't *mean* anything about the semantic interpretation of the item at that position. It's for this reason that a list is mutable: since the index of an item has no semantic meaning, inserting new items or removing them from anywhere in the sequence doesn't alter the meaning of the structure. James Tauber explains further: -- \ "You can be a victor without having victims." -- Harriet Woods | `\ | _o__) | Ben Finney From jstroud at mbi.ucla.edu Sat Feb 10 03:25:04 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 10 Feb 2007 00:25:04 -0800 Subject: interacting with shell - another newbie question In-Reply-To: <0e2dnUM6nIWq41DYRVnzvA@telenor.com> References: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> <0e2dnUM6nIWq41DYRVnzvA@telenor.com> Message-ID: <%hfzh.53050$QU1.17723@newssvr22.news.prodigy.net> Tina I wrote: > James wrote: >> Hello, >> >> I work in this annoying company where I have to autheticate myself to >> the company firewall every 30-50 minutes in order to access the >> internet. (I think it's a checkpoint fw). >> >> I have to run "telnet what.ever.ip.address 259" then it prompts me >> with userid, then password, then I have to select "1". Then the >> program closes itself and the internet is enabled. >> >> I would like to automate this process with Python and run it every 30 >> miniutes so I don't have to keep typing in these userid/password >> everytime. How can this be done? Is there a module I can use to >> interact with the shell? (I'm running linux) >> >> Thank you. >> >> James >> > Sounds like the perfect way to get fired. To be sure though, remember to > store your password in clear text ;) > However bizarre the security measures seem it's obviously in place to > make sure it's *you* sitting at the computer. Scripting the > authentication process is equal to simply removing it. Yes, and finding ways to have employees pointlessly waste time is equal to simply removing them. From steve at holdenweb.com Fri Feb 16 09:50:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 09:50:40 -0500 Subject: Approaches of interprocess communication In-Reply-To: <87fy965plq.fsf@benfinney.id.au> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <87fy965plq.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "Gabriel Genellina" writes: > >> (And I would expect that making a connection to "localhost" actually >> does *not* go down up to the network card hardware layer, but I >> don't know for real if this is the case or not). > > It damned well better. That's the entire point of the loopback > interface: to get all the network layer code involved, but not to talk > on a physical network interface. > > If a programmer decides on behalf of the user that "localhost" should > be treated specially, that programmer is making an error. > Inter-process TCP/IP communication between two processes on the same host invariably uses the loopback interface (network 127.0.0.0). According to standards, all addresses in that network space refer to the local host, though 127.0.0.1 is conventionally used. The transmit driver for the loopback interface receives a datagram from the local network layer and immediately announces its reception back to the local network layer. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From arkanes at gmail.com Tue Feb 27 17:20:55 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 27 Feb 2007 16:20:55 -0600 Subject: design question: no new attributes In-Reply-To: References: <8BIEh.1349$QI4.489@trnddc01> <1172561344.290126.191530@h3g2000cwc.googlegroups.com> Message-ID: <4866bea60702271420k43ef8b3ajdb8bc242606f6059@mail.gmail.com> On 2/27/07, Alan Isaac wrote: > "Arnaud Delobelle" wrote in message > news:1172561344.290126.191530 at h3g2000cwc.googlegroups.com... > > def __setattr__(self, attr, val): > > if hasattr(self, attr): > > self.__dict__[attr] = val > > else: > > # Tell the user off > > But then you cannot even set attributes during initialization, right? > I want that restriction only after an object is initialized. > (I realize that I could condition on an attribute set during initialization, > but I am asking for the most elegant way to achieve this.) > > Alan > You specifically excluded slots in your spec, but why? It's as close to a working, elegant solution you will find. Nothing else will work, and will be horribly inelegant. You can still do it the above way, with nasty hacking (but not really any nastier than what you're doing) by pushing the __setattr__ hook on as the last part of your __init__. Of course, if they subclass and don't call your base class __init__, then they can get by you. So maybe you should inspect the call stack in your __setattr__ and only allow instance setting if you're within your "approved" __init__ method. Even then, you can't stop them from grabbing your class, removing or overwriting the hook, and creating classes on the fly. I think at this point (actually quite a while before this point) you're getting into silly amounts of thinking about it. Python for consenting adults and all that. From __peter__ at web.de Sat Feb 3 10:48:58 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 16:48:58 +0100 Subject: compound statement from C "?:" References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> Message-ID: Jussi Salmela wrote: > It's naturally clear that a combination of if-elifs-else is more > adaptable to different situations, but the OP's question was: > > I would like to do the equivalent if python of the C line: > printf("I saw %d car%s\n", n, n != 1 ? "s" : "") And my answer, triggered by your intermission > And I'm starting to wonder what the 'obvious way' (as in 'Zen of Python') > to write this would be. was that in Python you would achieve the best results with if ... else instead: >> if n == 1: >> print "I saw a car" >> else: >> print "I saw %d cars" % n > In this question I thought I recognized the familiar > tool=hammer==>problem:nail pattern of thought and tried to show > that in addition to the ternary operator Python has other ways of > resolving that particular problem of his. It seems we operated on different levels of abstraction, You: hammer=ternary operator Me: hammer=oneliner > I'm certainly not an advocate of one-liners because at their extreme > they easily result in write-only solutions. D'accord. Did I mention that, as a "for fun" approach, "s" * (n != 1) is quite clever :-) Peter From bearophileHUGS at lycos.com Sun Feb 4 12:06:23 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Feb 2007 09:06:23 -0800 Subject: Parameter lists In-Reply-To: References: Message-ID: <1170608783.394629.318750@v45g2000cwv.googlegroups.com> Mizipzor > I dont like the looks of that code, there are many > function parameters to be sent in and if I were to add an attribute, i > would need to add it in three places. Add it to the function > parameters, add it to the class and assign it. > Is there a smoother way to do this? You may use something like this: def selfassign(self, locals): # Code from web.py http://webpy.org modified. for key, value in locals.iteritems(): if key != 'self': setattr(self, key, value) Generally used in __init__ methods, as: def __init__(self, foo, bar, baz=1): selfassign(self, locals()) You may use it as (untested): class Stats: def __init__(self, speed, maxHp, armor, strength, attackSpeed, imagePath): selfassign(self, locals()) self.originalImage = loadTexture(imagePath) del self.imagePath I don't like that del Bye, bearophile From cityhunter007 at gmail.com Thu Feb 8 16:16:19 2007 From: cityhunter007 at gmail.com (James) Date: 8 Feb 2007 13:16:19 -0800 Subject: Fwd: Python new user question - file writeline error In-Reply-To: <45cb8045$0$449$426a74cc@news.free.fr> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <1170887579.160693.78160@a34g2000cwb.googlegroups.com> <813A863A-3D95-47B5-8E54-B6DDF5A57DF5@Milochik.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> <45cb8045$0$449$426a74cc@news.free.fr> Message-ID: <1170969379.309403.143010@a75g2000cwd.googlegroups.com> On Feb 8, 3:26 pm, Bruno Desthuilliers wrote: > Shawn Milo a ?crit : > > > > > To the list: > > > I have come up with something that's working fine. However, I'm fairly > > new to Python, so I'd really appreciate any suggestions on how this > > can be made more Pythonic. > > > Thanks, > > Shawn > > > Okay, here's what I have come up with: > > > #! /usr/bin/python > > > import sys > > import re > > > month > > ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'?OCT':10,'NOV':11,'DEC':12} > > > infile=file('TVA-0316','r') > > outfile=file('tmp.out','w') > > > def formatDatePart(x): > > "take a number and transform it into a two-character string, > > zero padded" > > x = str(x) > > while len(x) < 2: > > x = "0" + x > > return x > > x = "%02d" % x > > > regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") > > regexps are not really pythonic - we tend to use them only when we have > no better option. When it comes to parsing CSV files and/or dates, we do > have better solution : the csv module and the datetime module.... > > > for line in infile: > > matches = regex.findall(line) > > for someDate in matches: > > > dayNum = formatDatePart(someDate[1:3]) > > monthNum = formatDatePart(month[someDate[4:7]]) > > yearNum = formatDatePart(someDate[8:12]) > > > newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) > > line = line.replace(someDate, newDate) > > outfile.writelines(line) > > > infile.close > > outfile.close > > I wonder why some of us took time to answer your first question. You > obviously forgot to read these answers. No offense - but the fact that 're' module is available, doesn't that mean we can use it? (Pythonic or not - not sure what is really pythonic at this stage of learning...) Like Perl, I'm sure there are more than one way to solve problems in Python. I appreciate everyone's feedback - I definitely got more than expected, but it feels comforting that people do care about writing better codes! :) From python at hope.cz Tue Feb 6 05:47:07 2007 From: python at hope.cz (Johny) Date: 6 Feb 2007 02:47:07 -0800 Subject: Repr or Str ? Message-ID: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> Where and when is good/nescessary to use `repr` instead of `str` ? Can you please explain the differences Thanks LL From kavithapython at yahoo.co.in Tue Feb 27 06:13:20 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Tue, 27 Feb 2007 11:13:20 +0000 (GMT) Subject: newbie question(file-delete trailing comma) In-Reply-To: <595502.96598.qm@web31113.mail.mud.yahoo.com> Message-ID: <743170.77162.qm@web7813.mail.in.yahoo.com> i get an error when i try to delete in file and rename it as out file,,the error says "permission denied". actually i need something like following: in_file = open('in.txt','w') for line in in_file: line.strip().strip(',') but when i run the above code,i get an error"bad file descriptor" thanks,, kavitha Mohammad Tayseer wrote: kavitha thankaian wrote: > and i need the output also in the same input.txt just add import os os.remove('in.txt') os.rename('out.txt', 'in.txt') --------------------------------- Don't be flakey. Get Yahoo! Mail for Mobile and always stay connected to friends.-- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob at work.org Wed Feb 14 13:59:01 2007 From: bob at work.org (Martien Friedeman) Date: 15 Feb 2007 07:59:01 +1300 Subject: Testers please References: Message-ID: <45d35bf5$1@clear.net.nz> That's amazing! We had the same idea. From sjmachin at lexicon.net Sun Feb 11 03:20:46 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 00:20:46 -0800 Subject: HTML Parsing In-Reply-To: References: <1171148863.807386.310960@h3g2000cwc.googlegroups.com> Message-ID: <1171182045.946209.15730@l53g2000cwa.googlegroups.com> On Feb 11, 6:05 pm, Ayaz Ahmed Khan wrote: > "mtuller" typed: > > > I have also tried Beautiful Soup, but had trouble understanding the > > documentation > > As Gabriel has suggested, spend a little more time going through the > documentation of BeautifulSoup. It is pretty easy to grasp. > > I'll give you an example: I want to extract the text between the > following span tags in a large HTML source file. > > Linux Kernel Bluetooth CAPI Packet Remote Buffer Overflow Vulnerability > > >>> import re > >>> from BeautifulSoup import BeautifulSoup > >>> from urllib2 import urlopen > >>> soup = BeautifulSoup(urlopen('http://www.someurl.tld/')) > >>> title = soup.find(name='span', attrs={'class':'title'}, text=re.compile(r'^Linux \w+')) > >>> title > > u'Linux Kernel Bluetooth CAPI Packet Remote Buffer Overflow Vulnerability' > One can even use ElementTree, if the HTML is well-formed. See below. However if it is as ill-formed as the sample (4th "td" element not closed; I've omitted it below), then the OP would be better off sticking with Beautiful Soup :-) C:\junk>type element_soup.py from xml.etree import cElementTree as ET import cStringIO guff = """ LETTER 33,699 1.0 """ tree = ET.parse(cStringIO.StringIO(guff)) for elem in tree.getiterator('td'): key = elem.get('headers') assert elem[0].tag == 'span' value = elem[0].text print repr(key), repr(value) C:\junk>\python25\python element_soup.py 'col1_1' 'LETTER' 'col2_1' '33,699' 'col3_1' '1.0' HTH, John From silverburgh.meryl at gmail.com Mon Feb 26 16:28:20 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 26 Feb 2007 13:28:20 -0800 Subject: Walk thru each subdirectory from a top directory Message-ID: <1172525300.450438.57080@8g2000cwh.googlegroups.com> i am trying to use python to walk thru each subdirectory from a top directory. Here is my script: savedPagesDirectory = "/home/meryl/saved_pages/data" dir=open(savedPagesDirectory, 'r') for file in dir: if (isdir(file)): # get the full path of the file fileName = savedPagesDirectory + file + 'index.html' print fileName $ ./scripts/regressionTest.py Traceback (most recent call last): File "./scripts/regressionTest.py", line 12, in ? dir=open(savedPagesDirectory, 'r') IOError: [Errno 21] Is a directory But I get the above error: Can you please tell me what did I do wrong? Thank you. From paddy3118 at netscape.net Mon Feb 5 23:55:17 2007 From: paddy3118 at netscape.net (Paddy) Date: 5 Feb 2007 20:55:17 -0800 Subject: Calling J from Python In-Reply-To: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> Message-ID: <1170737717.413948.124010@p10g2000cwp.googlegroups.com> On Feb 5, 2:48 pm, "Gosi" wrote: > It is quite easy to call J from Python > > http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... Hii Gosi, >From reading what has gone before, you seem to have got it in the neck from some pythonistas. I'd just like to say from some but not all. It is *A GOOD THING* that Python has bridges to other languages. Some may not care to program in the other language - which is a separate concer;. but a link between the language - be it Haskell or befunge or J, makes Python better in my view. If your expert J programmers have need for something that is hard to do in J they might now be more likely to use Python. We should remember that Python is a great glue language too, and links to other languages and tools is how we maintain that position. - Paddy. From jan.m.danielsson at gmail.com Sun Feb 4 20:18:56 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Mon, 05 Feb 2007 02:18:56 +0100 Subject: Return images with matplotlib? Message-ID: <45c684e2$1@griseus.its.uu.se> Hello all, I have written a program which takes some data from a postgresql database, and via mod_python outputs it as tables on a web site. Now I would like to present these tables as graphs, which matplotlib can do. But in order to properly display these graphs on the web page, I need to return the image data, like so: def barchart(req, params): some_format = matplotlib.generate_fancy_graph(params) png_buf = make_png_buffer(some_format) return png_buf Is this possible? If so -- how? -- Kind regards, Jan Danielsson ------------ And now a word from our sponsor ------------------ For a quality usenet news server, try DNEWS, easy to install, fast, efficient and reliable. For home servers or carrier class installations with millions of users it will allow you to grow! ---- See http://netwinsite.com/sponsor/sponsor_dnews.htm ---- From bdesth.quelquechose at free.quelquepart.fr Sun Feb 18 08:59:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 18 Feb 2007 14:59:05 +0100 Subject: why I don't like range/xrange In-Reply-To: <1171742513.441273.87130@v33g2000cwv.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <45d61e34$0$29759$426a74cc@news.free.fr> <45d744ad$0$30359$426a74cc@news.free.fr> <1171742513.441273.87130@v33g2000cwv.googlegroups.com> Message-ID: <45d8542f$0$29060$426a74cc@news.free.fr> sjdevnull at yahoo.com a ?crit : > Bruno Desthuilliers wrote: > >>Roel Schroeven a ecrit : >> >>>Bruno Desthuilliers schreef: >>> >>> >>>>stdazi a ecrit : >>> >>> >>>>>for (i = 0 ; i < 10 ; i++) >>>>> i = 10; >>>> >>>> >>>>for i in range(10): >>>> i = 10 >>>> >>>>What's your point, exactly ? >>> >>> >>>In the first iteration, i is set equal to 10. Then, before starting the >>>second iteration, i is incremented to 11; then the loop condition is >>>checked and results in false. So the loop terminates after the first >>>iteration. >> >>oops - my bad. But why would one do so when a break would do the trick: >>for i in range(10): >> break > > > After the C loop finishes, i is 11. After the python loop-with-break > finishes, i is 0. That may effect later code. > Lord saves me from having to maintain programs based on such constructions... From steve at holdenweb.com Thu Feb 15 07:05:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 12:05:59 +0000 Subject: pygame and python 2.5 In-Reply-To: <1171419576.565394.253240@a34g2000cwb.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> <1171213686.383076.280390@j27g2000cwj.googlegroups.com> <1171419576.565394.253240@a34g2000cwb.googlegroups.com> Message-ID: <45D44CA7.9010504@holdenweb.com> mensanator at aol.com wrote: > On Feb 13, 2:24 am, Steve Holden wrote: [...] >>>> This wouldn't be a simple project, but since there's a Windows buildbot >>>> for Python there's no reason why the same couldn't be done for >>>> extensions. I'll raise this with the PSF and see what the response is: >>>> then your carping will at least have had some positive effect ;-) >>>> Stick with it, and let's try to make things better. >>> Ok. >> On a point of information, as it happens there's a Board meeting today >> and I have tabled the topic for discussion. Unfortunately I can't >> guarantee to attend the meeting (I am moving from the UK to the USA this >> week) but I will try to do so, and will attempt to report back to c.l.py >> within a week. > > Again, thanks for listening and trying to help. Even if nothing comes > of > it, at least we tried. I figure that sooner or later something has to > be > done and I'd rather see it done sooner. And no, I don't think I'm > entitled to that. > >> regards >> Steve >> Unfortunately the matter wasn't discussed due to my enforced absence from the 'Net and pressure of other business. But it's on my radar now and I will continue to progress it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From sjmachin at lexicon.net Wed Feb 21 00:37:25 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 21:37:25 -0800 Subject: eval('000052') = 42? In-Reply-To: References: Message-ID: <1172036245.213528.303000@v33g2000cwv.googlegroups.com> On Feb 21, 3:09 pm, Astan Chee wrote: > Hi, > I just tried to do > eval('00052') and it returned 42. > Is this a known bug in the eval function? Or have I missed the way eval > function works? > Thanks Eight fives are forty. Forty plus two is forty two. I see no bug here, only a language design strangeness which can be blamed on the then- pervasive influence of all things from Bell Labs :-) BTW, hasn't anyone told you not to play with the eval function? Put it down. You could catch something nasty. From dingbat at codesmiths.com Thu Feb 15 14:10:53 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 15 Feb 2007 11:10:53 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: <381Bh.2463$Jl.1669@newsread3.news.pas.earthlink.net> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <7xps8cjt8s.fsf@ruckus.brouhaha.com> <1171538985.045430.317190@v45g2000cwv.googlegroups.com> <381Bh.2463$Jl.1669@newsread3.news.pas.earthlink.net> Message-ID: <1171566653.207307.213490@k78g2000cwa.googlegroups.com> On 15 Feb, 17:55, Dennis Lee Bieber wrote: > Sounds more like a case for a parser/lexer wherein the emitted "code > tokens" are the "new style" identifiers... 8-( I'm trying not to think about that.... Fortunately I don't think it's _quite_ that bad. From ziga.seilnacht at gmail.com Tue Feb 27 17:30:26 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 27 Feb 2007 14:30:26 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172613744.661578.227150@k78g2000cwa.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> Message-ID: <1172615426.752353.25610@8g2000cwh.googlegroups.com> Andrew Felch wrote: > > Thanks Ziga. I use pickle protocol 2 and binary file types with the > command: "cPickle.dump(obj, file, 2)" > > I did your suggestion, i commented out the "__call__" function of > MetaInstanceTracker and copied the text to the __new__ function of > AutoReloader (code appended). I got a crazy recursive error message > (also appended below). In my code, I am creating a new instance, > rather than using the pickled object (it needs to work in both modes). > > Thanks very much for helping me get through this. With my development > approach, finding a solution to this problem is really important to > me. Here is a version that should work. It should work with all protocols, see InstanceTracker.__reduce_ex__. Note that all subclasses of InstanceTracker and AutoReloader should be cautious when overriding the __new__ method. They must call their base class' __new__ method, preferably by using super(), or the tracking won't work. # adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 import weakref, inspect class MetaInstanceTracker(type): def __init__(cls, name, bases, ns): super(MetaInstanceTracker, cls).__init__(name, bases, ns) cls.__instance_refs__ = [] def __instances__(cls): instances = [] validrefs = [] for ref in cls.__instance_refs__: instance = ref() if instance is not None: instances.append(instance) validrefs.append(ref) cls.__instance_refs__ = validrefs return instances class InstanceTracker(object): __metaclass__ = MetaInstanceTracker def __new__(*args, **kwargs): cls = args[0] self = super(InstanceTracker, cls).__new__(*args, **kwargs) cls.__instance_refs__.append(weakref.ref(self)) return self def __reduce_ex__(self, proto): return super(InstanceTracker, self).__reduce_ex__(2) class MetaAutoReloader(MetaInstanceTracker): def __init__(cls, name, bases, ns): super(MetaAutoReloader, cls).__init__(name, bases, ns) f = inspect.currentframe().f_back for d in [f.f_locals, f.f_globals]: if name in d: old_class = d[name] for instance in old_class.__instances__(): instance.change_class(cls) cls.__instance_refs__.append(weakref.ref(instance)) for subcls in old_class.__subclasses__(): newbases = [] for base in subcls.__bases__: if base is old_class: newbases.append(cls) else: newbases.append(base) subcls.__bases__ = tuple(newbases) break class AutoReloader(InstanceTracker): __metaclass__ = MetaAutoReloader def change_class(self, new_class): self.__class__ = new_class Ziga From pythonnews at nospam.jmbc.fr Sun Feb 4 04:40:44 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Sun, 04 Feb 2007 10:40:44 +0100 Subject: wxPython: TextCtrl delayed update when using TE_RICH(2) In-Reply-To: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> References: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> Message-ID: <45c5aa41$0$21142$7a628cd7@news.club-internet.fr> Hi, > def Execute(self, evt): > print "Start query" > time.sleep(5) > > The "Start query" message should show in the *messages* box when I > press the button. Instead, it shows only after the time.sleep(5) > delay. > > If I don't use the wx.TE_RICH / wx.TE_RICH2 style on *messages*, the > text shows before the time.sleep(5) For this kind of stuff, I'd try to put "self.out.WriteText(string)" in some 'Idle' event, which avoid to fall in focus loops or other objects events management problems not easy to solve. Did you try something like that : def write(self, string): self.outBuffer= string def onIdle(self,event): if self.outBuffer != None: self.out.WriteText(self.outBuffer) self.outBuffer= None From arkanes at gmail.com Thu Feb 1 13:57:51 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 1 Feb 2007 12:57:51 -0600 Subject: mysqldb duplicate entry error handling In-Reply-To: <1170355868.967026.240510@h3g2000cwc.googlegroups.com> References: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> <1170355868.967026.240510@h3g2000cwc.googlegroups.com> Message-ID: <4866bea60702011057k6e0f883bw7137732448074b00@mail.gmail.com> On 1 Feb 2007 10:51:09 -0800, baur79 wrote: > now it gives this error > > except IntegrityError, NameError: > NameError: global name 'IntegrityError' is not defined > > any idea > i have python 2.3.2 installed > IntegrityError will most likely be defined in the namespace of whatever you're using for MySQL access. From etatoby at gmail.com Sat Feb 24 11:45:31 2007 From: etatoby at gmail.com (Toby) Date: 24 Feb 2007 16:45:31 GMT Subject: How to build Hierarchies of dict's? (Prototypes in Python?) References: Message-ID: <45e06bab$0$20809$5fc30a8@news.tiscali.it> Charles D Hixson wrote: > What I basically want is a kind of class that has both class and > instance level dict variables, such that descendant classes > automatically create their own class and instance level dict variables. > The idea is that if a member of this hierarchy looks up something in > it's local dict, and doesn't find it, it then looks in the class dict, > and if not there it looks in its ancestral dict's. This is rather like > what Python does at compile time, but I want to do it at run time. I don't understand, Python already does it at runtime: class A: A_class_var = 1 class B(A): B_class_var = 2 def __init__(self): self.B_inst_var = 3 >>> b.A_class_var 1 >>> b.B_class_var 2 >>> b.B_inst_var 3 >>> A.another = 4 >>> b.another 4 Can you post a ">>>"-script of what you would like your classes to do? Toby From sjmachin at lexicon.net Fri Feb 16 17:07:52 2007 From: sjmachin at lexicon.net (John Machin) Date: 16 Feb 2007 14:07:52 -0800 Subject: Compression library In-Reply-To: <1171616579.762722.81270@v45g2000cwv.googlegroups.com> References: <1171616579.762722.81270@v45g2000cwv.googlegroups.com> Message-ID: <1171663672.612021.35670@h3g2000cwc.googlegroups.com> On Feb 16, 8:02 pm, roche.ale... at gmail.com wrote: > Hi all, > I'm looking for a library in python containing severall compression > algorithms like RLE, Deflate, LZ77-78-W, Huffman,...... > do someone know if such of this type of lib exists?? Short answer: Yes Longer answer: You too could know if you were to get off your fundament and get onto your googler ... e.g. 2nd hit from search for "python compression" is """ Compression algorithms in python - by David MacKay This page offers a library of compression algorithms in python. ... """ From robert.kern at gmail.com Wed Feb 7 22:41:33 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 07 Feb 2007 21:41:33 -0600 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: W. Watson wrote: > Robert Kern wrote: >> W. Watson wrote: >>> For some reason Python 2.2.4 cannot find the Numeric module. It's been >>> suggested that I should re-install the Numeric file. How do that? Also the >>> PIL. The three install files are: >>> python-2.4.4.msi >>> PIL-1.1.5.win32-py2.4.exe >>> Numeric-24.2.win32-py2.4.exe >> The latter two are executable installers. Run them. >> > I have re-run Numeric. The python program still cannot detect the Numeric > module. Well, check to make sure that the Python executable is the one that you think it is. You can look at sys.executable to find the actual .exe of the running Python interpreter. With Python 2.4.4 and a standard installation, it should be c:\Python24\python.exe I believe. Then check to make sure that Numeric and PIL are actually installed in c:\Python24\Lib\site-packages\ . -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From irmen.NOSPAM at xs4all.nl Sat Feb 17 19:01:06 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 18 Feb 2007 01:01:06 +0100 Subject: message processing/threads In-Reply-To: References: Message-ID: <45d7976f$0$327$e4fe514c@news.xs4all.nl> Jonathan Curran wrote: > I need a program running in the background to process messages (FIFO order) > which I would send using soap/xmlrpc/pyro (haven't decided yet). According to > my thinking I would need to make this a threaded application. One thread to > process the messages and the other thread(s) would be used to listen for > messages and insert it into the message queue. > > Is my thinking correct? Is there a better way to do such a thing? For your interest: Pyro includes a "server" by itself that takes care of all of this. --Irmen From B.Ogryczak at gmail.com Tue Feb 27 09:09:40 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 27 Feb 2007 06:09:40 -0800 Subject: finding out the precision of floats In-Reply-To: References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> Message-ID: <1172585380.631673.257410@q2g2000cwa.googlegroups.com> On Feb 27, 1:36 pm, Facundo Batista wrote: > Arnaud Delobelle wrote: > > (and I don't want the standard Decimal class :) > > Why? Why should you? It only gives you 28 significant digits, while 64-bit float (as in 32-bit version of Python) gives you 53 significant digits. Also note, that on x86 FPU uses 80-bit registers. An then Decimal executes over 1500 times slower. >>> from timeit import Timer >>> t1 = Timer('(1.0/3.0)*3.0 - 1.0') >>> t2 = Timer('(Decimal(1)/Decimal(3))*Decimal(3)-Decimal(1)', 'from decimal import Decimal') >>> t2.timeit()/t1.timeit() 1621.7838879255889 If that's not enough to forget about Decimal, take a look at this: >>> (Decimal(1)/Decimal(3))*Decimal(3) == Decimal(1) False >>> ((1.0/3.0)*3.0) == 1.0 True From andrea.gavana at gmail.com Wed Feb 7 15:29:15 2007 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Wed, 7 Feb 2007 21:29:15 +0100 Subject: Simple SVN/CVS-like library in Python? Message-ID: Hi All, in our office we work with quite complex input files for a reservoir simulator. Those files have thousands of keywords, switches, sub-keywords and whatever. Every time a modification is requested, we modify the input file and re-run the simulator. Obviously, the possible modifications are innumerable: so, after few months, we lose the records of all the changes we made during time and we don't have anymore a clear history of our work. This can be a problem, as sometimes it happens that an old input file is requested by collegues/sub-companies, and it is a pain to retrieve the correct file and results. So, I have written a GUI in wxPython that could help us in tracking the history, but I was wondering if there exists a small and simple SVN/CVS-like library in Python that may help us in a better way, storing modifications/changes and showing which input file are the "children" of (are derived from) another input file (older). But I am open to all possible suggestions to improve/modify the software, as this is an area in which my experience is about nothing above zero. Thank you very much for every hint. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ From gagsl-py at yahoo.com.ar Fri Feb 16 05:15:41 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 07:15:41 -0300 Subject: KeyboardInterrupt not caught References: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> <5f56302b0702160158g2bc55f99qdd00a06cfc4f8e09@mail.gmail.com> Message-ID: En Fri, 16 Feb 2007 06:58:54 -0300, Daniel Nogradi escribi?: >> why is KeyboardInterrupt not caught (xp)? > > Hi, are you sure this is exactly what you run? > The code above works perfectly for me and prints > > kbd-interr,SystemExit > normal end > > as it should upon pressing Ctrl-C (although I'm on linux not xp but > that shouldn't matter at all). I'm using XP and it works as expected too. -- Gabriel Genellina From http Thu Feb 15 19:13:48 2007 From: http (Paul Rubin) Date: 15 Feb 2007 16:13:48 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> <1171584254.805386.97300@a75g2000cwd.googlegroups.com> Message-ID: <7xvei3arib.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > Now what is it you want to do with args that you can't do with it as a > tuple? I'm ok with it being a tuple, but I'm not so wed to the notion that tuples are record structures. I think it would be lame to not be able to iterat through the arg list, for example. From spe.stani.be at gmail.com Wed Feb 28 13:38:22 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 28 Feb 2007 10:38:22 -0800 Subject: Eric on XP for Newbie In-Reply-To: <1172682935.812867.239660@k78g2000cwa.googlegroups.com> References: <1172679222.026525.248430@a75g2000cwd.googlegroups.com> <1d9au31u0gabx$.bmnr6jzorw6m.dlg@40tude.net> <1172682935.812867.239660@k78g2000cwa.googlegroups.com> Message-ID: <1172687902.289346.91940@s48g2000cws.googlegroups.com> On Feb 28, 6:15 pm, jeffwatkins2... at gmail.com wrote: > On Feb 28, 4:27 pm, Alan Franzoni > > wrote: > > Il 28 Feb 2007 08:13:42 -0800, jeffwatkins2... at gmail.com ha scritto: > > > [cut] > > > Forget the tars. > > >http://www.quadgames.com/download/pythonqt/ > > > Get the two EXEs here. BTW, I don't think Eric3 is a really good IDE on > > Windows (yet). Try something likeSPE, or Scite, or any other editor like > > UltraEdit32. > > Thanks > > I've installedSPE. But what now? How do I run it? It doesn't appear > in "all programs" and ther's no .exe file that I can find Which installer did you use? If you used the python25 installer, use the python24 installer instead. (It will also work as it is not specific to 2.4 I have removed the python25 installer.) Than the shortcuts should appear in your "All Programs". Stani PS. A new version is about to released: http://pythonide.stani.be From etatoby at gmail.com Sat Feb 24 12:27:12 2007 From: etatoby at gmail.com (Toby) Date: 24 Feb 2007 17:27:12 GMT Subject: Endianness conversion References: <45e05c49$0$20809$5fc30a8@news.tiscali.it> Message-ID: <45e07570$0$20809$5fc30a8@news.tiscali.it> Dan Sommers wrote: > You could try the struct module. If your input comes in fixed sized > chunks, just call struct.unpack and struct.pack once per chunk. Thanks, but it was a bit awkward to use for big chunks. I ended up writing my own byteswapper in Pyrex: def swapbytes(data): "Swap every two bytes of a even-sized python string, in place" cdef int i cdef char t, *p p = data for i from 0 <= i < len(data) / 2: t = p[0] p[0] = p[1] p[1] = t p = p + 2 Toby From Kiran.Karra at gmail.com Thu Feb 1 17:57:59 2007 From: Kiran.Karra at gmail.com (Kiran) Date: 1 Feb 2007 14:57:59 -0800 Subject: python executing windows exe Message-ID: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> Hi everybody, I am making python run an executable using the os module. Here is my question. The executable, once it is running, asks the user to input a filename that it will process. Now, my question is how do i automate this. let me make this clear, it is not an argument you pass in when you type in the exe. An example below illustrates: THIS IS NOT WHAT YOU DO: nec2d.exe couple1.nec # couple1.nec is the file you want to prcess rather, what you do is in windows cmd: nec2d.exe **** PROGRAM PRINTS OUT STUFF***** **** PROGRAM PRINTS OUT STUFF***** **** PROGRAM PRINTS OUT STUFF***** **** PROGRAM PRINTS OUT STUFF***** Please enter input file: <--------- THIS IS WHERE THE USER IS ASKED TO TYPE IN THE FILENAME everybody thanks for your help -- Kiran From gagsl-py at yahoo.com.ar Mon Feb 12 01:01:56 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 03:01:56 -0300 Subject: string.replace non-ascii characters References: Message-ID: En Mon, 12 Feb 2007 02:38:29 -0300, Samuel Karl Peterson escribi?: Sorry to steal the thread! This is only related to your signature: > "if programmers were paid to remove code instead of adding it, > software would be much better" -- unknown I just did that last week. Around 250 useless lines removed from a 1000 lines module. I think the original coder didn't read the tutorial past the dictionary examples: *all* functions returned a dictionary or list of dictionaries! Of course using different names for the same thing here and there, ugh... I just throw in a few classes and containers, removed all the nonsensical packing/unpacking of data going back and forth, for a net decrease of 25% in size (and a great increase in robustness, maintainability, etc). If I were paid for the number of lines *written* that would not be a great deal :) -- Gabriel Genellina From nagle at animats.com Fri Feb 2 01:55:54 2007 From: nagle at animats.com (John Nagle) Date: Fri, 02 Feb 2007 06:55:54 GMT Subject: Python does not play well with others In-Reply-To: <7x64alp986.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> Message-ID: <_fBwh.15572$ji1.7286@newssvr12.news.prodigy.net> Paul Rubin wrote: > Ben Finney writes: > >>>Python still isn't ready for prime time in the web hosting world. >> >>That doesn't follow. It's just as valid to say that the web hosting >>providers (that you've interacted with so far) aren't ready to support >>the Python functionality you want. > > > I'd say the functionality that John wants is the same that pretty much > everyone wants, and it's much easier to get for other languages than > for Python. That's about it. What's so striking is that this was a surprise. One would think from what one reads about Python that it just works. I've been able to pound through these problems. I finally got M2Crypto, Python, and MySQLdb all working on a shared hosting server. But it was quite a bit of work. I gave up on getting the hosting provider to install current versions. So I just spent four hours struggling with the build procedure for M2Crypto, to get it to build with a combination of versions of OpenSSL, M2Crypto, and SWIG that aren't the latest, but are supposed to work. (Hint: you need to define "__i386__" or other machine if appropriate as a command line argument to SWIG, so that OpenSSL's older conditional includes work right.) This is really a build system management and coordination issue. Python has only two kinds of modules - nailed into the distribution, or external and unsupported. Whether or not something is supported should be independent of whether it's built by the main build file. Components which have external dependencies, like SSL, M2Crypto, and MySQLdb don't fit well into that model. They need to undergo regression testing with each new Python distribution, but they don't really need to be part of the main build. Right now, SSL is too far inside, while the other two are too far outside. A middle ground would help. Otherwise, you get version hell. John Nagle From hg at nospam.org Tue Feb 27 02:51:52 2007 From: hg at nospam.org (hg) Date: Tue, 27 Feb 2007 08:51:52 +0100 Subject: Is there a technic to avoid this bug References: <54inn6F2115doU1@mid.uni-berlin.de> <1172586643.865731.78020@m58g2000cwm.googlegroups.com> Message-ID: Michele Simionato wrote: > pychecker Thanks all ... pydev extension does not however ... will have to install pychecker also. hg From mail at timgolden.me.uk Wed Feb 14 08:19:25 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 14 Feb 2007 13:19:25 +0000 Subject: WindowsNT user authentication In-Reply-To: <1171458314.065280.164360@v33g2000cwv.googlegroups.com> References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> <1171294708.261232.18290@p10g2000cwp.googlegroups.com> <1171357845.968797.229580@m58g2000cwm.googlegroups.com> <1171458314.065280.164360@v33g2000cwv.googlegroups.com> Message-ID: <45D30C5D.7040207@timgolden.me.uk> billie wrote: > Another question, I'm sorry. > Do you got any idea about how to get permissions of a file/directory > given the username? > For example: I would like to know if C:\my_file.ext is readable/ > writable by user 'x' or not. This is an unfortunately messy question. The easiest answer -- and I'm quite serious -- might be to have the user *try* to read it and to catch the exception. Quite apart from the mildly labyrinthine techniques for determining object security, you face a potential race condition: by the time you've tested and got your answer, someone could have changed the permissions. Unlikely, you'll admit, but possible enough to the try-except approach attractive. There are some examples of file security both in the CHM which comes with the pywin32 extensions and in the demos folder, on my machine: c:\python24\lib\site-packages\win32\demos\security I was going to start explaining win32 security terms in this reply, but perhaps I won't unless the try-it-and-see approach advocated above doesn't work! HTH somewhat TJG From kousue at gmail.com Tue Feb 27 10:52:17 2007 From: kousue at gmail.com (kousue at gmail.com) Date: 27 Feb 2007 07:52:17 -0800 Subject: Checking for EOF in stream In-Reply-To: References: Message-ID: <1172591537.153394.124130@a75g2000cwd.googlegroups.com> On Feb 19, 6:58 pm, GiBo wrote: > Hi! > > Classic situation - I have to process an input stream of unknown length > until a I reach its end (EOF, End Of File). How do I check for EOF? The > input stream can be anything from opened file through sys.stdin to a > network socket. And it's binary and potentially huge (gigabytes), thus > "for line in stream.readlines()" isn't really a way to go. Could you use xreadlines()? It's a lazily-evaluated stream reader. > For now I have roughly: > > stream = sys.stdin > while True: > data = stream.read(1024) > process_data(data) > if len(data) < 1024: ## (*) > break > > I smell a fragile point at (*) because as far as I know e.g. network > sockets streams may return less data than requested even when the socket > is still open. Well it depends on a lot of things. Is the stream blocking or non- blocking (on sockets and some other sorts of streams, you can pick this yourself)? What are the underlying semantics (reliable-and- blocking TCP or dropping-and-unordered-UDP)? Unfortunately, you really need to just know what you're working with (and there's really no better solution; trying to hide the underlying semantics under a proscribed overlaid set of semantics can only lead to badness in the long run). > I'd better like something like: > > while not stream.eof(): > ... > > but there is not eof() method :-( > > This is probably a trivial problem but I haven't found a decent solution. For your case, it's not so hard: http://pyref.infogami.com/EOFError says "read() and readline() methods of file objects return an empty string when they hit EOF." so you should assume that if something is claiming to be a file-like object that it will work this way. > Any hints? So: stream = sys.stdin while True: data = stream.read(1024) if data=="": break process_data(data) From sjmachin at lexicon.net Thu Feb 8 20:11:21 2007 From: sjmachin at lexicon.net (John Machin) Date: 8 Feb 2007 17:11:21 -0800 Subject: struct.pack bug? In-Reply-To: <45CB9D09.3030604@pytex.org> References: <45CB9D09.3030604@pytex.org> Message-ID: <1170983481.155968.125040@s48g2000cws.googlegroups.com> On Feb 9, 8:58 am, Jonathan Fine wrote: > Hello > > I find the following inconsistent: > === > >>> sys.version > '2.4.1a0 (#2, Feb 9 2005, 12:50:04) \n[GCC 3.3.5 (Debian 1:3.3.5-8)]' > >>> pack('>B', 256) > '\x00' > >>> pack(' '\x00' > >>> pack('B', 256) > Traceback (most recent call last): > File "", line 1, in ? > struct.error: ubyte format requires 0<=number<=255 > >>> > === > > I was hoping that '>B' and ' ust as 'B' does. > > On Oct 27 2006, 11:17 am, Jansson Christer reported a > different anomoly to this newsgroup, using the same > subject. Your Python is out-of-date in two dimensions: the 2.4 series is way past 2.4.1, and Python 2.5 has been out for a while. Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 | >>> from struct import pack | >>> pack(' References: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Message-ID: <1171363423.429096.86840@m58g2000cwm.googlegroups.com> J. Clifford Dyer wrote: > Stuart D. Gathman wrote: > > On Sat, 03 Feb 2007 05:02:54 -0800, Tool69 wrote: > > > >> Does anyone have any advice, and more genraly how to script Vim with > >> Python ? > > > > :py import sys > > :py print sys.version > > :help :py > > > >> I know I can put some python functions inside my vimrc file like > >> this : > >> > >> function! My_function() > >> python << EOF > >> import vim, string > >> ...blablabla > >> EOF > >> endfunction > >> > >> but I would like to use external ".py" files. > > > > :py import myfile > > > > Use :py inside your vimrc - don't run python externally. > > Which versions of vim is this valid for? I tried ":py print 'Hello'", > and got "E319: Sorry, the command is not available in this version" It's valid for vim 5.0 and later (all official vim releases since March 1998). You have to make sure python support is enabled at build time with --enable-pythoninterp or other configure options that turn it on (check for +python in the output of ":ver" to see if a precompiled binary includes python support). From steve at REMOVE.THIS.cybersource.com.au Thu Feb 22 16:18:10 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Feb 2007 08:18:10 +1100 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: On Thu, 22 Feb 2007 08:18:07 +0200, Hendrik van Rooyen wrote: > I would xor each char in it with 'U' as a mild form of obfuscation... I've often wished this would work. >>> 'a' ^ 'U' Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for ^: 'str' and 'str' instead of the more verbose >>> chr(ord('a') ^ ord('U')) '4' > Look at the array module to get things you can xor, or use ord() on > each byte, and char() Arrays don't support XOR any more than strings do. What's the advantage to using the array module if you still have to jump through hoops to get it to work? ''.join([chr(ord(c) ^ 85) for c in text]) is probably about as simple as you can get. -- Steven. From JStoneGT at aol.com Wed Feb 7 08:35:33 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Wed, 7 Feb 2007 08:35:33 EST Subject: python for web programming Message-ID: Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Feb 11 00:33:07 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 Feb 2007 21:33:07 -0800 Subject: os.tmpfile() -> permission denied (Win XP) In-Reply-To: References: <1171169872.507298.196990@j27g2000cwj.googlegroups.com> Message-ID: <1171171987.567968.278740@s48g2000cws.googlegroups.com> On Feb 11, 4:15 pm, "Gabriel Genellina" wrote: > En Sun, 11 Feb 2007 01:57:52 -0300, John Machin > escribi?: > > > | >>> os.tmpfile() > > Traceback (most recent call last): > > File "", line 1, in > > OSError: [Errno 13] Permission denied > > > 1. Before I start checking what permissions who has to do what to > > which, what directory is it likely to be trying to open the temp file > > in? C:\WINDOWS\TEMP....? > > You could analyze the source, I have already followed the twisty little passages: os.tmpfile() is really nt.tempfile(), but there is no Modules/ntmodule.c (Modules/ posixmodule.c does a Jekyll & Hyde trick). (nt|posix)module calls tmpfile(), which is (as I mentioned) in the C stdio library. How can I analyse the source of that? Have Microsoft had a rush of blood to the head and gone open source overnight?? > but usually I find easier to use FILEMON:http://www.sysinternals.com Thanks, I'll try that. Cheers, John From scott.daniels at acm.org Tue Feb 27 00:15:19 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 26 Feb 2007 21:15:19 -0800 Subject: Lists: Converting Double to Single In-Reply-To: <45e38410$0$6830$4d3efbfe@news.sover.net> References: <45e38410$0$6830$4d3efbfe@news.sover.net> Message-ID: <12u7fhgfqfffp66@corp.supernews.com> Leif K-Brooks wrote: > rshepard at nospam.appl-ecosys.com wrote: >> ... >> Unfortunately, when I try to use that last list in a NumPy function, >> I'm told that it cannot be broadcast to the correct shape. So, what I >> want to do is strip the extra brackes from each end to leave just >> [3.5, 4.5, 5.5, 6.5, 7.5]. > > l = l[0] Or, if you want to simultaneously assert there is only one list, use unpacking like: [l] = l Although I'd prefer to use a better name than l; something like: lst = [[3.5, 4.5, 5.5, 6.5, 7.5]] [inner] = lst print inner, lst -- --Scott David Daniels scott.daniels at acm.org From S.Mientki-nospam at mailbox.kun.nl Fri Feb 16 19:34:53 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 17 Feb 2007 01:34:53 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <45d626f5$0$19811$426a74cc@news.free.fr> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Stef Mientki a ?crit : >> ifti_crazy at yahoo.com wrote: >> >>> I am VB6 programmer and wants to start new programming language but i >>> am unable to deciced. >>> >>> i have read about Python, Ruby and Visual C++. but i want to go >>> through with GUI based programming language like VB.net >>> >>> so will you please guide me which GUI based language has worth with >>> complete OOPS Characteristics >> >> Although the GUI of Python is not as good as VB, > > "the GUI of Python" ? What's that ? Python is a *programming language*, > not a GUI toolkit. The final goal of programming language is (in most cases) meant to create functional things, that can assist people to perform their tasks. The UI of that resulting thing should be optimal adapted to the final audience (and task). My audience is most comfortable with a intuitive GUI. In most of my applications, I need about 50% of the time for the GUI and 50% for the other functional code. These estimates are for Delphi (is about identical as VB, which I used previous). For what I've seen until now from Python, - designing the GUI will cost me about 2 .. 3 times as much in Python - Python is not capable of doing everything I need (almost all interactive actions are very primitive and crashes a lot) - designing my other functional code in Python, will reduce the development time with an estimated factor of 2 So the combination of Delphi (or VB) and Python seems the optimal combination for heavily GUI's. - one of the big problems with Python is the version differences (compatibility) In one of the other threads, Dabo was meant as a GUI designer, I tried it yesterday, and although it looks very promising, at the moment this is not a graphical design environment, just a complex (compared to Delphi) design environment with graphical feedback. Just my 2 cents ;-) > >> (although others in this group will definitely have a different opinion), >> the beautiful thing about Python is, >> that you can easily embed /encapsulate it in VB, >> giving you the best of both worlds. > > Why would one go thru the pain of "embedding" Python in VB (if that's > even possible) when Python can directly access the Win32 API and all COM > components and have bindings for GUI toolkits like wxWidgets ? "Pain of embedding" ? About 10 lines of code, which you find ready to use on the web ;-) And the performance is fantastic ! (I even use it for realtime, as a complete replacement for MatLab and LabView) Bruno, I think we've a different audience / target application, and at the moment we'll never agree about GUI, but I promise that'll try the different Python graphics in the future, and you will be the first to hear if my current conclusions are wrong. cheers, Stef From jjl at pobox.com Fri Feb 23 16:16:41 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 23 Feb 2007 21:16:41 GMT Subject: Looking for contract developer(s) - where can I find them? References: <1172121800.532683.126450@q2g2000cwa.googlegroups.com> Message-ID: <874ppczi9w.fsf@pobox.com> rscottco at gmail.com writes: > On Feb 21, 9:51 pm, Scott SA wrote: > > > > I've just sent a job listing to python.org and posted this message on > > comp.lang.python, > > Interesting, so Python-list at python.org and comp.lang.python are > _related_. I guess that means I'm the new guy on the block. Well I > guess this joke is on me this time ... LOL! Yes, there's a bidirectional gateway between the two -- post to one and it shows up on the other. John From martin at v.loewis.de Thu Feb 22 15:00:09 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 22 Feb 2007 21:00:09 +0100 Subject: Possible to set cpython heap size? In-Reply-To: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> Message-ID: <45DDF649.5020901@v.loewis.de> Andy Watson schrieb: > I have an application that scans and processes a bunch of text files. > The content I'm pulling out and holding in memory is at least 200MB. > > I'd love to be able to tell the CPython virtual machine that I need a > heap of, say 300MB up front rather than have it grow as needed. I've > had a scan through the archives of comp.lang.python and the python > docs but cannot find a way to do this. Is this possible to configure > the PVM this way? You can configure your operating system. On Unix, do 'ulimit -m 200000'. Regards, Martin From S.Mientki-nospam at mailbox.kun.nl Fri Feb 9 14:56:03 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 09 Feb 2007 20:56:03 +0100 Subject: Best Free and Open Source Python IDE In-Reply-To: <1171047698.558376.160500@v33g2000cwv.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> <1171047698.558376.160500@v33g2000cwv.googlegroups.com> Message-ID: <6fd78$45ccd1c1$d443bb3a$15713@news.speedlinq.nl> Szabolcs Nagy wrote: > Srikanth wrote: >> Yes, >> >> All I need is a good IDE, I can't find something like Eclipse (JDT). >> Eclipse has a Python IDE plug-in but it's not that great. Please >> recommend. >> >> Thanks, >> Srikanth > > try pida > http://pida.co.uk/index.php/Main_Page > nice idea to re-use components you already have. Which brings me to some other questions on waste: - isn't it a pitty so many people are involved in writing another editor / IDE ? - isn't it a waste for newbies to evaluate a dozen editors / IDE's ? What anser do we really give here ? Aren't we just telling the guy, what we've chozen (with our limited overview of our newbie time) ;-) (sorry, I also gave an answer ;-) Can't we persuade the next newbie, asking this question, to start some kind of wiki page, where the differences between editors / IDE's are listed ? Unfortunately he number of IDE's / editors is so large, a simple 2 dimensional array of features would become too large ;-) Maybe a first split would be the required OS ? Next split could be editor-features and IDE features ? just some thoughts, of a some months old newbie, Stef Mientki From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 16:43:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 22:43:27 +0100 Subject: string.find for case insensitive search In-Reply-To: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: <45ca40d9$0$4321$426a74cc@news.free.fr> Johny a ?crit : > Is there a good way how to use string.find function to find a > substring if I need to you case insensitive substring? "abCdZEd".lower().find("BcD".lower()) From g.willgoose at telluricresearch.com Mon Feb 12 23:52:57 2007 From: g.willgoose at telluricresearch.com (g.willgoose at telluricresearch.com) Date: 12 Feb 2007 20:52:57 -0800 Subject: get pid of a nohup command in Python Message-ID: <1171342377.456635.203490@q2g2000cwa.googlegroups.com> I'm new to Python and am evaluating moving a project from Tcl/Tk to Python and am stuck on one issue. How can I nohup (or any detached task for that matter) a process and get its PID in Python. The obvious route of (with a trivial example) os.system("nohup ls > junk &") returns the status of the command execution (ie. 0). I wish to get the PID output of the command (e.g. 16617). All the other commands spawn** also seem to return the execution status not the PID. This is a showstopper so any help appreciated. From bignose+hates-spam at benfinney.id.au Tue Feb 27 18:45:02 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 10:45:02 +1100 Subject: Running Python scripts from BASH References: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> Message-ID: <873b4ryxkx.fsf@benfinney.id.au> "Ishpeck" writes: > I'm using Python to automate testing software for my company. I > wanted the computers in my testing lab to automatically fetch the > latest version of the python scripts from a CVS repository and then > ask a local database server which of the scripts to run. You may be interested in experimenting with the Buildbot for this purpose. -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From steve at REMOVEME.cybersource.com.au Wed Feb 14 20:59:03 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 12:59:03 +1100 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 14 Feb 2007 12:09:34 -0800, Paul Rubin wrote: > "redawgts" writes: >> try: >> f = file(self.filename, 'rb') ... >> Can someone tell me what's wrong with the code? > > Various people have explained the error: if the file open attempt > fails, f is never assigned. Doing it the right way (i.e. handling the > potential exceptions separately) with try/except statements is messy, > so it's worth mentioning that 2.5 adds the new "with" statement to > clean this up. I'm not using 2.5 myself yet so maybe someone will > have to correct me, but I think you'd write: > > from __future__ import with_statement > > self.isDataLoaded = False > with open(self.filename, 'rb') as f: > f.seek(DATA_OFFSET) > self.__data = f.read(DATA_SIZE) > self.isDataLoaded = True > > and that should handle everything, closing the file automatically. I don't have Python 2.5 here to experiment, but how is that different from this? self.isDataLoaded = False try: f = open(self.filename, 'rb') f.seek(DATA_OFFSET) self.__data = f.read(DATA_SIZE) self.isDataLoaded = True except: pass else: pass (apart from being four lines shorter) -- Steven D'Aprano From __peter__ at web.de Mon Feb 19 07:01:36 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 13:01:36 +0100 Subject: (beginners question) howto set self.field4.subfield8='asdf'? References: <1171877794.747825.294890@t69g2000cwt.googlegroups.com> <1171885138.150935.207890@h3g2000cwc.googlegroups.com> Message-ID: openopt at ukr.net wrote: > Thx > but is there any simpleir way, if using not class, but just struct (or > something like that, MATLAB equivalent for that one)? > I'm thinking of rewriting some optimization solvers (non-smooth, > constrained, with (sub)gradients or patterns provided by user) to > Python and I don't know currently is it possible to easy convert > things like > prob = []; > prob.advanced.ralg.hs = 1 (so in this line all subfields are > generating automatically in MATLAB or Octave) > I have huge amount of such lines, and implementing separate class for > each one is unreal. Get used to thinking of a class as a lightweight construct written with well-defined constraints rather than some know-it-all can-do-everything unwieldy monster. You can of course use one class throughout >>> class Struct: ... def __init__(self, **kw): ... self.__dict__.update(kw) ... >>> a = Struct(f=42) >>> b = Struct(x=1, y=2) >>> a.f 42 >>> b.x, b.y (1, 2) but separate classes don't require much more effort and make your code both more readable and more flexible. Peter From lbates at websafe.com Tue Feb 27 18:34:13 2007 From: lbates at websafe.com (Larry Bates) Date: Tue, 27 Feb 2007 17:34:13 -0600 Subject: database without installation again In-Reply-To: References: Message-ID: andrew_s wrote: > Hi! > > I'm looking for any database which I could use without need of instalation. > I've read some threads here but I couldn't find any complete answer. > On my ISP's server I can use Python throu cgi only. There is Python 2.4.3 > and it has only standard library modules and no possibility to oficially > install anything else. > This version has embedded Berkeley DB (bsddb) and it could be OK for storing > data only, but I need a possibility to use simple selects with group by and > aggregates, which I think are not supported by bsddb. SQLite could be good > choice, but unfortunately it's included in standard Python library from > version 2.5. > > Any ideas? Maybe is it possible to "install" by myself something like SQLite > or MySQLdb in my cgi-bin directory? I've tried it putting files from MySQLdb > module, but there was errors with missing libssl.so or sth. I think, the > best solution would be db stored in binary file with interface in based on > standard Python library, but is there anything like that?? > > TIA! > Change to an ISP that allows you: MySQL databases root access to your virtual machine By the time you do the research and/or write something you will have spent more time than moving to another ISP. Its not all that hard and they are CHEAP. -Larry From olivier.feys at gmail.com Mon Feb 5 10:59:23 2007 From: olivier.feys at gmail.com (Olivier Feys) Date: Mon, 05 Feb 2007 16:59:23 +0100 Subject: get objects referencing another one Message-ID: <45C7545B.7010809@gmail.com> I'm working on a tree and I have refcounting problems. Is it possible from an object, to get the list of objects referencing it ? thanks From ziga.seilnacht at gmail.com Tue Feb 27 16:38:42 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 27 Feb 2007 13:38:42 -0800 Subject: gmpy moving to code.google.com In-Reply-To: References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> Message-ID: <1172612322.546122.162640@k78g2000cwa.googlegroups.com> Alex Martelli wrote: > On Feb 27, 2007, at 2:59 AM, Daniel Nogradi wrote: > > > Hi Alex, > > > I did another test, this time with python 2.4 on suse and things are > > worse than in the previous case (which was python 2.5 on fedora 3), > > ouput of 'python gmp_test.py' follows: > > Interesting! gmpy interacts with decimal.Decimal by "monkey- > patching" that class on the fly; clearly the monkey-patching isn't > working with 2.4 on SuSE, so all the addition attempts are failing > (all 6 of them). > > So the issue is finding out why this strategy is failing there, while > succeeding on other Linux distros, Mac, and Windows. This is a bug in Python's decimal module in release 2.4.0. It was fixed in release 2.4.1: http://svn.python.org/view?rev=38708&view=rev Ziga From Finger.Octopus at gmail.com Sat Feb 10 07:21:29 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 10 Feb 2007 04:21:29 -0800 Subject: Distributing Python Applications Message-ID: <1171110089.040455.154690@v33g2000cwv.googlegroups.com> Hello, It has been such a painful thing for me. As I made a program to encrypt files, now I want to distribute that program over other computers. I created .EXE file with py2exe but the "dist" folder makes around 2 mb and it restricts for the python DLL to be within the same folder. Is there any easy way to get this thing done in just one exe file? I mean if I do interfacing with C/C++ will it work for me and if I do interfacing with C/C++ will it be necessary on the other computer to have python installed on it? Thanks in advance... From gagsl-py at yahoo.com.ar Mon Feb 12 14:29:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 16:29:37 -0300 Subject: favourite editor References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> <45D08DAB.6080908@websafe.com> <1171307483.481407.167480@a75g2000cwd.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 16:11:23 -0300, azrael escribi?: > I expirienced some big craches. tra running some aplication vith using > Vpython. when you close the vpython window, pyscripter also crashes. > sometimes im writing some code and suddenly get about 300 error > messages without running anything. I like pyscripter, but sometimes it > drives me crazy But why blame PyScripter when it might be a problem in VPython as well? -- Gabriel Genellina From deviantbunnylord at gmail.com Mon Feb 12 05:20:11 2007 From: deviantbunnylord at gmail.com (deviantbunnylord at gmail.com) Date: 12 Feb 2007 02:20:11 -0800 Subject: Regular Expressions In-Reply-To: <1171227036.789128.188720@q2g2000cwa.googlegroups.com> References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> <1171227036.789128.188720@q2g2000cwa.googlegroups.com> Message-ID: <1171275611.208401.212000@v33g2000cwv.googlegroups.com> HTML: htmllib and HTMLParser (both in the Python library), BeautifulSoup (again GIYF) XML: xml.* in the Python library. ElementTree (recommended) is included in Python 2.5; use xml.etree.cElementTree. The source of HTMLParser and xmllib use regular expressions for parsing out the data. htmllib calls sgmllib at the begining of it's code--sgmllib starts off with a bunch of regular expressions used to parse data. So the only real difference there I see is that someone saved me the work of writing them ;0). I haven't looked at the source for Beautiful Soup, though I have the sneaking suspicion that most processing of html/xml is all based on regex's. From pydecker at gmail.com Fri Feb 16 21:48:43 2007 From: pydecker at gmail.com (Peter Decker) Date: Fri, 16 Feb 2007 21:48:43 -0500 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> Message-ID: On 2/16/07, Stef Mientki wrote: > In one of the other threads, Dabo was meant as a GUI designer, > I tried it yesterday, > and although it looks very promising, > at the moment this is not a graphical design environment, > just a complex (compared to Delphi) design environment with graphical feedback. > Just my 2 cents ;-) Dabo is indeed a work in progress. They are developing the various tools now to get people started, but have plans for a full graphical IDE in the manner of Delphi or Visual Studio. You can complain that this free tool developed by volunteers in their spare time isn't as polished as a commercial tool backed by large corporations that can afford large paid staffs. Or you could contribute. -- # p.d. From GSlusarek at gmail.com Thu Feb 1 06:14:14 2007 From: GSlusarek at gmail.com (Grzegorz Smith) Date: 1 Feb 2007 03:14:14 -0800 Subject: ZSI and WSDL schema Message-ID: <1170328454.427204.245470@p10g2000cwp.googlegroups.com> Hi all. I have problem with ZSI and WSDL schema.I generate from WSDL by wsdl2py client method for webservice. I made soap call and something goes wrong. Doeas anyone know hot to create some server code by ZSI from WSDL?? I just suspectes that my return data from webservice is in incorrect envelope -> so maybe wsdl2py can help mi generate correct server method, or just generate correct structure that webservice should return. Thanks for any help. Gregor From steve at holdenweb.com Sun Feb 4 15:27:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 04 Feb 2007 20:27:15 +0000 Subject: Learning to program in Python In-Reply-To: <1168029599.576718.74200@i15g2000cwa.googlegroups.com> References: <1168028517.005902.172880@11g2000cwr.googlegroups.com> <1168029133.866590.43770@i15g2000cwa.googlegroups.com> <1168029599.576718.74200@i15g2000cwa.googlegroups.com> Message-ID: jbchua wrote: > John Henry wrote: >> jbchua wrote: >>> Hello everybody. >>> >>> I am an Electrical Engineering major and have dabbled in several >>> languages such as Python, C, and Java in my spare time because of my >>> interest in programming. However, I have not done any practical >>> programming because I have no idea where to get started. I taught >>> myself these languages basically by e-tutorials and books. This makes >>> me feel as if I don't really know how to implement these languages. >>> Does anybody have any advice on where to start applying my limited >>> knowledge practically in order to advance my learning? >> Which area of EE are you in? Or just starting on that as well? >> >> If you're just starting, chanllege yourself to build a R mesh and >> calculate the Thevenin equivalent looking out from a particular node. >> Then you can expand that to an RLC network. >> >> Besure to use Objects, think in terms of objects, and code in objects. >> Don't hard code the data type. You'll be able to see how magical the >> Duck Typing is in Python. >> >> Have fun. > > I'm a freshman-- I have yet to take any actual EE classes. I am > actually thinking of maybe changing my focus towards Computer Science > or at least minoring in it. > > To be perfectly honest, I have no idea what you just asked me to do ;\ > That's an answer that indicates you are likely to learn fast. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From deets at nospam.web.de Sun Feb 25 17:17:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 Feb 2007 23:17:46 +0100 Subject: Help on object scope? In-Reply-To: <1172440275.868863.91120@k78g2000cwa.googlegroups.com> References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> <1172440275.868863.91120@k78g2000cwa.googlegroups.com> Message-ID: <54eg90F1vupsiU1@mid.uni-berlin.de> > > Thank you for the advice, but that seems a bit unwieldy. My code will > have about 10 of these global objects, all of which interact with > eachother. It seems silly to have to pass 10 parameters around to each > instance I work with. I hope there is a smarter way to do it, or > perhaps someone can suggest a smarter way to code it. > > Am I stuck with just having to put all the code in one file? That is > what I wanted to avoid, because the file will get incredibly long. It > seems like the only reason my code above failed is because there were > two separate modules. Perhaps I just need to import /lib/q.py in a > different way? You can interact just fine, just qualify the objects with the module names. So in q, you need to use p.r instead of just r. It's another question if this design is really good - relying on so many globals. It would certainly be better to have e.g. a class that looks like this: import p import q class GlueThingy(object): def __init__(self): self.p1 = p.SomeObject(self) self.q1 = q.SomeOtherObject(self) Then in SomeObject you can use the passed GlueThingy reference to access other instances: class SomeObject(object): def __init__(self, glue): self.glue = glue def do_something(self): self.glue.q1.foobar() Diez From tleeuwenburg at gmail.com Thu Feb 8 22:59:40 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 8 Feb 2007 19:59:40 -0800 Subject: Looking for a MoinMoin guru - MoinMoin+SpamBayes == no wiki spam? In-Reply-To: <1170981347.050263.181360@j27g2000cwj.googlegroups.com> References: <1170981347.050263.181360@j27g2000cwj.googlegroups.com> Message-ID: <1170993580.119528.112650@s48g2000cws.googlegroups.com> I think it's a fantastic idea, myself. I think it should work well. It's probably important to filter the edit, not the whole article, otherwise the ham might obscure the spam. Cheers, -T From stigsen at e-texteditor.com Fri Feb 16 10:44:08 2007 From: stigsen at e-texteditor.com (Alexander Stigsen) Date: Fri, 16 Feb 2007 16:44:08 +0100 Subject: [ANN] wxCocoaDialog v0.3 Message-ID: <45D5D148.6090109@e-texteditor.com> wxCocoaDialog v0.3 http://code.google.com/p/wxcocoadialog/ wxCocoaDialog is an multi-platform port of the CocoaDialog application for OS X, that allows the use of common GUI controls such as file selectors, text input, progress bars, yes/no confirmations and more with a command-line application. It is ideal for use in shell and Python scripts (or Perl, or Ruby, or... etc). Since the use of the original CocoaDialog is very common in shell scripts on Mac OS X, the port makes it possible to to also use such scripts on Linux and Windows (with cygwin). Implemented Controls As of wxCocoaDialog v0.3, the following controls are implemented: * inputbox * standard-inputbox * secure-inputbox * secure-standard-inputbox * dropdown * progressbar * textbox * msgbox * ok-msgbox * yesno-msgbox The wxWidgets port was originally created for use in the e text editor ( http://e-texteditor.com ), which supports TextMate bundles and can be extended with shell scripts (through cygwin) and in any scripting language. Since it could be useful in a lot of other contexts than e, it was released to the community as open source. From arnodel at googlemail.com Tue Feb 27 02:29:04 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 26 Feb 2007 23:29:04 -0800 Subject: design question: no new attributes In-Reply-To: References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: <1172561344.290126.191530@h3g2000cwc.googlegroups.com> On 27 Feb, 06:40, "Alan Isaac" wrote: > So my question remains: > how best to trap any such attempt > subsequent to object initialization? > (I am willing to have properties for > all data attributes, if that helps.) > You can define the __setattr__ method in your class as def __setattr__(self, attr, val): if hasattr(self, attr): self.__dict__[attr] = val else: # Tell the user off but of course the user can set attributes through instance.__dict__['attrname'] = val So to really do it you would need to design your own metaclass -- Arnaud From ahmerhussain at gmail.com Mon Feb 19 09:48:34 2007 From: ahmerhussain at gmail.com (Ahmer) Date: 19 Feb 2007 06:48:34 -0800 Subject: PyDev on Mac In-Reply-To: <53rf37F1ttqnuU1@mid.uni-berlin.de> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> <1171812580.477975.37060@t69g2000cwt.googlegroups.com> <53rf37F1ttqnuU1@mid.uni-berlin.de> Message-ID: <1171896514.236693.316700@h3g2000cwc.googlegroups.com> On Feb 18, 12:01 pm, "Diez B. Roggisch" wrote: > Ahmer schrieb: > > > > > On Feb 18, 4:50 am, "Diez B. Roggisch" wrote: > >> Ahmer schrieb: > > >>> I've been trying to set up PyDev on my new MacBook Pro, but i have not > >>> had an success. > >>> Could you please help! > >> Just wait until my crystal ball comes back from the cleaners, and I will > >> start looking at your problem. > > >> As you can lay back and do nothing while that happens, I suggest you > >> take this highly entertaining read: > > >>http://www.catb.org/~esr/faqs/smart-questions.html > > >> Diez > > > The main problem seems to be locating Python. > > > Even though I installed the official python for mac, it says the > > interpreter is invalid. > > So I tried jPython, no succes on that either. It always tells me I am > > using an invlaid interpreter. > > crystal ball still not available. > > Who tells you what exactly when you do what? Is there a shell-script > involved, what happens if you enter "python" at the commandline and > press return? > > All this are uneccessary guessing games because you don't give enough > context. Which is one of the many things mentioned on the site I > suggested you to read. So I think you should read it again. > > Diez Pythin runs but PyDev won't use the inerpreter. It gives me an error saying I'm using an invalid interpreter. Is there a way to do this using jPython? From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 15:16:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 21:16:31 +0100 Subject: Sorting a list In-Reply-To: <45c240cf$0$10895$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> Message-ID: <45c243a7$0$3020$426a34cc@news.free.fr> John Salerno a ?crit : > Hi everyone. If I have a list of tuples, and each tuple is in the form: > > (year, text) as in ('1995', 'This is a citation.') > > How can I sort the list so that they are in chronological order based on > the year? Calling sort() on the list should just work. > Is there a better way to do this than making a list of tuples? Depends... > (So far I have a text file and on each line is a citation. I use an RE > to search for the year, then put this year and the entire citation in a > tuple, and add this tuple to a list. You don't tell how these lines are formatted, but it's possible that you don't even need a regexp here. But wrt/ sorting, the list of tuples with the sort key as first element is one of the best solutions. From bj_666 at gmx.net Thu Feb 1 03:13:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 01 Feb 2007 09:13:13 +0100 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170308178.823986.322700@h3g2000cwc.googlegroups.com> <1170313815.362394.92400@a34g2000cwb.googlegroups.com> Message-ID: In <1170313815.362394.92400 at a34g2000cwb.googlegroups.com>, Paul McGuire wrote: > On Jan 31, 11:36 pm, "Paddy" wrote: >> On Feb 1, 2:42 am, krypto.wiz... at gmail.com wrote: >> >> > How to divide a number by 7 efficiently without using - or / operator. >> > We can use the bit operators. I was thinking about bit shift operator >> > but I don't know the correct answer. >> >>> int.__div__(14,2) >> 7 >> >> Not a minus or division operator in sight ;-) >> >> - Paddy. > > Now I'm confused - was the OP trying to divide by 7 or 2? I read it as divide by 7. And the `int.__div__()` Method limits this somehow -- a more polymorphic approach would be:: import operator operator.div(14, 7) :-) Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Fri Feb 16 05:23:23 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Feb 2007 11:23:23 +0100 Subject: Tkinter __call__ References: Message-ID: Gigs_ wrote: > I have tried but cant get it to work properly. It does work, but not the way you want it to. > I want to instead printit method to put __call__ and call it like that I don't understand. > Can someone help me, please? Try to explain what you want a bit more explicitly. Peter From S.Mientki-nospam at mailbox.kun.nl Fri Feb 9 08:06:37 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 09 Feb 2007 14:06:37 +0100 Subject: Newbie Question In-Reply-To: <1171025546.002411.213190@q2g2000cwa.googlegroups.com> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> Message-ID: <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> >> will explain the rest > > Delphi is a (dying) proprietary, MS-Windows-only[1] software relying > on a low-level language. > Well it may be dying, but for the moment it beats Python with a factor of 10, when it comes to user (the majority of PC users) friendly GUI ;-) cheers Stef Mientki From gagsl-py at yahoo.com.ar Mon Feb 5 17:03:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 19:03:51 -0300 Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" References: Message-ID: En Sat, 03 Feb 2007 07:35:22 -0300, Peter Otten <__peter__ at web.de> escribi?: > Gabriel Genellina wrote: > >> En Sat, 03 Feb 2007 06:12:33 -0300, Peter Otten <__peter__ at web.de> >> escribi?: >> >>> John Nagle wrote: >>> >>> import warnings >>> warnings.filterwarnings("ignore", message="Old style callback, use >>> cb_func(ok, store) instead") >> >> Or you can be more aggressive and filter out all DeprecationWarnings: >> warnings.simplefilter("ignore",DeprecationWarning) >> (same as using option -Wignore::DeprecationWarning on the python command >> line) > > The latter might be interesting for a cgi. I didn't mention it because I > didn't get it to work with my test case (importing sre) and Python's cgi > server. Trying again, I found that you must not quote the -W argument. > > #!/usr/local/bin/python2.5 -Wignore:The sre module is deprecated, please > import re. > >> From that follows that you can pass at most one commandline arg. > If you are using > > #!/usr/bin/env python2.5 > > python2.5 will be that single argument and no options are possible at > all. > What might be the reasons for such a seemingly arbitrary limitation? The shell parses that line, not Python, so you should look into its documentation. If one needs to disable the warning for all scripts, putting a call to warnings.simplefilter on sitecustomize.py would help (of course, if one is allowed to edit that file). -- Gabriel Genellina From Eric_Dexter at msn.com Thu Feb 8 07:00:26 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 8 Feb 2007 04:00:26 -0800 Subject: Calling J from Python In-Reply-To: <1170749117.582426.151770@p10g2000cwp.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> Message-ID: <1170936026.627390.212070@p10g2000cwp.googlegroups.com> I may have mistook the source code licence for the use licence.. I will look into a little further to see what it can do.. Looks like you are not allowed to redistribute k for profit. Some day I will look up letters a random in the search engine to see what I come up with. On Feb 6, 2:05 am, "Gosi" wrote: > On Feb 6, 3:04 am, "Eric_Dex... at msn.com" wrote: > > > On Feb 5, 8:48 am, "Gosi" wrote: > > > > It is quite easy to call J from Python > > > >http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... > > > There are a couple of issue that should be adressed. Am I going to > > jail if I write a program and then redistribute all the files required > > to run the program I write?? > > J is free for anyone to download and use. > > If someone is interested in putting you in jail it will not because > you distribute J or redistribute the J utilities. > > > The second is how do I use the j stuff > > without learning all that much about j. > > Just like Python then how much time you spend is uo to you. > > If you want to be good at it you may have to spend some time. > > You may also be just a casual user and dip into it now and again. > > There are lots of Demos, Labs and Help files besides all the > utilities. > > You can freely use the utilities and examples to create your own > application. > > You can write code in conventional style and not spend any time on the > advanced functionality. > > > I am just intrested in > > stealing graphics libraries and using what I have already written in > > python.. > > There are a number of graphics examples, utilities and demos you can > use in J and combine it with Python. > > The new grid classes in J are amazingly useful too. > > I am just starting to learn Python and I find it interesting to > combine it with J. > I know a few people who are doing so successfully. > > There are always some nicetise in any language that can be beneficial. > Combining them enhances both. > > http://groups.google.com/group/j-programminghttp://jsoftware.com/ From diffuser78 at gmail.com Wed Feb 21 12:26:58 2007 From: diffuser78 at gmail.com (DanielJohnson) Date: 21 Feb 2007 09:26:58 -0800 Subject: network simulator in Python ? Message-ID: <1172078818.126692.17510@k78g2000cwa.googlegroups.com> I was wondering if anyblody can suggest me a network simulator written in python in which I can add on my own code and extend its functionality. I am looking for a simulator which will simualte TCP, UDP, RTP and most networking protocol. The learning curve for ns2 and other simulator is too high for me at this time and thats why I am considering Python for it. Every help will be appreciated. Thanks From steven.bethard at gmail.com Thu Feb 15 16:00:08 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 15 Feb 2007 14:00:08 -0700 Subject: builtin set literal In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > Steven Bethard schrieb: >> Sch?le Daniel wrote: >>> it would be nice feature to have builtin literal for set type >>> maybe in P3 .. what about? >>> s = <1,2,3> >> >> In Python 3.0, this looks like:: >> >> s = {1,2,3} > > jepp, that looks not bad .. as in a mathe book. > the only disadvantage I see, that one may confuse it with a dict. Perhaps with a very cursory inspection. But the lack of any ':' characters is a pretty quick clue-in. STeVe From bearophileHUGS at lycos.com Fri Feb 16 03:25:27 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Feb 2007 00:25:27 -0800 Subject: builtin set literal In-Reply-To: <1171592265.316602.234820@s48g2000cws.googlegroups.com> References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> Message-ID: <1171612923.145381.220960@p10g2000cwp.googlegroups.com> Raymond Hettinger: > One of the reasons for the > rejection was that the small benefit of a literal notion was more than > offset by the attendant need for syntactical atrocities like those > listed above. {:} for empty dict and {} for empty set don't look too much atrocious to me. Note: the language Fortress, that in graphic modality uses unicode for its sources, has many collection literals (6 or more, you can see 3 of them at page 21): http://research.sun.com/projects/plrg/PLDITutorialSlides9Jun2006.pdf Bye, bearophile From ken.carlino at gmail.com Mon Feb 26 17:23:44 2007 From: ken.carlino at gmail.com (ken) Date: 26 Feb 2007 14:23:44 -0800 Subject: how can I create/set a 'file' reference in a attribute of a class Message-ID: <1172528624.153189.218200@8g2000cwh.googlegroups.com> Hi, i have a class: class LogHandler(ContentHandler): # a reference to a file open by some other function/class outputFile; def endElement(self, name): doSomething(self, "GroupResultList", self.text, outputFile) First, I get an error saying 'NameError: global name 'outputFile' is not defined' , how can I declare outputFile as a 'file reference'? Second , how can I set this file reference after I create the object 'LogHandler'? How can I do that? f = open('dummyFile.txt'); curHandler = LogHandler() curHandler.file = f From donmorrison at gmail.com Wed Feb 7 16:39:56 2007 From: donmorrison at gmail.com (Don Morrison) Date: Wed, 7 Feb 2007 13:39:56 -0800 Subject: string.find for case insensitive search In-Reply-To: References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: My apologies, I confused the built-in "str" with the module "string". I was reading from the section of the 2.4.4 docs called: 4.1.4 Deprecated string functions On 2/7/07, Robert Kern wrote: > Don Morrison wrote: > > lower() is also deprecated :) oh well > > The string method .lower() is not deprecated. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list > From franz.steinhaeusler at gmx.at Tue Feb 6 02:55:19 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 06 Feb 2007 08:55:19 +0100 Subject: Python compiled on Windows References: Message-ID: On Mon, 05 Feb 2007 12:17:48 +0100, hg wrote: >Duncan Booth wrote: > >> Franz Steinhaeusler wrote: >> >>> Hello, I'm only curious. >>> >>> Why is Python and most extension (also wxPython) not built using an >>> open source compiler like gcc or g++ on Windows? >>> >>> I'm always wondering, why Microsoft is still supported >>> in that way, using VC++ 7.1, if I'm not wrong. >>> >>> Ok, maybe the compiled assembler code could be better, but >>> this cannot be the reason, or? >>> >>> It would be wonderful (from the principle) if this could be possible. >>> From the standpoint of open source. >>> >>> What are your opinions? >> >> Practicality beats purity. >> >> To maximise the interoperability of Python with other software on the >> platform it makes sense to use the best supported compiler environment for >> the platform. @Duncan: Yes, you are not wrong! :) But this is not really open source in my opinion. Ok there is the VC++ toolkit for download. I'm just curious, if there ever had compiled on windows using that toolkit or even with gcc, and with gcc, whether there are problems or/and differences in speed and run time behaviour. > >Still, if one considers the many threads of people trying to get it to work >with the "free" version + other people that had to invest in VS mostly for >that (I did) / it might eventually be fair to reconsider. > >+ a dll is a dll > >hg @hg: that would be cool. From vinay_sajip at yahoo.co.uk Fri Feb 9 06:50:36 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 9 Feb 2007 03:50:36 -0800 Subject: TimedRotatingFileHandler() isn't rotating at midnight? In-Reply-To: References: Message-ID: <1171021836.812953.183150@m58g2000cwm.googlegroups.com> On 1 Feb, 05:32, Chris Shenton wrote: > I set this up 3 days ago and have not seen any of the logs I've > created this way being rotated. I expected them to rotate every > midnight. I'm calling the code that uses this logger many times, each > a separate run, if that matters. It might. I assume you have a long-running process which runs past midnight - that's the scenario that TimedRotatingFileHandler is meant for. Can you post a complete minimal example which shows the problem? > Am I doing something stupid? I can't find anything on google and don't > see anything in the code that would prevent rotating. > Rotating should happen when the logging process creates the handler before midnight and makes a logging call destined for that handler after midnight. Regards, Vinay Sajip From steven.bethard at gmail.com Wed Feb 28 17:09:02 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 28 Feb 2007 15:09:02 -0700 Subject: class declaration shortcut In-Reply-To: <1172699617.628947.118110@m58g2000cwm.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <7o-dndyPgY_db3jYnZ2dnUVZ_t2tnZ2d@comcast.com> <1172699617.628947.118110@m58g2000cwm.googlegroups.com> Message-ID: Luis M. Gonz?lez wrote: > On Feb 28, 6:21 pm, Steven Bethard wrote: >> How about something like:: >> >> class Person(Record): >> __slots__ = 'name', 'birthday', 'children' >> >> You can then use the class like:: >> >> person = Person('Steve', 'April 25', []) >> assert person.name == 'Steve' >> assert person.birthday == 'April 25' >> assert not person.children >> >> Is that what you were looking for? If so, the recipe for the Record >> class is here: >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 [snip] > Hmmm... not really. > The code above is supposed to be a shorter way of writing this: > > class Person: > def __init__(self, name, birthday, children): > self.name = name > self.birthday = birthday > self.children = children > > So the purpose of this question is finding a way to emulate this with > a single line and minimal typing. That __init__ is exactly what was generated in my example above. So you're mainly objecting to using two-lines? You can make it a one-liner by writing:: class Person(Record): __slots__ = 'name', 'birthday', 'children' > 1) How to get the variable name (in this case "Person") become the > name of the class without explicity indicating it. The only things that know about their own names are class statements (through metaclasses) so you can't really do it without a class statement of some sort (which means you'll have to use two lines). > 2) How to enter attribute names not enclosed between quotes. The only > way I can do it is by entering them as string literals. If you're really bothered by quotes, a pretty minimal modification to the recipe could generate the same code from: class Person(Record): slots = 'name birthday children' STeVe From paddy3118 at googlemail.com Sun Feb 25 16:00:26 2007 From: paddy3118 at googlemail.com (Paddy) Date: 25 Feb 2007 13:00:26 -0800 Subject: Nested Parameter Definitions In-Reply-To: <1172430363.360956.5300@q2g2000cwa.googlegroups.com> References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> <1172430363.360956.5300@q2g2000cwa.googlegroups.com> Message-ID: <1172437226.610212.54340@z35g2000cwz.googlegroups.com> On Feb 25, 7:06 pm, "Virgil Dupras" wrote: > On Feb 25, 1:00 pm, "Paddy" wrote: > > > > > I blogged on finding a new-to-me feature of Python, in that you are > > allowed to nnest parameter definitions: > > > >>> def x ((p0, p1), p2): > > > ... return p0,p1,p2 > > ...>>> x(('Does', 'this'), 'work') > > > ('Does', 'this', 'work') > > > Ruben commented that there was a poll on this features continued > > existence taken at PyCon and it could go. > > > Just as I found it, it could go > > > I wondered if those of you with some Python experience new of nested > > parameters and don't use them; or just forgot/don't know it is > > possible? > > > - Paddy. > > > Oh - the blog entry is athttp://paddy3118.blogspot.com/2007/02/pythons-function-nested-paramet... > > I didn't know about it either. Without the call example, I would have > had a hard time to try to figure out what these extra brackets are > for. For this reason, I think that an explicit unpack is more > readable, and thus better. The following example shows three possible ways of accessing nested data. i think , after now knowing how to use it, that the f0 function with nested parameters and its subsequent use is the most readable. Manual unpacking in the list comprehension for f1 is messy. No real reason for liking f0 over f2 except its shiny! >>> def f0 ((p0, p1), p2): ... pass ... >>> def f1 (p0, p1, p2): ... pass ... >>> def f2(p): ... (p0, p1), p2 = p ... >>> data = [ ((1, 2), 3), ((4, 5), 6)] >>> [ f0(*datum) for datum in data] [None, None] >>> [ f1(datum[0][0], datum[0][1], datum[1]) for datum in data] [None, None] >>> [ f2(datum) for datum in data] [None, None] >>> - Paddy. From kirk at nospam.jobsluder.net Sun Feb 25 22:01:29 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Mon, 26 Feb 2007 03:01:29 GMT Subject: RegExp performance? References: <45e145a0$0$90264$14726298@news.sunsite.dk> <1172400479.486951.300070@v33g2000cwv.googlegroups.com> <45e1d367$0$90273$14726298@news.sunsite.dk> Message-ID: In article <45e1d367$0$90273$14726298 at news.sunsite.dk>, Christian Sonne wrote: > Thanks to all of you for your replies - they have been most helpful, and > my program is now running at a reasonable pace... > > > I ended up using r"\b\d{9}[0-9X]\b" which seems to do the trick - if it > turns out to misbehave in further testing, I'll know where to turn :-P Anything with variable-length wildcard matching (*+?) is going to drag your performance down. There was an earlier thread on this very topic. Another stupid question is how are you planning on handling ISBNs formatted with hyphens for readability? In general I've found the following factors to be critical in getting good performance from re: 1: Reducing the number of times you call re.match or re.search. 2: Reducing the number of bytes that re has to search through. 3: Minimizing the use of wildcards in the expression. If you can pre-filter your input with string.find before running re.match you will improve performance quite a bit compared to running re expressions over all 10 pages. I played around a bit and attached some example code below searching over 21K of text for the ISBN number. testPrefilter() runs about 1/5th the execution time of line-by-line re calls or a single re call over a 21K string. Interestingly this ratio scales up to something as big as Mobey Dick. The searchLabels() functions below beats all the other functions by searching for "ISBN", or "International Book" and then using RE on the surrounding 500 bytes. You might also try searching for "Copyright" or "Library of Congress" since most modern books will have it all on the same page. A caveat here is that this only works if you can find a reasonably unique string at or near what you want to find with re. If you need to run re.search on every byte of the file anyway, this isn't going to help. --------------- timing test code --------------- #!/usr/bin/env python from timeit import Timer import re textString = """The text of a sample page using with an ISBN 10 number ISBN 0672328976 and some more text to compare.""" #add the full text of Mobey Dick to make the search functions #work for their bread. fileHandle= open("./mobey.txt") junkText = fileHandle.readlines() junkText.append(textString) textString=''.join(junkText) #print textString #compile the regex isbn10Re = re.compile(r"\b\d{9}[0-9X]\b") def testPrefilter(): """Work through a pre-loaded array running re only on lines containing ISBN""" for line in junkText: #search for 'ISBN" if (line.find('ISBN') > -1): thisMatch = isbn10Re.search(line) if thisMatch: return thisMatch.group(0) def testNofilter(): """Run re.search on every line.""" for line in junkText: #seaching using RE thisMatch = isbn10Re.search(line) if thisMatch: return thisMatch.group(0) def testFullre(): """Run re.search on a long text string.""" thisMatch = isbn10Re.search(textString) if thisMatch: return thisMatch.group(0) def searchLabels(): #identify some text that might be near an ISBN number. isbnLabels=["ISBN", "International Book"] #use the fast string.find method to locate those #labels in the text isbnIndexes = [textString.find(x) for x in isbnLabels] #exclude labels not found in the text. isbnIndexes = [y for y in isbnIndexes if y > -1] #run re.search on a 500 character string around the text label. for x in isbnIndexes: thisMatch=isbn10Re.search(textString[x-250:x+250]) return thisMatch.group(0) #print searchLabels() #print testPrefilter() #print testNofilter() t = Timer("testNofilter()","from __main__ import testNofilter") print t.timeit(100) u = Timer("testPrefilter()","from __main__ import testPrefilter") print u.timeit(100) v = Timer("testFullre()","from __main__ import testFullre") print v.timeit(100) w = Timer("searchLabels()", "from __main__ import searchLabels") print w.timeit(100) From ptmcg at austin.rr.com Thu Feb 1 08:57:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 1 Feb 2007 05:57:27 -0800 Subject: Help me with this!!! In-Reply-To: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> References: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> Message-ID: <1170338247.908255.156130@q2g2000cwa.googlegroups.com> On Feb 1, 4:21 am, "TOXiC" wrote: > Hi all, I've this code: > > regex = re.compile(r"(?si)(\x8B\xF0\x85\xF6)(?P.*) > (\xC6\x44\x24)",re.IGNORECASE) > file = open(fileName, "rb") > for line in file: > if (match): > print line > file.close() > > It search a text inside that hex value. > It works perfecly on a txt file but if I open a binary file (.exe,.bin > ecc...) with the same value it wont work, why? > Please help! Where do you assign the value of 'match'? Perhaps you are missing a line such as "match=regex.match(line)" or "match=regex.search(line)"? Perhaps this is why Peter Otten says that this code can't possibly be the code that works for text files? What is the significance of "for line in file" when file is opened in binary mode? Are EOLs properly interpreted in binary mode? ('file' is not the best variable name, by the way, as it masks Python's built- in file. How about "file_", or "inputfile", or "fileToBeSearched"?) -- Paul From ullrich at math.okstate.edu Sat Feb 24 06:16:50 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sat, 24 Feb 2007 05:16:50 -0600 Subject: CSV(???) References: Message-ID: On Fri, 23 Feb 2007 11:43:24 +0000 (UTC), Philipp Pagel wrote: >David C. Ullrich wrote: >> Is there a csvlib out there somewhere? > >How about csv in the standard library? > >> (Um: Believe it or not I'm _still_ using >> python 1.5.7. > >I have no idea if csv was part of the standard library backin those >days... Nope. >But even if not: either upgrade to something less outdated Thanks. Actually, for reasons I could explain if you really wanted to know, going to 2.x would actually cost me some money. Since I'm not getting paid for this... >or see if you >can get todays csv to work with the oldtimer. > >cu > Philipp ************************ David C. Ullrich From ahmerhussain at gmail.com Sun Feb 18 10:29:40 2007 From: ahmerhussain at gmail.com (Ahmer) Date: 18 Feb 2007 07:29:40 -0800 Subject: PyDev on Mac In-Reply-To: <53qlrtF1tm3brU1@mid.uni-berlin.de> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> Message-ID: <1171812580.477975.37060@t69g2000cwt.googlegroups.com> On Feb 18, 4:50 am, "Diez B. Roggisch" wrote: > Ahmer schrieb: > > > I've been trying to set up PyDev on my new MacBook Pro, but i have not > > had an success. > > > Could you please help! > > Just wait until my crystal ball comes back from the cleaners, and I will > start looking at your problem. > > As you can lay back and do nothing while that happens, I suggest you > take this highly entertaining read: > > http://www.catb.org/~esr/faqs/smart-questions.html > > Diez The main problem seems to be locating Python. Even though I installed the official python for mac, it says the interpreter is invalid. So I tried jPython, no succes on that either. It always tells me I am using an invlaid interpreter. From bignose+hates-spam at benfinney.id.au Thu Feb 15 20:50:43 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Feb 2007 12:50:43 +1100 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: <874ppm7tvw.fsf@benfinney.id.au> "Edward K Ream" writes: > > Isn't the very concept of major releases (1.x, 2.x, 3.x) that they > > *can* be not backwards-compatible with previous releases? > > Not at all. In the context of the question, this answer seems to say that a major release *must* be backwards-compatible (i.e. "can [may] not be not backwards-compatible"). Is that what you intend to say? If so, I disagree strongly. I assert that a major release *may* be backwards-incompatible, in well-defined ways. That's the only way to get rid of some kinds of cruft. So long as it's done in a well-documented way, with a change in major version number, it's a reasonable way (probably the *only* reasonable way) to remove particular kinds of cruft from any application -- even if that application is a programming language. -- \ "To stay young requires unceasing cultivation of the ability to | `\ unlearn old falsehoods." -- Robert Anson Heinlein | _o__) | Ben Finney From clajo04 at mac.com Fri Feb 9 10:20:44 2007 From: clajo04 at mac.com (John Clark) Date: Fri, 9 Feb 2007 10:20:44 -0500 Subject: NYC Python User Group Meeting Message-ID: <009501c74c5d$e04890b0$fefea8c0@haengma> Greetings! The next New York City Python Users Group meeting is this Tuesday, Feb. 13th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John From eopadoan at altavix.com Fri Feb 2 06:03:15 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 2 Feb 2007 09:03:15 -0200 Subject: Inconsistent list/pointer problem In-Reply-To: References: Message-ID: > def myFunc(listA): > listB = listA > work on & modify listB > return(listB) def my_func(listA): listB = listA[:] #work on & modify listB return listB Attribution makes the name t the left 'point' to the result of the expression at the right. In your myFunc the expersion at the right is the name listA, at it willl eval to the list that this references. So you will end with to references. In my my_func, the expression at the right is a slicing of the list, from begin to end (listA[:]). Slicing returns a new list, in this example, with the same items of the original list. So you end with two lists, as you wanted. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com From wolf_tracks at invalid.com Wed Feb 7 17:51:42 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 07 Feb 2007 14:51:42 -0800 Subject: Re-installing Numeric and PIL Files Message-ID: For some reason Python 2.2.4 cannot find the Numeric module. It's been suggested that I should re-install the Numeric file. How do that? Also the PIL. The three install files are: python-2.4.4.msi PIL-1.1.5.win32-py2.4.exe Numeric-24.2.win32-py2.4.exe Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet 'I think it not improbable that man, like the grub that prepares a chamber for the winged thing it has never seen but is to be, may have... destinies that he does not understand." -- Oliver Wendell Holmes -- Web Page: From kirk at nospam.jobsluder.net Wed Feb 21 14:40:57 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Wed, 21 Feb 2007 19:40:57 GMT Subject: Regex Speed References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172049029.217002.55560@v33g2000cwv.googlegroups.com> Message-ID: In article <1172049029.217002.55560 at v33g2000cwv.googlegroups.com>, "John Machin" wrote: > Getting back to the "It would be nice ..." bit: yes, it would be nice > to have even more smarts in re, but who's going to do it? It's not a > "rainy Sunday afternoon" job :-) Well, just as an idea, there is a portable C library for this at http://laurikari.net/tre/ released under LGPL. If one is willing to give up PCRE extensions for speed, it might be worth the work to wrap this library using SWIG. The cheap way in terms of programmer time is to pipe out to grep or awk on this one. From bignose+hates-spam at benfinney.id.au Sun Feb 4 17:03:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 05 Feb 2007 09:03:39 +1100 Subject: How can I access data from MS Access? References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> <45c4bee4$0$453$426a74cc@news.free.fr> <1170522973.012926.252510@k78g2000cwa.googlegroups.com> <45c649ed$0$5159$426a34cc@news.free.fr> Message-ID: <87bqk9shqc.fsf@benfinney.id.au> Bruno Desthuilliers writes: > I sadly admit that I was wrong. "Doesn't seem to work" is effectivly > even more useless than "doesn't work". I give up. +1 QOTW -- \ "You can't have everything; where would you put it?" -- Steven | `\ Wright | _o__) | Ben Finney From steve at holdenweb.com Mon Feb 5 08:31:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Feb 2007 13:31:51 +0000 Subject: Why less emphasis on private data? In-Reply-To: <1168248244.134804.138050@51g2000cwl.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> <1168189375.843789.306180@51g2000cwl.googlegroups.com> <7xps9q19wf.fsf@ruckus.brouhaha.com> <1168248244.134804.138050@51g2000cwl.googlegroups.com> Message-ID: <45C731C7.8020803@holdenweb.com> Paul Boddie wrote: > Paul Rubin wrote: >> Right, the problem is if those methods start changing the "private" >> variable. I should have been more explicit about that. >> >> class A: >> def __init__(self): >> self.__x = 3 >> def foo(self): >> return self.__x >> >> class B(A): pass >> >> class A(B): >> def bar(self): >> self.__x = 5 # clobbers private variable of earlier class named A > > Has this ever been reported as a bug in Python? I could imagine more > sophisticated "name mangling": something to do with the identity of the > class might be sufficient, although that would make the tolerated > "subversive" access to private attributes rather difficult. > > Paul > It would also force the mangling to take place at run-time, which would probably affect efficiently pretty adversely (thinks: should really check that mangling is a static mechanism before posting this). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From grante at visi.com Thu Feb 8 11:58:39 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Feb 2007 16:58:39 -0000 Subject: help on packet format for tcp/ip programming References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> <12sl6tuhkla8ob2@corp.supernews.com> <1170944844.977214.57350@s48g2000cws.googlegroups.com> <530s0uF1q8kfsU1@mid.uni-berlin.de> Message-ID: <12smllvh730lp9c@corp.supernews.com> On 2007-02-08, Diez B. Roggisch wrote: >>>> struct module pack and unpack will only work for fixed size buffer : >>>> pack('>1024sIL', buffer, count. offset) but the buffer size can vary >>>> from one packet to the next :-( >>> >>> Oh for Pete's sake... >>> >>> struct.pack('>%dsIL' % len(buffer), buffer, count, offset) >> >> >> that is great but how does one unpack on the other side? > > By peeking into the header, determining the number of bytes necessary? Better yet, use a protocol that's not brain-dead: send the buffer size _before_ you send the buffer. > But why do you need this anyway - if you know that you will > have python on both ends, use Pyro or xmlrpc. -- Grant Edwards grante Yow! A dwarf is passing at out somewhere in Detroit! visi.com From pDOTpagel at gsf.de Fri Feb 9 07:33:59 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Fri, 9 Feb 2007 12:33:59 +0000 (UTC) Subject: os.popen and broken pipes References: Message-ID: Antoon Pardon wrote: > On 2007-02-09, Philipp Pagel wrote: > > for filename in file_list: > > file = os.popen('uncompress -c '+filename, 'r') > > do_something(file) > > file.close() > > > > This works fine for some files but results in > > > > 'write error onstdout: Broken pipe' > As far as I can tell, your do_something doesn't consume the entire file. > So you close the file prematurly, which results in the uncompress/zcat > program trying to write to a pipe that is closed on the otherside, > giving you the above message. You are right: some of the files do not fulfill certain critereia causing so_somehting() to return before the entire file is processed. Thanks! cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From __peter__ at web.de Sat Feb 3 04:12:33 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 10:12:33 +0100 Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" References: Message-ID: John Nagle wrote: > How do I suppress "DeprecationWarning: Old style callback, use > cb_func(ok, > store) instead". A library is triggering this message, the library is > being fixed, but I need to make the message disappear from the output of a > CGI program. import warnings warnings.filterwarnings("ignore", message="Old style callback, use cb_func(ok, store) instead") Peter From bignose+hates-spam at benfinney.id.au Thu Feb 8 16:03:29 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 09 Feb 2007 08:03:29 +1100 Subject: doctests for interactive functions References: <45CB77E3.3040108@cc.umanitoba.ca> Message-ID: <87veic9xb2.fsf@benfinney.id.au> Brian van den Broek writes: > Since the classes are for getting input interactively, a > straightforward use of doctest is not going to work. (The tests > won't run automatically.) I've come up with a way to make it work, > but I would like to know from more experienced people if there are > better ways that I am overlooking. One suggestion I can give is to decouple the task of "get input from the user" and "validate this value against particular criteria". The former should be so simple and *stupid* in its implementation that very little can go wrong. The latter should be each of your validation classes, or some re-implementation of them, that is non-interactive and therefore easy to test. Then, the application simply uses these building blocks (that are now well-tested and reliable) to do what it does: get input, then validate that input, and possible ask for input again. -- \ "How many people here have telekenetic powers? Raise my hand." | `\ -- Emo Philips | _o__) | Ben Finney From greg at cosc.canterbury.ac.nz Thu Feb 1 03:02:46 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 01 Feb 2007 21:02:46 +1300 Subject: OT: Variant name spellings (Re: how to "free" an object/var ?) In-Reply-To: References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> <1170264406.588032.116550@s48g2000cws.googlegroups.com> Message-ID: <52dl94F1nm406U1@mid.individual.net> Steven D'Aprano wrote: > > Ste_ph_en??? I knew someone once who referred to the two ways of spelling Ste{v,ph}en as the "dry way" and the "wet way"... > It's not like I spell my name with four M's and a silent Q like the famous > author Farles Wickens *wink* Or Mr. Luxury-Yacht, which as we all know is pronounced Throatwarbler-Mangrove. With a silent hyphen. -- Greg Psmith (pronounced You-ing) From deets at nospam.web.de Wed Feb 14 11:27:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Feb 2007 17:27:07 +0100 Subject: How much memory used by a name References: Message-ID: <53grirF1s3cq0U1@mid.uni-berlin.de> Bernard Lebel wrote: > Hello, > > I would like to know if there is a way to know how much memory (bytes, > kilobytes, megabytes, etc) a name is using. > > More specifically, I have this list of strings that I want to write to > a file as lines. > This list grows througout the script execution, and toward the end, > the file is written. > > However I would like to know how much memory, before writing to the > file, is this list using. Is it possible at all? How about summing up the individual string lengths? total = sum(len(s) for s in my_list) Diez From msj at infoserv.dk Mon Feb 26 09:54:04 2007 From: msj at infoserv.dk (msj at infoserv.dk) Date: 26 Feb 2007 06:54:04 -0800 Subject: Python / Socket speed Message-ID: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> Seems like sockets are about 6 times faster on OpenSUSE than on Windows XP in Python. http://pyfanatic.blogspot.com/2007/02/socket-performance.html Is this related to Python or the OS? /MSkou From steve at REMOVE.THIS.cybersource.com.au Sun Feb 11 05:25:01 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Feb 2007 21:25:01 +1100 Subject: Regular Expressions References: Message-ID: On Sun, 11 Feb 2007 07:05:30 +0000, Steve Holden wrote: > Geoff Hill wrote: >> What's the way to go about learning Python's regular expressions? I feel >> like such an idiot - being so strong in a programming language but knowing >> nothing about RE. >> >> > In fact that's a pretty smart stance. That's a little harsh -- regexes have their place, together with pointer arithmetic, bit manipulations, reverse polish notation and goto. The problem is when people use them inappropriately e.g. using a regex when a simple string.find will do. > A quote attributed variously to > Tim Peters and Jamie Zawinski says "Some people, when confronted with a > problem, think 'I know, I'll use regular expressions.' Now they have two > problems." I believe that is correctly attributed to Jamie Zawinski. -- Steven From larry.bates at websafe.com Thu Feb 1 14:10:16 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Feb 2007 13:10:16 -0600 Subject: how to make a python windows service know it's own identity In-Reply-To: <1170264160.124454.6270@j27g2000cwj.googlegroups.com> References: <1170264160.124454.6270@j27g2000cwj.googlegroups.com> Message-ID: <45C23B18.5050000@websafe.com> Chris Curvey wrote: > Hi all, > > I have used the win32com libraries to set up a service called > MyService under Windows. So far, so good. Now I need to run multiple > copies of the service on the same machine. I also have that working. > For monitoring and logging, I'd like each instance of the service to > know it's own identity (MyService1, MyService2, etc.) > > But I can't quite seem to grasp how to do this. In the code below, > the command line parameter "-i" gives the service an identity, but how > do I get the service to understand it's identity when it is started? > > Many thanks! > > > class MyService(win32serviceutil.ServiceFramework): > """NT Service.""" > > _svc_name_ = "MyService" > _svc_display_name_ = "My Service" > > _id_ = '' > > def SvcDoRun(self): > provider = MyServiceClass(identifier=self._id_) > provider.start() > > # now, block until our event is set... > win32event.WaitForSingleObject(self.stop_event, > win32event.INFINITE) > > # __init__ and SvcStop snipped > > > ########################################################################### > if __name__ == '__main__': > import optparse > parser = optparse.OptionParser() > parser.add_option("-i", "--identifier", dest="identifier") > (opts, args) = parser.parse_args() > if opts.number is not None: > MyService._svc_name_ += opts.identifier > MyService._svc_display_name_ += opts.identifier > MyService._provider_id_ = opts.identifier > > win32serviceutil.HandleCommandLine(MyService, > customInstallOptions="i:") > What is your use case for this? Why not make a single server process multiple providers (store them in a list or other container)? -Larry Bates From mail at microcorp.co.za Mon Feb 19 01:04:33 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 19 Feb 2007 08:04:33 +0200 Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com><14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl><45d626f5$0$19811$426a74cc@news.free.fr><53nt2aF1sn581U1@mid.uni-berlin.de> <45d85388$0$29060$426a74cc@news.free.fr> Message-ID: <002f01c753eb$d45c7ec0$03000080@hendrik> "Bruno Desthuilliers" wrote: >Stef Mientki a ?crit : >(snip) >> I've been using Python for just 2 months, and didn't try any graphical >> design, > >So how can you comment on GUI programming with Python ? I think we have a language problem here (no pun intended) When Stef says "Gui Programming" he means using something like Delphi or Boa to do the Graphical Layout, while on this group it normally means writing the python code to make your own windows etc., using Tkinter or better... There is no doubt that the first approach gets you going faster, albeit true that you have more flexibility with the second. The learning curves are also different, the first approach feeling less painful, as you seem to make progress from the start, and you don't have to worry about questions like : "whats a frame/toplevel/mainloop/etc.?" So from Stef's perspective he is right when he claims that Python's "Gui Programming" is poor - in the standard library it is non existent, as there are no Delphi-, Glade- or Boa-like tools available. And one can argue that something like Boa or the WX.. packages are not Python, as they are not included in the standard library... - Hendrik From justin.mailinglists at gmail.com Thu Feb 15 03:39:13 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 15 Feb 2007 00:39:13 -0800 Subject: how to store and still search special characters in Python and MySql In-Reply-To: <1171254409.379444.183000@h3g2000cwc.googlegroups.com> References: <1171254409.379444.183000@h3g2000cwc.googlegroups.com> Message-ID: <1171528753.476765.316690@h3g2000cwc.googlegroups.com> On Feb 12, 12:26 pm, "ronrsr" wrote: > I have an MySQL database called zingers. The structure is: > > I am having trouble storing text, as typed in latter two fields. > Special characters and punctuation all seem not to be stored and > retrieved correctly. > > Special apostrophes and single quotes from Microsoft Word are causing > a > special problem, even though I have ''ed all 's > > > Input and output is through a browser. > > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position > 95: ordinal not in range(128) > args = ('ascii', "update zingers set keywords = > 'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal > not > in range(128)') > encoding = 'ascii' > end = 96 > object = "update zingers set keywords = 'a;Action;b;Religi... > \n > \n \n ' where zid = 422" > reason = 'ordinal not in range(128)' > start = 95 > > the characters I am trying to add are startquote and endquote copied > and pasted from Microsoft Word. > http://tinyurl.com/2g9364 as nobody has replied yet...perhaps the above link may help From danilo.horta at gmail.com Fri Feb 9 05:51:53 2007 From: danilo.horta at gmail.com (Horta) Date: 9 Feb 2007 02:51:53 -0800 Subject: A little more advanced for loop Message-ID: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> Hi folks, Suppose I have to loop over 3 lists being the same size at the same time and order. How can I do that without using the range() function or whatever indexing? Example using range: a = ['aaa', 'aaaa'] b = ['bb', 'bbbb'] c = ['c', 'cccc'] for i in range(len(a)): # using a[i], b[i], and c[i] I'm sure there's a elegant way to do that... Thanks in advance. From skpeterson at nospam.please.ucdavis.edu Mon Feb 12 00:38:29 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 21:38:29 -0800 Subject: string.replace non-ascii characters References: Message-ID: Steven Bethard on Sun, 11 Feb 2007 22:23:59 -0700 didst step forth and proclaim thus: > Samuel Karl Peterson wrote: > > Greetings Pythonistas. I have recently discovered a strange anomoly > > with string.replace. It seemingly, randomly does not deal with > > characters of ordinal value > 127. I ran into this problem while > > downloading auction web pages from ebay and trying to replace the > > "\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from > > urllib2. Yet today, all is fine, no problems whatsoever. Sadly, I > > did not save the exact error message, but I believe it was a > > ValueError thrown on string.replace and the message was something to > > the effect "character value not within range(128). > > Was it something like this? > > >>> u'\xa0'.replace('\xa0', '') > Traceback (most recent call last): > File "", line 1, in > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position > 0: ordinal not in range(128) Yeah that looks like exactly what was happening, thank you. I wonder why I had a unicode string though. I thought urllib2 always spat out a plain string. Oh well. u'\xa0'.encode('latin-1').replace('\xa0', " ") Horray. -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From Shawn at Milochik.com Sat Feb 10 13:03:02 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Sat, 10 Feb 2007 13:03:02 -0500 Subject: Hacking in python In-Reply-To: References: Message-ID: <2dc0c81b0702101003i4824ad24lb42b01e316760327@mail.gmail.com> On 2/10/07, Tina I wrote: > zefciu wrote: > > enes naci wrote: > >> i would like to know about hacking in python too whether its illegal or > >> not is not the point and anyway it doesn't mean i'm gong to use it. > >> > > > > If you mean hacking as modyfying the code of interpreter of libraries - > > it is perfectly legal, as Python is Open Source. > > > > If you mean hacking as cracking into computer systems, then what's the > > difference if it's with Python or anything else. > > > > If you mean hacking as gaining excellency in programming - then why > > should it be? > > > > Greets > > zefciu > It's really sad. I saw this poor schmuck on "Want to be a millionaire" > once. His second question was "What is a hacker?" I don't remember all > of the alternatives but two of them was "A computer programmer" and > "Someone illegally using a computer". > He answered 'computer programmer'... guess what was the 'correct one'. > > I guess he was lucky though... it could have been the one million question. > -- > http://mail.python.org/mailman/listinfo/python-list > That's truly horrible. I would sue. From inq1ltd at verizon.net Tue Feb 13 19:42:33 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Tue, 13 Feb 2007 19:42:33 -0500 Subject: Tkinter: how; newbie In-Reply-To: References: Message-ID: <200702131942.33786.inq1ltd@verizon.net> On Tuesday 13 February 2007 18:02, Gigs_ wrote: > can someone explain me this code? > > from Tkinter import * > > root = Tk() > > def callback(event): > print "clicked at", event.x, event.y > > frame = Frame(root, width=100, height=100) > frame.bind("", callback) > frame.pack() > > root.mainloop() > if you live on longititude 32, wrere is that? If you live on latitude 40 and longitiude 32 I can find that location. Your mouse is pointing to x, and y, which is simply a location on the screen. > > well, my problem is at frame.bind(",Button-1>", > callback) callback function prints event.x and > event.y. How the callback function get this two > number when it has only one argument (event) > Why its not: def callback(x, y): print x, y > > Im new to gui programming > > Sorry for bad eng! > > Thanks for replay! From horpner at yahoo.com Thu Feb 15 14:35:25 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Feb 2007 20:35:25 +0100 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: On 2007-02-15, Gabriel Genellina wrote: > En Thu, 15 Feb 2007 13:37:19 -0300, Neil Cerutti > escribi?: > >> On 2007-02-15, Gabriel Genellina wrote: >>> En Wed, 14 Feb 2007 10:41:53 -0300, Neil Cerutti >>> escribi?: >>>> So the effect is that mutual recursion isn't actually any >>>> harder. >>> >>> But some kind of language support is required in this case. At >>> least I don't know how to handle mutual recursion (apart from >>> inlining one function inside the other...). But I'm certainly >>> not a "program transformation guru" (neither a novice!) so I >>> would not be surprised if someone says it can be done... >> >> What happens (using the model of an imaginary virtual machine, >> perhaps like the Python interpreter) is the following. >> >> A normal function call pushes a call-frame onto a stack. The >> call-frame contains information necessary for returning from the >> function, and usually a place to store its local variables and >> parameters. >> >> A function called in "tail" position simply overwrites the >> current call-frame with the new one instead of pushing it onto >> the stack. > > This is the "kind of language support" menctioned. For tail > recursion you don't require that support. I'm not sure what you mean. The above support is enough for tail recursion, mutual recursion, and any other tail call to be "optimized." -- Neil Cerutti From bdesth.quelquechose at free.quelquepart.fr Wed Feb 14 19:08:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 15 Feb 2007 01:08:01 +0100 Subject: How much memory used by a name In-Reply-To: References: <45d36eea$0$24957$426a74cc@news.free.fr> Message-ID: <45d39d03$0$19671$426a74cc@news.free.fr> Bernard Lebel a ?crit : > Diez: thanks, I will try that. However isn't sum() returning an > integer that here would represent the number of elements? Nope, it will return the sum of the length of the lines in the list. The long way to write it is: total = 0 for line in thelist: total += len(line) > > Bruno: good question. We're talking about text files that can have > 300,000 lines, if not more. Currently, the way I have coded the file > writing, every line calls for a write() to the file object, Seems sensible so far... > The file is on the network. Mmm... Let's guess : it's taking too much time ?-) > This is taking a long time, (You know what ? I cheated) > and I'm looking for ways to speed up this > process. I though that keeping the list in memory and dropping to the > file at the very end could be a possible approach. OTOH, if the list grows too big, you may end up swapping (ok, it would need a very huge list). A "mixed" solution may be to wrap the file in a "buffered" writer that only perform a real write when it's full. This would avoid effective i/o on each line while keeping memory usage reasonable. Another one would be async I/O, but I don't know if and how it could be done in Python (never had to manage such a problem myself). My 2 cents... From miki.tebeka at gmail.com Fri Feb 2 09:16:50 2007 From: miki.tebeka at gmail.com (Miki) Date: 2 Feb 2007 06:16:50 -0800 Subject: How do I print out in the standard output coloured lines In-Reply-To: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> Message-ID: <1170425810.547515.270170@h3g2000cwc.googlegroups.com> Hello Carlos, > I'm interested in printing out coloured lines of my application and > I don't know what to use. Can anybody give me an idea?? I use the following script: #!/usr/bin/env python '''Print message using ANSI terminal codes''' __author__ = "Miki Tebeka " # $Id: ansiprint 1229 2005-05-16 05:50:22Z mikit $ # ===================================================== # Copyright (c) Miki Tebeka # This file is under the GNU Public License (GPL), see # http://www.gnu.org/copyleft/gpl.html for more details # ===================================================== from sys import stdout, stderr # Format bright = 1 dim = 2 underline = 4 blink = 5 reverse = 7 hidden = 8 # Forground black = 30 red = 31 green = 32 yellow = 33 blue = 34 magenta = 35 cyan = 36 white = 37 # Background on_black = 40 on_red = 41 on_green = 42 on_yellow = 43 on_blue = 44 on_magenta = 45 on_cyan = 46 on_white = 47 def ansiformat(msg, *args): '''Format msg according to args. See http://www.termsys.demon.co.uk/vtansi.htm for more details/ ''' return "\033[%sm%s\033[0m" % (";".join(["%s" % f for f in args]), msg) def ansiprint(msg, *args, **kw): '''Print formatted message. Should work on ANSI compatible terminal. ''' if kw.get("stderr", 0): outfo = stderr else: outfo = stdout outfo.write(ansiformat(msg, *args)) outfo.flush() if __name__ == "__main__": from sys import argv, exit from os.path import basename h = { "bright" : bright, "dim" : dim, "underline" : underline, "blink" : blink, "reverse" : reverse, "hidden" : hidden, "black" : black, "red" : red, "green" : green, "yellow" : yellow, "blue" : blue, "magenta" : magenta, "cyan" : cyan, "white" : white, "on_black" : on_black, "on_red" : on_red, "on_green" : on_green, "on_yellow" : on_yellow, "on_blue" : on_blue, "on_magenta" : on_magenta, "on_cyan" : on_cyan, "on_white" : on_white } eg = "e.g. ansiprint hello red on_green underline -> %s" % \ ansiformat("hello", red, on_green, underline) # Check command line if len(argv) < 2: print >> stderr, "usage: %s message [format ...]" % basename(argv[0]) print >> stderr, eg exit(1) for i in argv[2:]: if i not in h: ansiprint("%s: Unknown format\n" % i, red, bright, stderr=True) print >> stderr, "Formats can be:", msg = ", ".join([ansiformat(f, h[f]) for f in h.keys()]) print msg print >> stderr, eg exit(1) # Print ansiprint(argv[1], *[h[i] for i in argv[2:]]) print # vim: ft=python Hope you find it useful. -- Miki http://pythonwise.blogspot.com From gilbeert at gmail.com Thu Feb 1 08:13:05 2007 From: gilbeert at gmail.com (gilbeert at gmail.com) Date: 1 Feb 2007 05:13:05 -0800 Subject: newbie question: nested archives and zipfile Message-ID: <1170335585.254930.210140@k78g2000cwa.googlegroups.com> I sorry, but I'm not very familiar with Python. Please, help to solve my problem with reading file from "nested" zip archive. There is an ear_file.ear and inside this file there is a war_file.war and inside this file there is a jar_file.jar. I have to read content of a file (my_file.txt) from inside a jar_file.jar: ear_file.ear > war_file.war > jar_file.jar > my_file.txt Is it possible to directly read my_file.txt from inside this kind of nested archive? Please, give an example how to do that. Do I have to open ear_file.ear, read war_file.war, write it to file and then open writed war_file.war, read jar_file.jar, write it to file and then open wreted jar_file.jar and read my_file.txt?? Thanks in advance! From http Mon Feb 12 02:09:39 2007 From: http (Paul Rubin) Date: 11 Feb 2007 23:09:39 -0800 Subject: randomly generate n of each of two types References: <3YOzh.1133$yg7.205@trnddc08> <7x3b5bzyl3.fsf@ruckus.brouhaha.com> Message-ID: <7x1wkvg8cs.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Ah, I see what you mean... you're reminding me that the Original Poster > seems to want a biased set of almost-but-not-quite-randomly chosen > values, so that random_values(1) must return one each of True and False > and never True, True or False, False. I thought that was what was specified, "generate n of each of two types". So if n=10 and the two types are true and false, generate 10 trues and 10 falses. random.shuffle is the most direct way to do it but I gave another approach that doesn't use auxiliary space except for a few variables. From jstroud at mbi.ucla.edu Mon Feb 26 21:58:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 26 Feb 2007 18:58:42 -0800 Subject: Probably somewhat silly newbie question In-Reply-To: References: <1172544257.686173.180650@p10g2000cwp.googlegroups.com> Message-ID: James Stroud wrote: > elgrandchignon at gmail.com wrote: > >> Hi all-- >> >> Trying to learn Python w/little more than hobbyist (bordering on pro/ >> am, I guess) Perl as a background. >> >> My problem is, I have a list of departments, in this instance, things >> like "Cheese", "Bakery", et al. (I work @ a co-op health food store). >> I've populated a list, 'depts', w/these, so that their indexes match >> our internal indexing (which skips a few #'s). >> >> Now, I'd like to simply generate-- and be able to refer to-- a bunch >> of other lists-sets (for subdepartments) by iterating through this >> list, and naming each of these subdepartment lists "categoryx", where >> x is the index # from the master 'depts' list. And then be able to >> populate & refer to these lists by accessing their variable-including >> name. >> >> In Perl, it's a fairly trivial matter to use a string variable in >> naming some other kind of variable-- not sure about Python though. My >> initial, very weak stab at it (don't laugh!) went something like this: >> >> for i in range(len(depts)): >> if depts[i]: >> categorylistdeptname = 'category' + str(i) >> categorylistdeptname = [] >> >> Not sure what that wound up doing, but it sure didn't seem to work. > > > First, your are rebinding categorylistdeptname in the loop every time. > > But you probably want a dict (in python 2.4 or later): > > > deptdict = dict((dept, []) for dept in depts)) > > And this gets what you want, believe it or not. > > Now you can populate each list: > > deptdict['Bakery'].append("Donuts") > deptdict['Bulk'].extend(["Granola", "Rasins"]) > > And work witht the lists by name: > > for item in deptdict['Bulk']: > print item > # prints "Granola", "Rasins", etc. > > > James > Typo, too many parens. Should be: deptdict = dict((dept, []) for dept in depts) From adonis at REMOVETHISearthlink.net Fri Feb 16 14:15:32 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Fri, 16 Feb 2007 19:15:32 GMT Subject: Reg Google Web Toolkit and Python In-Reply-To: References: Message-ID: Shadab Sayani wrote: > Hi , > We have a project where I need to read files store > them in database in the backend.We have done this in > python.Now we decided to use Ajax technique for user > interface.For that we found that GWT is one of the > best toolkits.Now I got a doubt can I interface GWT > with python. > Thanks , > Shadab. > > Send instant messages to your online friends http://uk.messenger.yahoo.com I have not gone into much detail with GWT (you can look into the Python rendition of GWT called PyJamas), but it should be talking to a web server with the use of XMLHTTPRequest. So this should the case, then you can simply access your resources dynamically. e.g. web server: http://example.com/ resource: http://example.com/someJSONFormattedData An AJAX application with its XMLHTTPRequest it will perform an HTTP GET on /someJSONFormattedData, which depending on your web application server could either be static or dynamic data. Then upon reception of the data, simply parse it and update a section or sections of your AJAX application (unless GWT has mechanisms to handle such things for you). Hope this helps. Adonis From bdesth.quelquechose at free.quelquepart.fr Mon Feb 26 16:10:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 26 Feb 2007 22:10:28 +0100 Subject: Add images together In-Reply-To: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> Message-ID: <45e34508$0$18699$426a74cc@news.free.fr> iceman a ?crit : > Hi, > > I am trying to add together a number of images: > > im = image1 + image2 + ... > > How can i do this? > > I have tried to add two image instances > together but i get the following error: > TypeError: unsupported operand type(s) for +: 'instance' and > 'instance' > 1/ Python has no builtin "image" type. 2/ I don't know any unambiguous mathematical definition of "image addition" 3/ Whatever "image" object you are using, it comes from a package. Please read the package documentation. From rkmr.em at gmail.com Wed Feb 21 11:23:21 2007 From: rkmr.em at gmail.com (mark) Date: Wed, 21 Feb 2007 08:23:21 -0800 Subject: getting a thread out of sleep In-Reply-To: <1172035578.410747.319890@j27g2000cwj.googlegroups.com> References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> Message-ID: On 20 Feb 2007 21:26:18 -0800, placid wrote: > On Feb 21, 4:21 pm, "placid" wrote: > > On Feb 21, 4:12 pm, mark wrote: > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > On Feb 21, 3:08 pm, mark wrote: > > > > > Right now I have a thread that sleeps for sometime and check if an > > > > > event has happened and go back to sleep. Now instead I want the thread > > > > > to sleep until the event has occured process the event and go back to sleep > > > > > > > class eventhndler(threading.Thread): > > > > > def __init__(self): > > > > > threading.Thread.__init__(self) > > > > > def run(self): > > > > > while True: > > > > > time.sleep(SLEEPTIME) > > > > > ''''do event stuff''' > > > > > > The way i would do this is by using an threading.Event ( > > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > > > > > class eventhandler(threading.Thread): > > > > def __init__(self): > > > > threading.Thread.__init__(self) > > > > self.event = threading.Event() > > > > def run: > > > > while True: > > > > # block until some event happens > > > > self.event.wait() > > > > """ do stuff here """ > > > > self.event.clear() > > > > > > > > > > the way to use this is to get the main/separate thread to set() the > > > > event object. > > > > > Can you give an example of how to get the main threead to set teh event object? > > > this is exactly what i wanted to do! > > > thanks a lot! > > > mark> > oops I've miss-typed the thread variable name the following should > work > > > if __name__ == "__main__": > evtHandlerThread = eventhandler() > evtHandlerThread.start() > > # do something here # > evtHandlerThread.event.set() > > # do more stuff here # > evtHandlerThread.event.set() > > Can I have the same thread process two or more events? Can you tell how to do this? The code you gave is waiting on one event right. How can I do it for more events? thanks a lot! mark From deets at nospam.web.de Mon Feb 5 09:03:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Feb 2007 15:03:50 +0100 Subject: Watch folder for new file and execute extern program References: <1170682938.056015.238000@p10g2000cwp.googlegroups.com> Message-ID: <52orq7F1petn3U1@mid.uni-berlin.de> Michael Bo wrote: > Hi. > Can anyone guide me on how to minitor a folder for new files? And when > they appear I need to run and externe program with the file just > created (buy a 3rd program). This is OS-dependend. On Linux, FAM/GAM-server come to mind. Diez From haraldarminmassa at gmail.com Mon Feb 12 05:30:32 2007 From: haraldarminmassa at gmail.com (GHUM) Date: 12 Feb 2007 02:30:32 -0800 Subject: New Pythin user looking foe some good examples to study In-Reply-To: References: Message-ID: <1171276231.983653.264240@p10g2000cwp.googlegroups.com> Johnny, look no further than your harddrive. The Python Standard Lib is full of code examples of Python programming for various uses. Just find where your packagemanager has installed them; within windows it is usually python24/lib or python25/lib I suspect them to be below usr/lib on linux. best wishes, Harald From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 5 13:05:02 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 05 Feb 2007 19:05:02 +0100 Subject: Count nb call of a function, without global var or decorator References: <45c75b0f$0$5090$ba4acef3@news.orange.fr> <52p5c5F1p0r0cU1@mid.individual.net> <45c77058$0$25945$ba4acef3@news.orange.fr> Message-ID: <52p9ueF1pnjdaU1@mid.individual.net> M?ta-MCI wrote: > If the iterator is extern (to the function), it's like decorator, > or global var. Please excuse me, I don't understand your point. I'm not even sure if both of us speak of the same iterators. > If it is internal, it's huge, compare to this.count=this.count+1 > (or this.count+=1) In which way huge? If you want top notch performance you should use a C extension anyway ... Regards, Bj?rn -- BOFH excuse #339: manager in the cable duct From aahz at pythoncraft.com Wed Feb 28 20:09:31 2007 From: aahz at pythoncraft.com (Aahz) Date: 28 Feb 2007 17:09:31 -0800 Subject: [humor] Black Box of Or Message-ID: http://worsethanfailure.com/Comments/The_Black_Box_of_Or.aspx -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From jeff.templon at gmail.com Mon Feb 19 06:12:02 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 19 Feb 2007 03:12:02 -0800 Subject: How to test if one dict is subset of another? In-Reply-To: References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> Message-ID: <1171883522.303348.121760@l53g2000cwa.googlegroups.com> On Feb 19, 11:07 am, Peter Otten <__pete... at web.de> wrote: > Use a RDBMS (a database), they tend to be good at this kind of operations. yeah, one of the options is metakit ... sqlite and buzhug both looked promising but the constraint of pythons 2.2 and 2.3 ruled that out. disadvantage of metakit is that it's not pure python, meaning possible integration problems. the system has to be deployed at 200+ sites worldwide on a mix of RHEL 3 and 4 based systems, with some Debian clusters thrown in, and running real production ... hence my desire to find a pure-python solution if at all possible. it's looking grim. JT From ms at cerenity.org Sat Feb 3 07:20:43 2007 From: ms at cerenity.org (Michael) Date: Sat, 03 Feb 2007 12:20:43 +0000 Subject: Where Does One Begin? References: <1170485721.683685.178470@v33g2000cwv.googlegroups.com> Message-ID: <45c47d82$0$8736$ed2619ec@ptn-nntp-reader02.plus.net> Marc 'BlackJack' Rintsch wrote: > In <1170485721.683685.178470 at v33g2000cwv.googlegroups.com>, > Eric_Dexter at msn.com wrote: > >> pygame is probily a good program to start with as long as you keep in >> mind that it is possible that up to 50% of the p.c. laptops may not be >> able to run it. > > Huh? Care to explain this? I'd appreciate that being explained as well (also preferably backed up as well, but I'd be happy with explained :), since I've not actually seen this problem myself ever, though I've heard about it occasionally, but never seen it. What causes the problem? Michael. From mail at microcorp.co.za Sun Feb 11 02:32:22 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 11 Feb 2007 09:32:22 +0200 Subject: pygame and python 2.5 References: <17868.46349.59089.178486@montanaro.dyndns.org><013b01c74cd8$8d913860$03000080@hendrik> <1171146974.180146.292500@l53g2000cwa.googlegroups.com> Message-ID: <019901c74db0$050d77a0$03000080@hendrik> "Ben Sizer" wrote: > On Feb 10, 8:42 am, Steve Holden wrote: > > Hendrik van Rooyen wrote: > > > wrote: > > > "Ben Sizer" wrote: > > > > >> Ben> Python extensions written in C require recompilation for each new > > >> Ben> version of Python, due to Python limitations. > > > > >> Can you propose a means to eliminate this limitation? > > > > > Yes. - Instead of calling something, send it a message... > > > > I suppose you are proposing to use the ISO 19999.333 generic > > message-passing interface for this? The one that doesn't actually call a > > function to pass a message? > > I'm assuming you're being facetious here..? Please see my reply to Steve - and Yes, I believe he was oulling the oiss... > > Of course, functions get called at the ends of the message passing > process, but those functions can stay the same across versions while > the messages themselves change. The important part is reducing the > binary interface between the two sides to a level where it's trivial > to guarantee that part of the equation is safe. > > eg. > Instead of having PySomeType_FromLong(long value) exposed to the API, > you could have a PyAnyObject_FromLong(long value, char* > object_type_name). That function can return NULL and set up an > exception if it doesn't understand the object you asked for, so Python > versions earlier than the one that implement the type you want will > just raise an exception gracefully rather than not linking. > > The other issue comes with interfaces that are fragile by definition - > eg. instead of returning a FILE* from Python to the extension, return > the file descriptor and create the FILE* on the extension side with > fdopen. This sort of thing is exactly what is wrong with the whole concept of an API... Its very difficult, if not impossible, to guarantee that *my stuff* and *your stuff* will work together over time. Whereas if *my stuff* just publishes a message format, *anything* that can make up the message can interact with it - but it requires *my stuff* to be independently executable, and it needs a message passing mechanism that will stand the test of time. And it can create a whole new market of "Mini Appliances" each of which has *your stuff* inside them... - Hendrik From jstroud at mbi.ucla.edu Tue Feb 13 19:17:49 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 13 Feb 2007 16:17:49 -0800 Subject: Comparing lists ... In-Reply-To: <45d253e8$0$449$426a74cc@news.free.fr> References: <45d253e8$0$449$426a74cc@news.free.fr> Message-ID: Loic wrote: > I would like to know if it is possible, and how to do this with Python: > > I want to design a function to compare lists and return True only if > both lists are equal considering memory location of the list. > I suppose it would be the equivalent of comparing 2 pointers in c++ > > lets call this function check(a, b) > and define a few lists: > > >>> l0 = [1, 2, 3, 4] > >>> l1 = [1, 2, 3, 4] > >>> l2 = l0 > > I want it to have the following behaviour: > > >>> check(l1, l0) > False > > >>> check(l2, l0) > True > > >>> check(l1, l2) > False > > > Any idea how to do this with Python? Use "is". E.g.: l0 is l1 James From rene at korteklippe.de Tue Feb 27 07:59:29 2007 From: rene at korteklippe.de (=?ISO-8859-1?Q?Ren=E9_Fleschenberg?=) Date: Tue, 27 Feb 2007 13:59:29 +0100 Subject: Is type object an instance or class? In-Reply-To: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> References: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> Message-ID: <45e42b31$0$6401$9b4e6d93@newsspool2.arcor-online.net> Hi The article you read at http://www.cafepy.com/article/python_types_and_objects is really good, and the most comprehensive one I know about Python's object system. I recommend that you read it as many times as you need to understand it. It can be confusing -- just don't give up ;) I will try to give some answers to your questions. Note that I assume we are only speaking of new-style classes. Old-style classes are different, but pretty uninteresting since there is little reason to use them in new code. Another note: As far as this stuff in Python is concerened, "type" and "class" are, to my knowledge, basically just two different names for the same thing. JH schrieb: > Hi > http://www.cafepy.com/article/python_types_and_objects/ > I found that a type/class are both a subclass and a instance of base > type "object". > > It conflicts to my understanding that: > > 1.) a type/class object is created from class statement > 2.) a instance is created by "calling" a class object. Why? I see no conflict here. > A object should not be both a class and an instance at the same time. It should. 1) Everything is an object. 2) Every object is an instance of a class. >From this, it logically follows that every class should also be an instance of a class. Classes are objects, and objects are instances of classes. > Further I found out there is a special type call "type" that is a > subclass of base type "object". All other types are instances of this > type. Even base type "object" is an instance of this special type. > > What is role of this type "type" in object creation? Could someone > there straighten this concept a little? I) object' is the root of the inheritance hierarchy. All classes inherit from 'object'. 'object' is its own baseclass. Also, all objects are instances of 'object'. II) 'type' is the root of the type hierarchy. All types (i.e. classes) are subtypes of 'type'. 'type' is its own type. Because 'type' also is, like everything else, an object, it is an instance of 'object' (see I). Because it is a type object (a class), it also is a subclass of 'object' (again, see I). Objects are created by instantiating their class/type. Classes (also called "type objects") are usually created by instantiating 'type'. The object you instantiate to get a class is called that class' "metaclass". One can just as well call it that class' type. Unless you specify something else, the metaclass is 'type'. Sometimes it can be useful to not use the default 'type' as a metaclass, but a class that inherits from 'type'. class A(type): # Custom code here. pass class B(object): __metaclass__ = A type(B) # A. We overrode the metaclass. type(type(B)) # 'type'. The default metaclass. > For example (Python2.5): > >>>> issubclass(int, object) > True All classes are subclasses of 'object'. 'int' is a class, so it is a subclass of 'object'. >>>> isinstance(int, object) > True All objects are instances of 'object', and 'int' is an object. >>>> print type(int) > 'type' is the default type for classes (the "metaclass"). In the case of 'int', that default was not changed. >>>> isinstance(int, type) > True Since all classes are subclasses of 'object' and 'object' is an instance of 'type', all classes are instances of 'type'. >>>> issubclass(int, type) > False No reason why it should be. It could be, but it does not have to. >>>> issubclass(type, object) > True 'type' is a class, all classes are subclasses of 'object'. >>>> isinstance(type, object) > True 'type' is an object, all objects are instances of 'object'. >>>> isinstance(object, type) > True 'object' is a class, all classes are instances of 'type'. Hope this helps ;) -- Ren? From wolf_tracks at invalid.com Wed Feb 7 20:12:16 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 07 Feb 2007 17:12:16 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: <1170896151.334753.113130@l53g2000cwa.googlegroups.com> References: <1170896151.334753.113130@l53g2000cwa.googlegroups.com> Message-ID: Matimus wrote: >> For some reason Python 2.2.4 cannot find the Numeric module. It's been > > Is this a typo, or are you really using 2.2.4? If so, you are going to > have to get the versions of Numeric and PIL that work with Python 2.2. > Or, alternatively, you can install python 2.4.4 with the .msi file you > listed. You should also be able to run that just like an executable if > you are using Windows XP. Based on the assumption that you have Python > 2.2 installed, this will leave you with two version of Python, which > will work, but could be tricky. It might be best to just uninstall and > reinstall Python. > > -Matt > Yes, a typo. 2.4.4. What is installed is: python-2.4.4.msi PIL-1.1.5.win32-py2.4.exe Numeric-24.2.win32-py2.4.exe Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet 'I think it not improbable that man, like the grub that prepares a chamber for the winged thing it has never seen but is to be, may have... destinies that he does not understand." -- Oliver Wendell Holmes -- Web Page: From JStoneGT at aol.com Tue Feb 13 11:01:59 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Tue, 13 Feb 2007 11:01:59 EST Subject: Newbie question about Class Message-ID: [quote]The idea behind that class is to act "as-if" it were a real dictionary. Dicts have an update method, and UserDict should too. But it's not listed in the book (should appear a few lines below that code); this is a possible implementation: def update(self, other): for key in other.keys(): self.data[key] = other[key] Given this method, __init__ works fine. Using self.data.update(dict) is OK if the dict argument is a real dictionary, but not if it's another UserDict.[/quote] Thank you. But I'm still confused that what's the "real dictionary"?I can't know this point.Please help and thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dingbat at codesmiths.com Fri Feb 16 13:31:58 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 16 Feb 2007 10:31:58 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: <1171483611.930377.141080@l53g2000cwa.googlegroups.com> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <1171472657.567241.302690@h3g2000cwc.googlegroups.com> <1171483611.930377.141080@l53g2000cwa.googlegroups.com> Message-ID: <1171650718.626260.223380@v45g2000cwv.googlegroups.com> On 14 Feb, 20:06, "Beej" wrote: > http://linuxgazette.net/109/pramode.html Thanks, that's a _really_ interesting link (Oh, I need to learn Scheme!) My code now looks like this, which I'm starting to feel much happier about in a functional sense. c_rot = lambda c, chars : (chr((ord(c) - ord(chars[0]) + (len(chars) // 2)) % len(chars) + ord(chars[0]))) c_rot13 = lambda c : (((c, \ c_rot(c, string.ascii_uppercase)) [c in string.ascii_uppercase]), \ c_rot(c, string.ascii_lowercase)) [c in string.ascii_lowercase] rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'') I also considered this, but don't trust it as it relies on the two sets being mutually disjoint between their inputs and outputs. qc_rot = lambda c, chars : (c, c_rot(c, chars)) [c in chars] c_rot13 = lambda c : (qc_rot( qc_rot(c, string.ascii_lowercase), string.ascii_uppercase)) From __peter__ at web.de Thu Feb 1 07:54:40 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Feb 2007 13:54:40 +0100 Subject: how do I pipe two processes? References: <1170321143.287492.4300@k78g2000cwa.googlegroups.com> Message-ID: Bilgehan.Balban at gmail.com wrote: > Hi, I want to pipe output of process A to B, and read output of B from > python. On Unix if I do the following: > > child_out, child_in = popen2("program_a | program_b") > > line = child_out.readline() > > I get "IOError: bad file descriptor" from Python, and broken pipe > error from program_b. How do I do this right? In through the out door? From the docs: ... Returns the file objects (child_stdin, child_stdout) ... Peter From paul at subsignal.org Sun Feb 4 08:41:55 2007 From: paul at subsignal.org (paul) Date: Sun, 04 Feb 2007 14:41:55 +0100 Subject: when will python 2.5 take in mainstream? In-Reply-To: References: Message-ID: Eric CHAO schrieb: > A lot of application based on python claim that python 2.3 or 2.4 is > needed not 2.5, ie. mysqldb. I've been using python for months. I > don't care about 2.4 or 2.5. But I like the default icons of python in > 2.5. So I just use that, but some scripts can't work on that. What do you mean by "that"? I just use the 2.5 icons with 2.4 and all my scripts are happy ;) thanks Paul From steve at holdenweb.com Tue Feb 6 05:42:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 06 Feb 2007 10:42:03 +0000 Subject: Python cheatsheets In-Reply-To: References: Message-ID: robert wrote: > gonzlobo wrote: >> Curious if anyone has a python cheatsheet* published? I'm looking for >> something that summarizes all commands/functions/attributes. Having >> these printed on a 8" x 11" double-sided laminated paper is pretty >> cool. >> >> * cheatsheet probably isn't the right word, but you get the idea. :) > > search: python quick reference > > e.g.: http://www.benyoonline.com/pqr/pqr24/PQR2.4.html ... and be aware that the "quick" reference currently runs to seventeen or eighteen sides ... it should really be renamed "comprehensive reference", though it does currently omit the kitchenSink module :) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From grflanagan at yahoo.co.uk Wed Feb 14 06:08:51 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 14 Feb 2007 03:08:51 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: <1171451331.473322.190750@a75g2000cwd.googlegroups.com> On Feb 12, 1:27 am, "agent-s" wrote: > Basically I'm programming a board game and I have to use a list of > lists to represent the board (a list of 8 lists with 8 elements each). > I have to search the adjacent cells for existing pieces and I was > wondering how I would go about doing this efficiently. Thanks def iter_grid(cols): i=0 while True: yield divmod(i,cols) i += 1 def iter_adjacents(row, col): gen = iter_grid(3) for i in range(9): x, y = gen.next() if x == 1 and y ==1: continue else: yield row - x + 1, col - y + 1 def make_grid_dict(rows, cols): return dict( zip(iter_grid(cols), ['#'] * (rows*cols)) ) def make_adjacent_list(row, col, row_length, col_length): ret = [] for x, y in iter_adjacents(row, col): if x > -1 and y > -1 and x < row_length and y < col_length: ret.append((x,y)) return ret grid = make_grid_dict(8, 8) adjacents = dict(grid) for x,y in sorted(adjacents.keys()): adjacents[x,y] = make_adjacent_list(x, y, 8, 8) print '(%s, %s) - %s ' % (x, y, adjacents[x,y] (0, 0) - [(1, 1), (1, 0), (0, 1)] (0, 1) - [(1, 2), (1, 1), (1, 0), (0, 2), (0, 0)] (0, 2) - [(1, 3), (1, 2), (1, 1), (0, 3), (0, 1)] (0, 3) - [(1, 4), (1, 3), (1, 2), (0, 4), (0, 2)] (0, 4) - [(1, 5), (1, 4), (1, 3), (0, 5), (0, 3)] (0, 5) - [(1, 6), (1, 5), (1, 4), (0, 6), (0, 4)] (0, 6) - [(1, 7), (1, 6), (1, 5), (0, 7), (0, 5)] (0, 7) - [(1, 7), (1, 6), (0, 6)] (1, 0) - [(2, 1), (2, 0), (1, 1), (0, 1), (0, 0)] (1, 1) - [(2, 2), (2, 1), (2, 0), (1, 2), (1, 0), (0, 2), (0, 1), (0, 0)] (1, 2) - [(2, 3), (2, 2), (2, 1), (1, 3), (1, 1), (0, 3), (0, 2), (0, 1)] (1, 3) - [(2, 4), (2, 3), (2, 2), (1, 4), (1, 2), (0, 4), (0, 3), (0, 2)] (1, 4) - [(2, 5), (2, 4), (2, 3), (1, 5), (1, 3), (0, 5), (0, 4), (0, 3)] (1, 5) - [(2, 6), (2, 5), (2, 4), (1, 6), (1, 4), (0, 6), (0, 5), (0, 4)] (1, 6) - [(2, 7), (2, 6), (2, 5), (1, 7), (1, 5), (0, 7), (0, 6), (0, 5)] (1, 7) - [(2, 7), (2, 6), (1, 6), (0, 7), (0, 6)] (2, 0) - [(3, 1), (3, 0), (2, 1), (1, 1), (1, 0)] (2, 1) - [(3, 2), (3, 1), (3, 0), (2, 2), (2, 0), (1, 2), (1, 1), (1, 0)] (2, 2) - [(3, 3), (3, 2), (3, 1), (2, 3), (2, 1), (1, 3), (1, 2), (1, 1)] (2, 3) - [(3, 4), (3, 3), (3, 2), (2, 4), (2, 2), (1, 4), (1, 3), (1, 2)] (2, 4) - [(3, 5), (3, 4), (3, 3), (2, 5), (2, 3), (1, 5), (1, 4), (1, 3)] (2, 5) - [(3, 6), (3, 5), (3, 4), (2, 6), (2, 4), (1, 6), (1, 5), (1, 4)] (2, 6) - [(3, 7), (3, 6), (3, 5), (2, 7), (2, 5), (1, 7), (1, 6), (1, 5)] (2, 7) - [(3, 7), (3, 6), (2, 6), (1, 7), (1, 6)] (3, 0) - [(4, 1), (4, 0), (3, 1), (2, 1), (2, 0)] (3, 1) - [(4, 2), (4, 1), (4, 0), (3, 2), (3, 0), (2, 2), (2, 1), (2, 0)] (3, 2) - [(4, 3), (4, 2), (4, 1), (3, 3), (3, 1), (2, 3), (2, 2), (2, 1)] (3, 3) - [(4, 4), (4, 3), (4, 2), (3, 4), (3, 2), (2, 4), (2, 3), (2, 2)] (3, 4) - [(4, 5), (4, 4), (4, 3), (3, 5), (3, 3), (2, 5), (2, 4), (2, 3)] (3, 5) - [(4, 6), (4, 5), (4, 4), (3, 6), (3, 4), (2, 6), (2, 5), (2, 4)] (3, 6) - [(4, 7), (4, 6), (4, 5), (3, 7), (3, 5), (2, 7), (2, 6), (2, 5)] (3, 7) - [(4, 7), (4, 6), (3, 6), (2, 7), (2, 6)] (4, 0) - [(5, 1), (5, 0), (4, 1), (3, 1), (3, 0)] (4, 1) - [(5, 2), (5, 1), (5, 0), (4, 2), (4, 0), (3, 2), (3, 1), (3, 0)] (4, 2) - [(5, 3), (5, 2), (5, 1), (4, 3), (4, 1), (3, 3), (3, 2), (3, 1)] (4, 3) - [(5, 4), (5, 3), (5, 2), (4, 4), (4, 2), (3, 4), (3, 3), (3, 2)] (4, 4) - [(5, 5), (5, 4), (5, 3), (4, 5), (4, 3), (3, 5), (3, 4), (3, 3)] (4, 5) - [(5, 6), (5, 5), (5, 4), (4, 6), (4, 4), (3, 6), (3, 5), (3, 4)] (4, 6) - [(5, 7), (5, 6), (5, 5), (4, 7), (4, 5), (3, 7), (3, 6), (3, 5)] (4, 7) - [(5, 7), (5, 6), (4, 6), (3, 7), (3, 6)] (5, 0) - [(6, 1), (6, 0), (5, 1), (4, 1), (4, 0)] (5, 1) - [(6, 2), (6, 1), (6, 0), (5, 2), (5, 0), (4, 2), (4, 1), (4, 0)] (5, 2) - [(6, 3), (6, 2), (6, 1), (5, 3), (5, 1), (4, 3), (4, 2), (4, 1)] (5, 3) - [(6, 4), (6, 3), (6, 2), (5, 4), (5, 2), (4, 4), (4, 3), (4, 2)] (5, 4) - [(6, 5), (6, 4), (6, 3), (5, 5), (5, 3), (4, 5), (4, 4), (4, 3)] (5, 5) - [(6, 6), (6, 5), (6, 4), (5, 6), (5, 4), (4, 6), (4, 5), (4, 4)] (5, 6) - [(6, 7), (6, 6), (6, 5), (5, 7), (5, 5), (4, 7), (4, 6), (4, 5)] (5, 7) - [(6, 7), (6, 6), (5, 6), (4, 7), (4, 6)] (6, 0) - [(7, 1), (7, 0), (6, 1), (5, 1), (5, 0)] (6, 1) - [(7, 2), (7, 1), (7, 0), (6, 2), (6, 0), (5, 2), (5, 1), (5, 0)] (6, 2) - [(7, 3), (7, 2), (7, 1), (6, 3), (6, 1), (5, 3), (5, 2), (5, 1)] (6, 3) - [(7, 4), (7, 3), (7, 2), (6, 4), (6, 2), (5, 4), (5, 3), (5, 2)] (6, 4) - [(7, 5), (7, 4), (7, 3), (6, 5), (6, 3), (5, 5), (5, 4), (5, 3)] (6, 5) - [(7, 6), (7, 5), (7, 4), (6, 6), (6, 4), (5, 6), (5, 5), (5, 4)] (6, 6) - [(7, 7), (7, 6), (7, 5), (6, 7), (6, 5), (5, 7), (5, 6), (5, 5)] (6, 7) - [(7, 7), (7, 6), (6, 6), (5, 7), (5, 6)] (7, 0) - [(7, 1), (6, 1), (6, 0)] (7, 1) - [(7, 2), (7, 0), (6, 2), (6, 1), (6, 0)] (7, 2) - [(7, 3), (7, 1), (6, 3), (6, 2), (6, 1)] (7, 3) - [(7, 4), (7, 2), (6, 4), (6, 3), (6, 2)] (7, 4) - [(7, 5), (7, 3), (6, 5), (6, 4), (6, 3)] (7, 5) - [(7, 6), (7, 4), (6, 6), (6, 5), (6, 4)] (7, 6) - [(7, 7), (7, 5), (6, 7), (6, 6), (6, 5)] (7, 7) - [(7, 6), (6, 7), (6, 6)] From sean_mcilroy at yahoo.com Mon Feb 5 15:07:04 2007 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 5 Feb 2007 12:07:04 -0800 Subject: alias for data member of class instance? Message-ID: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> hi all is there a way to do this ... class clown: def __init__(self): self.x = 0 self.y = ALIAS(self.x) ## FEASIBLE ? ... so that you get results like this ... krusty = clown() krusty.x >> 0 krusty.y >> 0 krusty.x = 1 krusty.x >> 1 krusty.y >> 1 ... ? thanks. peace stm From steve at REMOVE.THIS.cybersource.com.au Fri Feb 9 22:07:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Feb 2007 14:07:43 +1100 Subject: Matching Strings References: Message-ID: On Fri, 09 Feb 2007 16:17:31 -0800, James Stroud wrote: > Assuming item is "(u'ground water',)" > > import re > item = re.compile(r"\(u'([^']*)',\)").search(item).group(1) Using a regex is a lot of overhead for a very simple operation. If item is the string "(u'ground water',)" then item[3:-3] will give "ground water". >>> import re, timeit >>> item = "(u'ground water',)" >>> timeit.Timer('item[3:-3]', 'from __main__ import item').repeat() [0.56174778938293457, 0.53341794013977051, 0.53485989570617676] >>> timeit.Timer( \ ... '''re.compile(r"\(u'([^']*)',\)").search(item).group(1)''', \ ... 'from __main__ import item; import re').repeat() [9.2723720073699951, 9.2299859523773193, 9.2523660659790039] However, as many others have pointed out, the Original Poster's problem isn't that item has leading brackets around the substring he wants, but that it is a tuple. -- Steven. From popuser at christest2.dc.k12us.com Tue Feb 20 20:14:05 2007 From: popuser at christest2.dc.k12us.com (Pop User) Date: Tue, 20 Feb 2007 20:14:05 -0500 Subject: Regex Speed In-Reply-To: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> Message-ID: <45DB9CDD.7070400@christest2.dc.k12us.com> garrickp at gmail.com wrote: > While creating a log parser for fairly large logs, we have run into an > issue where the time to process was relatively unacceptable (upwards > of 5 minutes for 1-2 million lines of logs). In contrast, using the > Linux tool grep would complete the same search in a matter of seconds. > Its very hard to beat grep depending on the nature of the regex you are searching using. The regex engines in python/perl/php/ruby have traded the speed of grep/awk for the ability to do more complex searches. http://swtch.com/~rsc/regexp/regexp1.html This might not be your problem but if it is you can always popen grep. It would be nice if there were a Thompson NFA re module. From kirk at nospam.jobsluder.net Sun Feb 4 10:41:37 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Sun, 04 Feb 2007 15:41:37 GMT Subject: Python does not play well with others References: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170600807.504088.80150@m58g2000cwm.googlegroups.com> Message-ID: In article <1170600807.504088.80150 at m58g2000cwm.googlegroups.com>, "Paul Boddie" wrote: > Would it benefit the Python community more if Python shipped with > MySQL support out of the box? Is it likely that a user suddenly finds > him/herself needing to connect to a MySQL database? The other problem is that it chains the python release schedule to that of MySQL AB (and postgresql, and whatever.) One of the key advantages to independent modules is that I don't need to update my entire python system every time my database vendor releases a new library, nor do I have to accept lag time as the module is tested and rolled into the base distribution. Database client libraries are much more of a moving target than core language features. I find it interesting that PHP struggled with these issues and decided to abandon embedded MySQL support partly because they couldn't maintain their own parallel versions of the client libraries. http://us2.php.net/manual/en/faq.databases.php#faq.databases.mysql.ph p5 Among the other problems faced by both PHP and Python in bundling MySQL support is that they can't legally do it without adopting the GPL. Which leaves me wondering why the python core should adopt a feature that was abandoned by PHP, and was never highly recommended or used? > Paul From rshepard at nospam.appl-ecosys.com Sun Feb 25 19:35:53 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 26 Feb 2007 00:35:53 GMT Subject: Referencing Items in a List of Tuples References: <1172424046.323933.85250@q2g2000cwa.googlegroups.com> Message-ID: On 2007-02-25, Jussi Salmela wrote: > I'm nitpicking, but the OP has a list of tuples: > ec = [ item[2:] for item in mainlist if item[:2] == ('eco','con') ] Jussi, An excellent nit to pick. Thank you, Rich From bjourne at gmail.com Wed Feb 7 13:41:19 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 7 Feb 2007 19:41:19 +0100 Subject: Why doesn't my heapify work? In-Reply-To: References: Message-ID: <740c3aec0702071041h1d59caa0m67bd893859f3dc9c@mail.gmail.com> You do know about the heapq module? http://docs.python.org/dev/lib/module-heapq.html -- mvh Bj?rn From fperez.net at gmail.com Fri Feb 23 00:24:17 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 22 Feb 2007 22:24:17 -0700 Subject: pylab, integral of sinc function References: Message-ID: Sch?le Daniel wrote: > Hello, > > In [19]: def simple_integral(func,a,b,dx = 0.001): > ....: return sum(map(lambda x:dx*x, func(arange(a,b,dx)))) > ....: > > In [20]: simple_integral(sin, 0, 2*pi) > Out[20]: -7.5484213527594133e-08 > > ok, can be thought as zero > > In [21]: simple_integral(sinc, -1000, 1000) > Out[21]: 0.99979735786416357 > > hmm, it should be something around pi > it is a way too far from it, even with a=-10000,b=10000 > > In [22]: def ppp(x): > ....: return sin(x)/x > ....: > > In [23]: simple_integral(ppp, -1000, 1000) > Out[23]: 3.1404662440661117 > > nice > > is my sinc function in pylab broken? > is there a better way to do numerical integration in pylab? Pylab is mostly a plotting library, which happens (for historical reasons I won't go into) to expose a small set of numerical algorithms, most of them actually residing in Numpy. For a more extensive collection of scientific and numerical algorithms, you should look into using SciPy: In [34]: import scipy.integrate In [35]: import scipy as S In [36]: import scipy.integrate In [37]: S.integrate. S.integrate.Inf S.integrate.composite S.integrate.NumpyTest S.integrate.cumtrapz S.integrate.__all__ S.integrate.dblquad S.integrate.__class__ S.integrate.fixed_quad S.integrate.__delattr__ S.integrate.inf S.integrate.__dict__ S.integrate.newton_cotes S.integrate.__doc__ S.integrate.ode S.integrate.__file__ S.integrate.odeint S.integrate.__getattribute__ S.integrate.odepack S.integrate.__hash__ S.integrate.quad S.integrate.__init__ S.integrate.quad_explain S.integrate.__name__ S.integrate.quadpack S.integrate.__new__ S.integrate.quadrature S.integrate.__path__ S.integrate.romb S.integrate.__reduce__ S.integrate.romberg S.integrate.__reduce_ex__ S.integrate.simps S.integrate.__repr__ S.integrate.test S.integrate.__setattr__ S.integrate.tplquad S.integrate.__str__ S.integrate.trapz S.integrate._odepack S.integrate.vode S.integrate._quadpack These will provide dramatically faster performance, and far better algorithmic control, than the simple_integral: In [4]: time simple_integral(lambda x:sinc(x/pi), -100, 100) CPU times: user 7.08 s, sys: 0.42 s, total: 7.50 s Wall time: 7.58 Out[4]: 3.1244509352 In [40]: time S.integrate.quad(lambda x:sinc(x/pi), -100, 100) CPU times: user 0.05 s, sys: 0.00 s, total: 0.05 s Wall time: 0.06 Out[40]: (3.124450933778113, 6.8429604895257158e-10) Note that I used only -100,100 as the limits so I didn't have to wait forever for simple_integral to finish. As you know, this is a nasty, highly oscillatory integral for which almost any 'black box' method will have problems, but at least scipy is nice enough to let you know: In [41]: S.integrate.quad(lambda x:sinc(x/pi), -1000, 1000) Warning: The maximum number of subdivisions (50) has been achieved. If increasing the limit yields no improvement it is advised to analyze the integrand in order to determine the difficulties. If the position of a local difficulty can be determined (singularity, discontinuity) one will probably gain from splitting up the interval and calling the integrator on the subranges. Perhaps a special-purpose integrator should be used. Out[41]: (3.5354545588973298, 1.4922039610659907) In [42]: S.integrate.quad(lambda x:sinc(x/pi), -1000, 1000,limit=1000) Out[42]: (3.1404662439375475, 4.5659823144674379e-08) Cheers, f ps - the 2nd number is the error estimate. From kentilton at gmail.com Mon Feb 26 14:30:53 2007 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 26 Feb 2007 14:30:53 -0500 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: Tech HR wrote: > In article <1172482314.598240.3440 at j27g2000cwj.googlegroups.com>, > dixkey at gmail.com wrote: > > >>On Feb 26, 6:32 am, Tech HR wrote: >> >>>Our >>>website is currently a LAMP appication with P=Python. We are looking for >>>bright motivated people who know or are willing to learn Python and/or >>>Linux, Apache and MySQL system administration skills. (And if you want >>>to convince us that we should switch over to Postgres, we're willing to >>>listen.) >> >>This is more out of curiosity, but does it mean that you wouldn't be >>willing to listen about a switch from Python to Lisp? > > > No, it doesn't mean that. In fact, there is a significant faction in > the technical staff (including the CTO) who would like nothing better > than to be able to use Lisp instead of Python. Ah, you must lack courage in your convictions. Unless you plan on being out of business in six months, Do the Right Thing. Use the best language. Then worry about little things like libraries and filling seats. There is a great saying, "Think you can or think you cannot, either way you will be right." Something like that. > But we have some pretty > compelling reasons to stick with Python, not least of which is that it > is turning out to be very hard to find Lisp programmers. (Actually, > it's turning out to be hard to find Python programmers too, but it's > easier to train a Java programmer or a Perler on Python than Lisp. Place two ads, both for "Java/Perl/C programmers". One looking for folks willing to learn Python, one for those willing to learn Lisp. I guarantee you respondents to the second group will be more fun to go bar-hopping with. Oh, and twice as good at programming as the first group. You are solving the wrong problem. "lisp is the best language and we cannot find Lisp programmers." The problem is not the choice of Lisp, the problem is finding people to program Lisp. They do not have to be Lisp programmers with certified scorched areas from being flamed by me on c.l.l. They just need to be great programmers, in any language. Choosing Lisp will make all of you twenty to one hundred percent happier to go to work each day and stay a little longer each night to grind out CFFI bindings for the libs you need. Hiring a good programmer to learn Lisp will have them putting in about a hundred hours a week and loving it. Tap into the energy, man. > We > also have fair bit of infrastructure built up in Python at this point.) Do I tell you my problems? :) kt -- Well, I've wrestled with reality for 35 years, Doctor, and I'm happy to state I finally won out over it. -- Elwood P. Dowd In this world, you must be oh so smart or oh so pleasant. -- Elwood's Mom From arkanes at gmail.com Mon Feb 5 10:36:02 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 5 Feb 2007 09:36:02 -0600 Subject: CTypes In-Reply-To: <4Rrxh.18422$pQ3.13066@newsread4.news.pas.earthlink.net> References: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> <1170544958.865802.120010@s48g2000cws.googlegroups.com> <1170592004.632364.65340@v33g2000cwv.googlegroups.com> <1170594987.511527.215030@p10g2000cwp.googlegroups.com> <4Rrxh.18422$pQ3.13066@newsread4.news.pas.earthlink.net> Message-ID: <4866bea60702050736l151edbd6s4eefec90ab73d750@mail.gmail.com> On 2/4/07, Dennis Lee Bieber wrote: > On 4 Feb 2007 05:16:27 -0800, "SoutoJohn at gmail.com" > declaimed the following in comp.lang.python: > > > > script file 'test.py' and a DLL 'AutoIt3X.DLL' in the same folder, how > > could I load it? The tutorial did something like dll=windll.kernel32, > > which I understands loads the kernel but I don't see how I could apply > > that to load AutoIt3X. Thanks in advanced. > > I've not used ctypes, but from all the examples I've seen.... > > What happens if you specify: > > dll = ctypes.windll.AutoIt3X > > I think ctypes uses a getattr() trap to extract the dll name from > the invocation, then passes that to the Windows library loading code. > -- This is indeed what ctypes does. There's also a LoadLibrary static method of windll.cdll etc that you can use to get it explicitly (like if you need to load a DLL not on your path). dll = ctypes.windll.LoadLibrary(r"C:\AutoIT#x.dll") From S.Mientki-nospam at mailbox.kun.nl Sat Feb 3 12:25:31 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 03 Feb 2007 18:25:31 +0100 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? Message-ID: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Is it possible to change the searchpath for modules on the flight, under winXP ? Most preferred is some command to extend the searchpath. (the environment variable PYTHONPATH needs a reboot) thanks, Stef Mientki From tleeuwenburg at gmail.com Thu Feb 8 22:05:52 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 8 Feb 2007 19:05:52 -0800 Subject: Python Papers second issue now available! In-Reply-To: <1170988026.204547.97250@m58g2000cwm.googlegroups.com> References: <1170988026.204547.97250@m58g2000cwm.googlegroups.com> Message-ID: <1170990352.338449.153010@k78g2000cwa.googlegroups.com> http://pythonpapers.cgpublisher.com/product/pub.169/prod.5 Sorry, forgot to add the URL From jvframework at gmail.com Tue Feb 27 08:44:33 2007 From: jvframework at gmail.com (jvframework at gmail.com) Date: 27 Feb 2007 05:44:33 -0800 Subject: Calling Python Web Services from C# Message-ID: <1172583873.292450.200490@p10g2000cwp.googlegroups.com> I have a C# .NET cliente calling a Python web services. I pass two string values to web service and I wanna receive a string from the method. But, the server side receive my string values and the client side only display a empty string (""). I generate a C# Proxy class from the python web services WSDL with wsdl.exe tool. Any idea about this problem? Regards. From aspineux at gmail.com Thu Feb 1 18:25:11 2007 From: aspineux at gmail.com (aspineux) Date: 1 Feb 2007 15:25:11 -0800 Subject: python executing windows exe In-Reply-To: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> References: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> Message-ID: <1170372305.523749.295580@m58g2000cwm.googlegroups.com> First look if your .exe will accept to work that way ! try in a DOS prompt > echo yourfilename | nec2d.exe or if the program expect more input, write them all in a file ( myinputs.txt ) and try : > nec2d.exe < myinputs.txt If it works looks for module subprocess and more precisely object subprocess.popen and method comunicate On 1 f?v, 23:57, "Kiran" wrote: > Hi everybody, > I am making python run an executable using the os module. Here is > my question. The executable, once it is running, asks the user to > input a filename that it will process. Now, my question is how do i > automate this. let me make this clear, it is not an argument you pass > in when you type in the exe. An example below illustrates: > > THIS IS NOT WHAT YOU DO: > nec2d.exe couple1.nec # couple1.nec is the > file you want to prcess > > rather, what you do is in windows cmd: > > nec2d.exe > **** PROGRAM PRINTS OUT STUFF***** > **** PROGRAM PRINTS OUT STUFF***** > **** PROGRAM PRINTS OUT STUFF***** > **** PROGRAM PRINTS OUT STUFF***** > Please enter input file: <--------- THIS IS WHERE THE USER IS ASKED > TO TYPE IN THE FILENAME > > everybody thanks for your help > -- Kiran From Mark.Geyzer at gmail.com Sun Feb 11 09:10:56 2007 From: Mark.Geyzer at gmail.com (volcano) Date: 11 Feb 2007 06:10:56 -0800 Subject: How to access an absolute address through Python? In-Reply-To: References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> <1171197574.776135.96980@k78g2000cwa.googlegroups.com> <1171198707.889681.177270@h3g2000cwc.googlegroups.com> Message-ID: <1171203056.653392.223110@s48g2000cws.googlegroups.com> On Feb 11, 3:46 pm, Steve Holden wrote: > volcano wrote: > > On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch wrote: > [...] > >> What's your goal? What do you expect at the memory address you want to > >> access? > > >> Ciao, > >> Marc 'BlackJack' Rintsch > > > My goal is to sync program with external equipment through a register > > defined as an absolute physical address. I know how to do it from C - > > was curious if it may be done from Python. Can it be done? > > No. You'd have to use a compiled extension. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007 Steve, Fred, thank you. This is exactly what I have done, though I did hope for shortcut. Life is tough:)! From bdesth.quelquechose at free.quelquepart.fr Tue Feb 13 18:33:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 14 Feb 2007 00:33:35 +0100 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Message-ID: <45d24379$0$1332$426a74cc@news.free.fr> devicerandom at gmail.com a ?crit : > Hi, > (snip) > - is there a better way than using multiple inheritance to plug-in > dynamically commands in a Cmd command line? Yes : use composition + delegation. Python makes it easy: #foo.py class Commands(object): def do_this(self,args): ... def do_that(self,args): ... #bar.py class Commands(object): def do_what(self, args): ... I've seen I can do it by explicitely import them and using multiple inheritance: class MyCli(cmd.Cmd): def __init__(self, *plugins): self.plugins = plugins self._cache = {} def __getattr__(self, name): try: return self._cache[name] except KeyError: for plugin in self.plugins: attr = getattr(plugin, name, None) if attr is not None: self._cache[name] = attr return attr my_cli = MyCli(foo.Command(), bar.Command()) From andy.terrel at gmail.com Mon Feb 12 22:30:12 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 12 Feb 2007 19:30:12 -0800 Subject: c++ for python programmers In-Reply-To: <1171318292.493867.181860@a34g2000cwb.googlegroups.com> References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> <1171318292.493867.181860@a34g2000cwb.googlegroups.com> Message-ID: <1171337412.448867.238550@k78g2000cwa.googlegroups.com> On Feb 12, 4:11 pm, "Thomas Nelson" wrote: > On Feb 12, 1:35 pm, andrew clarke wrote: > > > Thomas, I sent you a message off-list but it bounced due to your mailbox > > being full. > > > Short answer: Subscribe to the c-p... at yahoogroups.com mailing list and > > ask your C/C++ questions there. > > > Regards > > Andrew > > I have to edit a large C++ project written by someone else. My email > address > above is incorrect; replace mail with cs. Thanks for the help. > > Thomas To learn C I recommend K&R (Kernigahn and Richie), for C++ I like Savitch's book, Absolute C++. I too learned python then c/c++. Also I would disagree with the people saying never to use C++, it will run much faster for computationally intensive programs. It will make you a better python programmer, you get to see how things are done "under the hood". From exhuma at gmail.com Fri Feb 16 05:11:36 2007 From: exhuma at gmail.com (exhuma.twn) Date: 16 Feb 2007 02:11:36 -0800 Subject: Approaches of interprocess communication Message-ID: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Hi all, Supposing you have two separate processes running on the same box, what approach would you suggest to communicate between those two processes. Let me list the ones I know of: * Sockets Advantage: Supported per se in nearly every programming language without even the need to install additional packages Disadvantage: Lot's of code to write, and it's kind of silly to communicate via TCP/IP if the processes run on the same machine. * Webservices Advantage: Relatively easy to use, can work across different languages Disadvantage: Even more overhead on the TCP/IP side that simple sockets, as really bulky SOAP messages need to be passed around. * CORBA -- similar to webservices but more complicated to code. * Shared memory I don't know much about this subject. Supposing both processes are written in Python, is there any other way to achieve this? To me, shared memory sound the most suited approach. But as said, I am still fuzzy in this area. Where can I find more information on this subject? From dubrovsky at physics.uq.edu.au Tue Feb 20 21:41:57 2007 From: dubrovsky at physics.uq.edu.au (Alejandro Dubrovsky) Date: Wed, 21 Feb 2007 12:41:57 +1000 Subject: Regex Speed References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172013317.943062.303110@t69g2000cwt.googlegroups.com> Message-ID: Steve Holden wrote: > John Machin wrote: > [...] >> >> To help you, we need either (a) basic information or (b) crystal >> balls. > [...] > > How on earth would having glass testicles help us help him? > John, of course, meant spheres of doped single crystal silicon on which we could simulate all the specific coding problems for which all possible values of garrickp would have posted the message that he/she/it did, then solve them by descending order of likelyhood till garrickp emitted a "That solves it, thanks!" From bapolis at gmail.com Thu Feb 1 19:51:30 2007 From: bapolis at gmail.com (Toine) Date: 1 Feb 2007 16:51:30 -0800 Subject: Calculating future dates Message-ID: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> Hello, I'm new to Python so please bare with me... I need to calculate a date that is exactly 31 days from the current date in YYYY-MM-DD format. I know that date.today() returns the current date, but how can I add 31 days to this result? I'm sure this task is simple, but I haven't been able to figure it out. Thanks From aisaac at american.edu Tue Feb 27 15:59:03 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 27 Feb 2007 20:59:03 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: "Steven D'Aprano" wrote in message news:pan.2007.02.27.07.24.57.769316 at REMOVEME.cybersource.com.au... class Difficult(object): def __setattr__(self, name, value): if self.__dict__.has_key(name): print "'%s' exists as an instance attribute" % name self.__dict__[name] = value elif self.__class__.__dict__.has_key(name): print "'%s' exists as a class attribute" % name self.__class__.__dict__[name] = value else: print "Can't create new attributes, 'cos I said so!" But this prevents setting attributes during initialization, so it does not meet the spec. Cheers, Alan From ralf at schoenian-online.de Wed Feb 7 23:05:37 2007 From: ralf at schoenian-online.de (=?ISO-8859-2?Q?Ralf_Sch=F6nian?=) Date: Thu, 08 Feb 2007 05:05:37 +0100 Subject: uml and python In-Reply-To: <1170900832.692717.259160@l53g2000cwa.googlegroups.com> References: <1170900832.692717.259160@l53g2000cwa.googlegroups.com> Message-ID: <45caa188$1@news.arcor-ip.de> azrael schrieb: > hy guys > > i've been googling and got several posts, but nothing that is a > satisfaction in my eyes. can someone tell me a nice uml diagram tool > with python export (if possible nice gui), or at least nice uml tool > > gpl or freeware (widows) prefered > > thanks > Take a look at gaphor: http://gaphor.sourceforge.net/ Regards, Ralf Schoenian From paul at boddie.org.uk Tue Feb 13 11:48:17 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 13 Feb 2007 08:48:17 -0800 Subject: Freeze packaging for Debian In-Reply-To: <9839a4-vpb.ln1@lairds.us> References: <9839a4-vpb.ln1@lairds.us> Message-ID: <1171385297.383776.281490@a75g2000cwd.googlegroups.com> On 13 Feb, 16:48, cla... at lairds.us (Cameron Laird) wrote: > How is Freeze--freeze.py --packaged > for Debian? *Is* it packaged for Debian? A search for freeze.py in package contents conducted from the Debian packages page [1] indicates that the file in question is provided by the examples package for each particular version of Python: so the python2.4-examples package would provide the file for a Python 2.4 installation, for example. Doing "dpkg -S freeze.py" yields python2.4- examples as the package responsible on my Kubuntu system. Paul [1] http://www.debian.org/distrib/packages (also http://packages.debian.org/) From shadabsayani at yahoo.com Fri Feb 16 10:18:46 2007 From: shadabsayani at yahoo.com (Shadab Sayani) Date: Fri, 16 Feb 2007 15:18:46 +0000 (GMT) Subject: Reg Google Web Toolkit and Python In-Reply-To: <53lranF1th0pcU1@mid.uni-berlin.de> Message-ID: <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> Hi , We have a project where I need to read files store them in database in the backend.We have done this in python.Now we decided to use Ajax technique for user interface.For that we found that GWT is one of the best toolkits.Now I got a doubt can I interface GWT with python. Thanks , Shadab. Send instant messages to your online friends http://uk.messenger.yahoo.com From jm.suresh at gmail.com Wed Feb 14 03:16:01 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 14 Feb 2007 00:16:01 -0800 Subject: Recursive calls and stack In-Reply-To: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: <1171440961.489199.269760@l53g2000cwa.googlegroups.com> On Feb 14, 11:09 am, "jm.sur... at no.spam.gmail.com" wrote: > Hi, > I have a program which literately finds the object that overlapping a > point. The horizontal and vertical search are called recursively from > inside each other. > Is this way of implementation fill thestackspace with the local > variables inside eachcall. If this is not good, is there a better way > to implement? Orpythonitself will understand that the calls happen > in the last line, so local variables need not be pushed into thestack? > > def find_point(pt): > return _hor_search(pt, random_obj) > > def _hor_search(pt, obj): > ... > object = ... > ... > if object meets some condition: > return object > else: > return _ver_search(pt, object) > > def _ver_search(pt, obj): > ... > object = ... > ... > if object meets some condition: > return object > else: > return _hor_search(pt, object) > > - > Suresh I found a simpler solution: get rid of recursive calls; using while loops. - Suresh From deets at nospam.web.de Wed Feb 14 08:33:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Feb 2007 14:33:36 +0100 Subject: replacing substrings within strings References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> <53gcsbF1sbe8oU1@mid.uni-berlin.de> <1171456059.848396.42270@m58g2000cwm.googlegroups.com> Message-ID: <53ghdgF1slkirU1@mid.uni-berlin.de> > Thats the same code. I was wondering if the string manipulation can be > done without an excursion into the list world. That's the price to pay for immutable strings. If you have to to lots of stuff like that, then keep things a list, and join only when you need the result as a string. Diez From sjmachin at lexicon.net Fri Feb 23 10:49:42 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Feb 2007 07:49:42 -0800 Subject: Finding non ascii characters in a set of files In-Reply-To: <1172244940.559402.17040@j27g2000cwj.googlegroups.com> References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> <1172244940.559402.17040@j27g2000cwj.googlegroups.com> Message-ID: <1172245781.973271.80100@m58g2000cwm.googlegroups.com> On Feb 24, 2:35 am, "John Machin" wrote: > On Feb 24, 2:12 am, "Peter Bengtsson" wrote: > > > On Feb 23, 2:38 pm, b... at yahoo.com wrote: > > > > Hi, > > > > I'm updating my program to Python 2.5, but I keep running into > > > encoding problems. I have no ecodings defined at the start of any of > > > my scripts. What I'd like to do is scan a directory and list all the > > > files in it that contain a non ascii character. How would I go about > > > doing this? > > > How about something like this: > > content = open('file.py').read() > > try: > > content.encode('ascii') > > except UnicodeDecodeError: > > print "file.py contains non-ascii characters" Sorry, I fell face down on the Send button :-) To check all .py files in the current directory, modify Peter's code like this: import glob for filename in glob.glob('*.py'): content = open(filename).read() maybe that UnicodeDecodeError should be ...Encode... and change the print statement to cater for filename being variable. If you have hundreds of .py files in the same directory, you'd better modify the code further to explicitly close each file. HTH, John From mail at timgolden.me.uk Mon Feb 26 12:10:08 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Feb 2007 17:10:08 +0000 Subject: [Fwd: Re: ez_setup.py] Message-ID: <45E31470.2040209@timgolden.me.uk> OK. He's solved it. For the historical record... Tim Golden wrote: > Nader Emami wrote: >> Tim Golden wrote: >>> Nader Emami wrote: >>>> Tim Golden wrote: >>>>> Nader Emami wrote: >>>>> >>>>>>>> How can do the second solution, (take off the home from Python >>>>>>>> path)? >>>>>>> >>>>>>> Depends on your setup. Since you're on *nix, I can't >>>>>>> test whether $HOME is automatically on sys.path (it >>>>>>> isn't on Win32). Are you running *in* /usr/people/emami? >>>>>>> If so, go somewhere else before you run ez_setup. Check >>>>>>> your PYTHONPATH env var; perhaps reset it before >>>>>>> running ez_setup. There are other more obscure possibilities >>>>>>> to do with things set in site.py but they're less likely. >>>>>>> >>>>>>> TJG >>>>>> I have a Linux and I don't have any PYTHONPTH variable, because >>>>>> if I run the next command it returns nothig: >>>>>> >>>>>> %env | grep -i pythonpath or >>>>>> %env | grep -i python >>>>> >>>>> I'm no expert here, but I believe that Linux is >>>>> case-sensitive, so you'd need to do: >>>>> >>>>> env | grep PYTHONPATH >>>>> >>>>> TJG >>>> 'grep' with 'i' option can catch both of them. I have done with >>>> capital letters also and the answer stays the same: >>>> %env | grep PYTHONPATH of %env | grep PTYTHON >>> >>> OK. Keep copying to the list, please. As I said, I'm not >>> a *nix person (and I'm running here on Windows) so you'll >>> get a more informed and wider audience from c.l.py. >>> >>> If there's no PYTHONPATH that means it's just down to >>> your system setup what goes on the path. Try (from >>> within the python interpreter): >>> >>> >>> import sys >>> for i in sys.path: >>> print i >>> >>> >>> >>> Do you see your home directory there? >>> >>> TJG >> This is the result of the code: >> /usr/people/emami/lib/python24.zip >> /usr/people/emami/lib/python2.4 >> /usr/people/emami/lib/python2.4/plat-linux2 >> /usr/people/emami/lib/python2.4/lib-tk >> /usr/people/emami/lib/python2.4/lib-dynload >> /usr/people/emami/lib/python2.4/site-packages > > (Sigh). Copying back to the list. > > So, are you running in /usr/people/emami when > you're call ez_setup? > > TJG > I have solved it. I have copied the "ez_setup.py" to my bin directory where "python" is installed and he hes done his job. From brian at sweetapp.com Tue Feb 6 15:00:48 2007 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 06 Feb 2007 21:00:48 +0100 Subject: XMLRPC Server In-Reply-To: References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> <45C868FB.909@sweetapp.com> Message-ID: <45C8DE70.9090807@sweetapp.com> Fredrik Lundh wrote: > well, if you're talking pure CGI, you need to start the interpreter, > import the required modules, connect to the database, unmarshal the > xml-rpc request, talk to the database, marshal the response, and shut > down, in less than 30 milliseconds. > > just importing the CGI module (or the database module) can take longer > than that... The original performance specification was "...receive up to 2000 calls per minute". I don't believe that means that a call has to be serviced in under 30ms (wall-clock time) but total CPU time would have to be <30ms in order to not fall behind under a constant 2000 requests/second load. So we can probably remove database connection and communication time (i.e. IO-bound components). Still, it's a lot tighter than I though it would be: % time python -c "import SimpleXMLRPCServer; import MySQLdb" real 0m0.144s user 0m0.046s sys 0m0.064s So it's already almost 4x too slow. But I'm running this on Ubuntu, running on VMWare on my 1.6GHz Pentium-M laptop. I would assume that a beefy server would do a lot better. Cheers, Brian From rkmr.em at gmail.com Wed Feb 21 00:12:10 2007 From: rkmr.em at gmail.com (mark) Date: Tue, 20 Feb 2007 21:12:10 -0800 Subject: getting a thread out of sleep In-Reply-To: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> Message-ID: On 20 Feb 2007 20:47:57 -0800, placid wrote: > On Feb 21, 3:08 pm, mark wrote: > > Right now I have a thread that sleeps for sometime and check if an > > event has happened and go back to sleep. Now instead I want the thread > > to sleep until the event has occured process the event and go back to sleep > > > > class eventhndler(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > def run(self): > > while True: > > time.sleep(SLEEPTIME) > > ''''do event stuff''' > > The way i would do this is by using an threading.Event ( > http://docs.python.org/lib/event-objects.html ) > > > > class eventhandler(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > self.event = threading.Event() > def run: > while True: > # block until some event happens > self.event.wait() > """ do stuff here """ > self.event.clear() > > > the way to use this is to get the main/separate thread to set() the > event object. Can you give an example of how to get the main threead to set teh event object? this is exactly what i wanted to do! thanks a lot! mark From gagsl-py at yahoo.com.ar Thu Feb 15 15:04:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 17:04:45 -0300 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 16:35:25 -0300, Neil Cerutti escribi?: > On 2007-02-15, Gabriel Genellina wrote: >> En Thu, 15 Feb 2007 13:37:19 -0300, Neil Cerutti >> escribi?: >> >>> On 2007-02-15, Gabriel Genellina wrote: >>>> En Wed, 14 Feb 2007 10:41:53 -0300, Neil Cerutti >>>> escribi?: >>>>> So the effect is that mutual recursion isn't actually any >>>>> harder. >>>> >>>> But some kind of language support is required in this case. At >>>> least I don't know how to handle mutual recursion (apart from >>>> inlining one function inside the other...). But I'm certainly >>>> not a "program transformation guru" (neither a novice!) so I >>>> would not be surprised if someone says it can be done... >>> >>> What happens (using the model of an imaginary virtual machine, >>> perhaps like the Python interpreter) is the following. >>> >>> A normal function call pushes a call-frame onto a stack. The >>> call-frame contains information necessary for returning from the >>> function, and usually a place to store its local variables and >>> parameters. >>> >>> A function called in "tail" position simply overwrites the >>> current call-frame with the new one instead of pushing it onto >>> the stack. >> >> This is the "kind of language support" menctioned. For tail >> recursion you don't require that support. > > I'm not sure what you mean. The above support is enough for tail > recursion, mutual recursion, and any other tail call to be > "optimized." I only want to say that tail *recursion* can be eliminated trivially transforming the code into a while loop, and that can be done by the programmer, and doesn't require compiler support. Head *recursion* can be eliminated too by using some storage as temporary stack, and that doesn't require external support either. Mutual recursion (and generic tail call elimination) require some sort of external support: one can't eliminate the call just by transforming the program. -- Gabriel Genellina From jjl at pobox.com Fri Feb 23 17:04:20 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 23 Feb 2007 22:04:20 GMT Subject: timeout in urllib.open() References: <7xabza829h.fsf@ruckus.brouhaha.com> Message-ID: <87r6sgy1i2.fsf@pobox.com> Paul Rubin writes: > Stefan Palme writes: > > is there a way to modify the time a call of > > > > urllib.open(...) > > > > waits for an answer from the other side? Have a tool which > > automatically checks a list of websites for certain content. The > > tool "hangs" when one of the contacted websites behaves badly and > > "never" answers... > > Other than by using socket timeouts, at least in Un*x, you can also > use signal.alarm. You can only have one OS-provided alarm pending at > a time, so if you want multiple overlapping timeouts you have to > schedule them yourself with a single alarm. Note that neither of these is guaranteed to time out urllib.open(), though usually they will. Another way to solve the underlying problem is not to try to time out the network operation(s) at all, but to use threads or non-blocking sockets (e.g. using Twisted). John From google at mrabarnett.plus.com Sat Feb 10 11:20:46 2007 From: google at mrabarnett.plus.com (MRAB) Date: 10 Feb 2007 08:20:46 -0800 Subject: Glob returning an empty list when passed a variable In-Reply-To: References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: <1171124446.031069.256420@j27g2000cwj.googlegroups.com> On Feb 10, 8:32 am, Steve Holden wrote: > Steven D'Aprano wrote: > > On Fri, 09 Feb 2007 14:15:51 +0000, Steve Holden wrote: > > >> area_name_string = '*% s*' % (Area_name) > > >> Interesting, I never realised until now that you can have spaces between > >> the percent sign and th format effector. > > > Space is one of the flags. From the docs: > > > The conversion flag characters are: > > > Flag Meaning > > # The value conversion will use the ``alternate form'' (where defined > > below). > > 0 The conversion will be zero padded for numeric values. > > - The converted value is left adjusted (overrides the "0" conversion if > > both are given). > > (a space) A blank should be left before a positive number (or empty > > string) produced by a signed conversion. > > + A sign character ("+" or "-") will precede the conversion (overrides a > > "space" flag). > > >http://docs.python.org/lib/typesseq-strings.html > > >>> "% s" % 'banana' > 'banana' > >>> "% s" % 1 > '1' > >>> "% s" % -1 > '-1' > >>> > [snip] I've just tried it and it works for the "d" format but not the "s" format: >>> "%d" % 1 '1' >>> "%+d" % 1 '+1' >>> "% d" % 1 ' 1' From comechao at gmail.com Fri Feb 9 13:43:00 2007 From: comechao at gmail.com (Bastos) Date: 9 Feb 2007 10:43:00 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1171046580.351974.108150@v33g2000cwv.googlegroups.com> On Feb 8, 10:03 am, "Srikanth" wrote: > Yes, > > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. > > Thanks, > Srikanth Gedit and some plugins, definitely. From orsenthil at gmail.com Wed Feb 28 03:32:53 2007 From: orsenthil at gmail.com (Phoe6) Date: 28 Feb 2007 00:32:53 -0800 Subject: How can I disable a device in windows using python In-Reply-To: References: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> Message-ID: <1172651573.437089.137630@s48g2000cws.googlegroups.com> On Feb 27, 2:21 pm, Duncan Booth wrote: > > Hi all, > > I am trying to disable it programmatic using python. I checked python > > wmi and i could not find ways to disable/enable, (listing is however, > > possible). > > > Where should I look for to enable/disable devices in python. > > Assuming you mean windows: > > If you don't mind doing it by spawning an external program try > downloading devcon.exe from Microsoft's website > (http://support.microsoft.com/kb/311272). Thanks for the reply, this is very helpful. Thanks, Senthil From dustin.getz at gmail.com Sun Feb 25 20:12:19 2007 From: dustin.getz at gmail.com (dustin.getz at gmail.com) Date: 25 Feb 2007 17:12:19 -0800 Subject: modifying a list while iterating through Message-ID: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> consider the following working loop where Packet is a subclass of list, with Packet.insert(index, iterable) inserting each item in iterable into Packet at consecutive indexes starting at index. i=0 while(i<1172561344.290126.191530@h3g2000cwc.googlegroups.com> Message-ID: <3c5Fh.3664$Tg7.2156@trnddc03> OK, let me approach this from a new direction. Suppose I define a class that behaves I think as I stipulated:: class NothingNew: a = 0 def __init__(self): self.b = 1 self.initialized = True def __setattr__(self, attr, val): if not hasattr(self,'initialized') or hasattr(self, attr): self.__dict__[attr] = val else: raise ValueError After adding some documentation, what are the downsides? (Assume a small project where everyone knows this has been done to the NothingNew class.) Anyone who wants the behavior can keep it. Anyone who wants to add stuff to an object just has to delete its "initialized" attribute. Anyone who want other behavior defined in this or a derived class can just override __init__. Does this address most of the (oddly passionate) objections? Thanks, Alan Isaac From donn at u.washington.edu Fri Feb 9 15:47:32 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 09 Feb 2007 12:47:32 -0800 Subject: os.popen and broken pipes References: Message-ID: In article , Philipp Pagel wrote: > Antoon Pardon wrote: > > On 2007-02-09, Philipp Pagel wrote: > > > for filename in file_list: > > > file = os.popen('uncompress -c '+filename, 'r') > > > do_something(file) > > > file.close() > > > > > > This works fine for some files but results in > > > > > > 'write error onstdout: Broken pipe' > > > As far as I can tell, your do_something doesn't consume the entire file. > > So you close the file prematurly, which results in the uncompress/zcat > > program trying to write to a pipe that is closed on the otherside, > > giving you the above message. > > You are right: some of the files do not fulfill certain > critereia causing so_somehting() to return before the entire file is > processed. Most programming environments don't have this problem, though. If you like, your program can undo what Python does: signal.signal(signal.SIGPIPE, signal.SIG_DFL) for filename in file_list: ... Then it will work as if you had written it in C, or awk or whatever. Donn Cave, donn at u.washington.edu From simone.leo at gmail.com Fri Feb 9 09:55:32 2007 From: simone.leo at gmail.com (Tekkaman) Date: 9 Feb 2007 06:55:32 -0800 Subject: unique elements from list of lists In-Reply-To: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> References: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> Message-ID: <1171032932.556577.185640@h3g2000cwc.googlegroups.com> Thanks everybody! Azrael: your suggestions involve python-level membership testing and dummy list construction just like my uniter3 example, so I'm afraid they would not go any faster. There's no built-in sequence flattening function that I know of btw. bearophile: your implementation is very similar to my uniter2 (subsequent set unions) but without the additional lambda def overhead, and in fact it goes faster. Not faster than uniter though. Peter: your solution is the fastest, removing the explicit for loop resulted in a 30% speed gain. Looks like using set() is a must. -- Simone From michael.tiller at gmail.com Tue Feb 27 07:28:16 2007 From: michael.tiller at gmail.com (michael.tiller at gmail.com) Date: 27 Feb 2007 04:28:16 -0800 Subject: ANN: PyDSTool now compatible with numpy 1.0.1, scipy 0.5.2 and 64-bit CPUs. In-Reply-To: <2ff9b$45db652f$d443bb3a$29705@news.speedlinq.nl> References: <2ff9b$45db652f$d443bb3a$29705@news.speedlinq.nl> Message-ID: <1172579296.156674.203150@j27g2000cwj.googlegroups.com> On Feb 20, 4:16 pm, Stef Mientki wrote: > Sounds GREAT ! > thank you ! > I just took a quick look, > the comparison to SimuLink looks good, > now if someone could make a comparison with Modelica;-) > > cheers, > Stef Mientki As far as I can tell, PyDSTool provides some basic symbolic math capabilities sufficient to formulate systems of equations that can then be simulated. The symbolic capability seems to be mainly to allow for analytical Jacobian calculation (presumably for backward differentiation algorithms, etc). Someone feel free to correct me if I'm wrong. This is all quite useful and it is implicitly included in Modelica but may important aspects of Modelica are missing. For example, Modelica includes inheritance (to facilitate reuse), polymorphism (to substitute one implementation of a component for another), a strong types system (to ensure safety and robustness), a meta-data infrastructure including standardized metadata for documentation and graphical representation, connectors to define interactions between components, an expansive standard library and support for numerous modeling formalisms both continuous, discrete and mixed systems of DAEs (e.g. block diagrams, acausal modeling, state charts, petri nets, ...). My sense is that perhaps PyDSTool is attempting to leverage some of these aspects directly from Python (e.g. inheritance). I am a fan of both Python and Modelica but when it comes to the kind of modeling work I do I prefer the more "static" approach to type checking that Modelica uses (of course that is just a personal preference). -- Mike From gagsl-py at yahoo.com.ar Sun Feb 11 21:11:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 23:11:37 -0300 Subject: compound statement from C "?:" References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> <1171232208.939808.33890@j27g2000cwj.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 19:16:49 -0300, Holger escribi?: >> >> if n == 1: >> >> print "I saw a car" >> >> else: >> >> print "I saw %d cars" % n > > Personally I don't like the if-else approach because of the don't- > repeat-yourself philosophy > >> D'accord. Did I mention that, as a "for fun" approach, "s" * (n != 1) is >> quite clever :-) > I like this one :-) > >> print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) > And this one. I presume all of this is only used as an example on using expressions. In any application with any chances of being i18n, the only viable way is the first one. Doing algebra on phrases is a no-no. -- Gabriel Genellina From gagsl-py at yahoo.com.ar Thu Feb 1 04:34:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 06:34:32 -0300 Subject: retrbinary ! how does it work ? References: <1170321454.210348.91370@a75g2000cwd.googlegroups.com> Message-ID: En Thu, 01 Feb 2007 06:17:34 -0300, blancmunier1 at yahoo.FR escribi?: > I'd like to copy files with FTP protocol in a subdirectory. > So far, my code look like that : > > import ftplib > session = ftplib.FTP('222.33.44.55','usr','pwd') > session.cwd('/') > files = session.nlst() > for file in files: > session.retrbinary('RETR '+file, open(file, 'wb').write) (hmm, using file as a variable name is not a good idea, it hides the builtin type of the same name) > It does work but the files are copied in the same directory as the > python file. And I would like to copy the file in this relative > directory : ../archives > For example, if the python file is in this directory : C:\SCOR\Bat\, > the FTP files gotta be in C:\SCOR\archives\ . Let's say, if the file name were "abc.txt", you should open the output using this name: '../archives/abc.txt' To build a path from its components, use os.path.join So, replace open(file,... above, with open(os.path.join('../archives',file),... -- Gabriel Genellina From sjmachin at lexicon.net Sun Feb 11 20:16:34 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 17:16:34 -0800 Subject: No module named pyExcelerator Error In-Reply-To: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> References: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> Message-ID: <1171242994.102776.69730@s48g2000cws.googlegroups.com> On Feb 12, 11:55 am, "susan" wrote: > Hi, > I'm new of Python, and this problem stucked me whole day but can't be > solved. > > I use python 2.4.3, which is download from cygwin packages. Is your Python installation working properly for you with other things, or is installing pyExcelerator the first thing that you have tried? > Then I > downloaded pyexcelerator-0.5.3a, unzip it, Is that "5" a typo? The latest version is 0.6.3a > > $ python ./pyExcelerator/setup.py install Try this instead: $ cd pyExcelerator $ python ./setup.py install i.e. do what the pyExcelerator README tells you to do. """ 0x0003. Installation. -------------------- As usually: python ./setup.py install """ This may make a positive difference; it can't be worse. HTH, John From sturlamolden at yahoo.no Thu Feb 22 13:41:27 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 22 Feb 2007 10:41:27 -0800 Subject: export an array of floats to python In-Reply-To: <1172169365.508476.279360@a75g2000cwd.googlegroups.com> References: <1172169365.508476.279360@a75g2000cwd.googlegroups.com> Message-ID: <1172169687.374464.83390@h3g2000cwc.googlegroups.com> On Feb 22, 7:36 pm, "sturlamolden" wrote: > npy_int dim = {480, 640}; /* whatever the size of your data, in C- > order */ oops... npy_int dim[] = {480, 640}; From steve at holdenweb.com Thu Feb 15 06:53:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 11:53:45 +0000 Subject: f---ing typechecking In-Reply-To: References: Message-ID: James Stroud wrote: > skip at pobox.com wrote: >> Concatenating tuples and lists seems logical if you think of tuples as >> sequences. If you think of them more like Pascal records or C structs >> instead (I believe that's Guido's perspective on tuples) then it makes no >> sense at all. >> >> Skip >> > > Then iterating over them makes no sense? > Given Guido's assertions about the nature of the tuple, no it doesn't. But I seriously doubt that 3.0 will remove the iterable interface from tuples, despite its impurity. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From fdu.xiaojf at gmail.com Wed Feb 7 01:01:43 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Wed, 07 Feb 2007 14:01:43 +0800 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: <45C935B1.60606@gmail.com> References: <45C935B1.60606@gmail.com> Message-ID: <45C96B47.6020106@gmail.com> fdu.xiaojf at gmail.com wrote: > Hi all, > > I'm interested in Parallel Python and I learned from the website of > Parallel Python > that it can run on SMP and clusters. But can it run on a our muti-CPU > server ? > We are running an origin3800 server with 128 CPUs. > > Thanks. > I have tested that at least it could run sum_primes.py on our server. But it seems Parallel Python just launch one python process for each job, and if I let it use 12 CPUs for 8 jobs, Parallel Python launches 12 python processes, 4 of which just sleep until all 8 jobs are done. From jura.grozni at gmail.com Sat Feb 10 23:25:04 2007 From: jura.grozni at gmail.com (azrael) Date: 10 Feb 2007 20:25:04 -0800 Subject: unique elements from list of lists In-Reply-To: <1171032932.556577.185640@h3g2000cwc.googlegroups.com> References: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> <1171032932.556577.185640@h3g2000cwc.googlegroups.com> Message-ID: <1171167904.468278.316710@a75g2000cwd.googlegroups.com> no heart feelings. i was just throwing ideas. no time to testing it. On Feb 9, 3:55 pm, "Tekkaman" wrote: > Thanks everybody!Azrael: your suggestions involve python-level membership testing and > dummy list construction just like my uniter3 example, so I'm afraid > they would not go any faster. There's no built-in sequence flattening > function that I know of btw. > bearophile: your implementation is very similar to my uniter2 > (subsequent set unions) but without the additional lambda def > overhead, and in fact it goes faster. Not faster than uniter though. > Peter: your solution is the fastest, removing the explicit for loop > resulted in a 30% speed gain. Looks like using set() is a must. > > -- Simone From steven.bethard at gmail.com Tue Feb 20 14:46:57 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 20 Feb 2007 12:46:57 -0700 Subject: builtin set literal In-Reply-To: <1171988959.628359.260710@l53g2000cwa.googlegroups.com> References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <1171988959.628359.260710@l53g2000cwa.googlegroups.com> Message-ID: Steven Bethard: > While Python 3.0 is not afraid to break backwards > compatibility, it tries to do so only when there's a very substantial > advantage. bearophileHUGS at lycos.com wrote: > I understand, but this means starting already to put (tiny) > inconsistencies into Python 3.0... Well, there's going to be an inconsistency one way or another: Lists: [1, 2] [1] [] Dicts: {1:2, 2:1} {1:2} {} Sets: {1, 2} {1} set() Note that if we used {} for the empty set and {:} for the empty dict, then sets would be consistent, but dicts would be inconsistent. And if you're really worried about consistencies, take a look at the current state of tuples: 1, 2 1, () There's just not an obvious *right* answer here, so it's better to stick with the backwards compatible version. STeVe From mizipzor at gmail.com Sun Feb 4 16:12:45 2007 From: mizipzor at gmail.com (Mizipzor) Date: 4 Feb 2007 13:12:45 -0800 Subject: "Subscribing" to topics? In-Reply-To: References: <5aoxh.7440$gJ1.6708@newsfe17.lga> <1170618799.354069.327210@h3g2000cwc.googlegroups.com> Message-ID: <1170623565.106773.263940@m58g2000cwm.googlegroups.com> On Feb 4, 9:55 pm, Toby A Inkster wrote: > You discovered wrong -- Google does not provide a free newsserver. They no > doubt *have* several newsservers, but don't provide direct access to them > either free, or for a fee. They only provide a web interface to access the > contents of their newsservers, with a fraction of the features that a real > newsreader would. Hehe, it has all the features I knew existed in a newsreader, except this "subscribe to topic" thing Im looking for. > You seem to already have a newsreader -- you're using Opera, which > includes a fairly good one, hidden away in the Hotlist/Panels/whatever- > they're-calling-it-today. Other newsreaders I'd recommend are PAN and > Forte Agent. Did I mention I use Opera? I do anyway, it was just days ago I made the switch from Firefox. I found their mail-/newsreader client but since I didnt know what to type in the server settings of the newsreader, my search continued. > So you just need a server. "pubnews.gradwell.net" still seems to exist -- > it's free. Alternatively, "news.individual.net" offers a good service for > a fairly low yearly cost. So should "pubnews.gradwell.net" go in both Incoming and Outgoing server fields? From newsuser at stacom-software.de Fri Feb 23 06:33:26 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Fri, 23 Feb 2007 12:33:26 +0100 Subject: What is bad with "Relative imports" Message-ID: Hi, PyLint says that "Relative imports" ... are worth to be warned . And I ask myself why? ----------------- Example directory structure --------- Sound/ Top-level package __init__.py Initialize the sound package Utils/ Subpackage __init__.py iobuffer.py errors.py misc.py ... Formats/ Let's say in misc.py exist the class Player(). What could be bad to expose it in Utils.__init__() like: ------------------ __init__.py ------------------------- import misc # provoke PyLint warning Player = misc.Player ... -------------------------------------------------------- with Sound.Utils.Player() ?? Thaks for your experience and comments Regards Alexander From charleshixsn at earthlink.net Fri Feb 23 15:53:59 2007 From: charleshixsn at earthlink.net (Charles D Hixson) Date: Fri, 23 Feb 2007 12:53:59 -0800 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) Message-ID: <45DF5467.6000803@earthlink.net> I'm sure I've read before about how to construct prototypes in Python, but I haven't been able to track it down (or figure it out). What I basically want is a kind of class that has both class and instance level dict variables, such that descendant classes automatically create their own class and instance level dict variables. The idea is that if a member of this hierarchy looks up something in it's local dict, and doesn't find it, it then looks in the class dict, and if not there it looks in its ancestral dict's. This is rather like what Python does at compile time, but I want to do it at run time. I'm sure I've seen how to do it...but have no idea where, or what it was called, or when (probably around the time Prothon was being discussed, as I have the idea of prototype associated with it for no clear reason). From andrzej.s at gazeta.pl Tue Feb 27 18:06:39 2007 From: andrzej.s at gazeta.pl (andrew_s) Date: Wed, 28 Feb 2007 00:06:39 +0100 Subject: database without installation again Message-ID: Hi! I'm looking for any database which I could use without need of instalation. I've read some threads here but I couldn't find any complete answer. On my ISP's server I can use Python throu cgi only. There is Python 2.4.3 and it has only standard library modules and no possibility to oficially install anything else. This version has embedded Berkeley DB (bsddb) and it could be OK for storing data only, but I need a possibility to use simple selects with group by and aggregates, which I think are not supported by bsddb. SQLite could be good choice, but unfortunately it's included in standard Python library from version 2.5. Any ideas? Maybe is it possible to "install" by myself something like SQLite or MySQLdb in my cgi-bin directory? I've tried it putting files from MySQLdb module, but there was errors with missing libssl.so or sth. I think, the best solution would be db stored in binary file with interface in based on standard Python library, but is there anything like that?? TIA! -- Andrews From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Feb 16 13:45:26 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 16 Feb 2007 19:45:26 +0100 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <53mce6F1sepr5U2@mid.individual.net> exhuma.twn wrote: > * Sockets > Advantage: Supported per se in nearly every programming > language without even the need to install additional packages > Disadvantage: Lot's of code to write, Who's Lot? :) No, seriously. Why would you think that it's much to write? It can, especially using Python, be as easy as using a file. > and it's kind of silly to communicate via TCP/IP if the > processes run on the same machine. Why? - Do you worry about CPU cycles, memory, ...? - Who forces you to use TCP? > Supposing both processes are written in Python, is there any other > way to achieve this? It depends on what those processes need to share. What you need can range from a simple unix socket connection to a full-fledged SQL database server. Regards, Bj?rn -- BOFH excuse #301: appears to be a Slow/Narrow SCSI-0 Interface problem From stefan.rank at ofai.at Mon Feb 5 02:12:06 2007 From: stefan.rank at ofai.at (Stefan Rank) Date: Mon, 05 Feb 2007 08:12:06 +0100 Subject: sgmllib bug in Python 2.5, works in 2.4. In-Reply-To: References: Message-ID: <45C6D8C6.4030609@ofai.at> on 05.02.2007 03:49 John Nagle said the following: > (Was prevously posted as a followup to something else by accident.) > > I'm running a website page through BeautifulSoup. It parses OK > with Python 2.4, but Python 2.5 fails with an exception: > > Traceback (most recent call last): > File "./sitetruth/InfoSitePage.py", line 268, in httpfetch > self.pagetree = BeautifulSoup.BeautifulSoup(sitetext) # parse into tree form > File "./sitetruth/BeautifulSoup.py", line 1326, in __init__ > BeautifulStoneSoup.__init__(self, *args, **kwargs) > File "./sitetruth/BeautifulSoup.py", line 973, in __init__ > self._feed() > File "./sitetruth/BeautifulSoup.py", line 998, in _feed > SGMLParser.feed(self, markup or "") > File "/usr/lib/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib/python2.5/sgmllib.py", line 291, in parse_starttag > self.finish_starttag(tag, attrs) > File "/usr/lib/python2.5/sgmllib.py", line 340, in finish_starttag > self.handle_starttag(tag, method, attrs) > File "/usr/lib/python2.5/sgmllib.py", line 376, in handle_starttag > method(attrs) > File "./sitetruth/BeautifulSoup.py", line 1416, in start_meta > self._feed(self.declaredHTMLEncoding) > File "./sitetruth/BeautifulSoup.py", line 998, in _feed > SGMLParser.feed(self, markup or "") > File "/usr/lib/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib/python2.5/sgmllib.py", line 285, in parse_starttag > self._convert_ref, attrvalue) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: ordinal > not in range(128) > > The code that's failing is in "_convert_ref", which is new in Python 2.5. > That function wasn't present in 2.4. I think the code is trying to > handle single quotes inside of double quotes, or something like that. > > To replicate, run > > http://www.bankofamerica.com > or > http://www.gm.com > > through BeautifulSoup. > > Something about this code doesn't like big companies. Web sites of smaller > companies are going through OK. > > Also reported as a bug: > > [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 > > > John Nagle Hi, I had a similar problem recently and did not have time to file a bug-report. Thanks for doing that. The problem is the code that handles entity and character references in SGMLParser.parse_starttag. Seems that it is not careful about unicode/str issues. My quick'n'dirty workaround was to remove the offending char-entity from the website before feeding it to Beautifulsoup:: text = text.replace('®', '') # remove rights reserved sign entity cheers, stefan From wdraxinger at darkstargames.de Tue Feb 20 08:35:25 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Tue, 20 Feb 2007 14:35:25 +0100 Subject: Sorting directory contents Message-ID: H folks, I got, hmm not really a problem, more a question of elegance: In a current project I have to read in some files in a given directory in chronological order, so that I can concatenate the contents in those files into a new one (it's XML and I have to concatenate some subelements, about 4 levels below the root element). It all works, but somehow I got the feeling, that my solution is not as elegant as it could be: src_file_paths = dict() for fname in os.listdir(sourcedir): fpath = sourcedir+os.sep+fname if not match_fname_pattern(fname): continue src_file_paths[os.stat(fpath).st_mtime] = fpath for ftime in src_file_paths.keys().sort(): read_and_concatenate(src_file_paths[ftime]) of course listdir and sorting could be done in a separate function, but I wonder if there was a more elegant approach. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From exarkun at divmod.com Fri Feb 16 10:27:07 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 16 Feb 2007 10:27:07 -0500 Subject: Pep 3105: the end of print? In-Reply-To: Message-ID: <20070216152707.25807.1058387555.divmod.quotient.23949@ohm> On Sat, 17 Feb 2007 02:17:23 +1100, Steven D'Aprano wrote: >On Fri, 16 Feb 2007 09:49:03 -0500, Jean-Paul Calderone wrote: > >> On Sat, 17 Feb 2007 01:32:21 +1100, Steven D'Aprano >>> [snip] >>> >>>I don't think that follows at all. print is only a problem if you expect >>>your code to work under both Python 2.x and 3.x. I wouldn't imagine >>>that many people are going to expect that: I know I don't. >> >> I think some people are confused that the language "Python 3.x" has "Python" >> in its name, since there is already a language with "Python" in its name, >> with which it is not compatible. > >There is no language "Python 3" -- yet. We're still all guessing just >how compatible it will be with Python 2. > >To be precise, there is an experimental Python 3, but the specifications >of the language are not fixed yet. > >As for the name... big deal. C and C++ and Objective C are completely >different languages. Fortran 77 and Fortran 90 aren't exactly the same; >nobody expects the same code to run unmodified on Forth 77 and FigForth, >or any of another three dozen varieties of Forth. > >And dare I mention Java and Javascript? > I was just pointing out that some people might be confused. I didn't make any judgement about that fact. You seem to be suggesting that because there are other confusing things, it's okay for Python to be confusing too. I'm not making any judgements about that, either. >Even in the Python world, nobody expects to run the same code base under >C Python and Jython and IronPython and PyPy. > I wonder if the fact that Jython and IronPython can't run most Python programs is one of the reasons they are generally only used in special circumstances? PyPy isn't finished yet, however, it _is_ an /explicit/ goal of PyPy to be compatible with CPython, so it doesn't really belong on that list. Jean-Paul From jjl at pobox.com Sat Feb 3 10:00:20 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 03 Feb 2007 15:00:20 GMT Subject: urllib2 hangs "forever" where there is no network interface References: <1170315718.860222.160810@k78g2000cwa.googlegroups.com> <1170353063.024553.10060@s48g2000cws.googlegroups.com> Message-ID: <871wl7b828.fsf@pobox.com> (I'm having news trouble, sorry if anybody sees a similar reply three times...) "dumbkiwi" writes: > On Feb 2, 5:02 am, j... at pobox.com (John J. Lee) wrote: > > "dumbkiwi" writes: [...] > > > If there is no network interface, urllib2 hangs for a very long time > > > before it raises an exception. I have set the socket timeout with > > > socket.setdefaulttimeout(), however, where there is no network > > > interface, this seems to be ignored - presumably, because without a > > > network interface, there is nothing for the socket module to interact > > > with. [...] > > Presumably Windows? (Unix systems almost always have at least a > > loopback interface) > > > > John > > Sorry, I should have been more specific. The network interfaces are > up - ie lo and eth1, it's where the wireless connection has dropped > out. The underlying problem is that Python's socket timeout is implemented using select() or poll(). Those system calls only allow timing out activity on file descriptors (e.g. sockets). The problem you're seeing is caused by getaddrinfo() blocking for a long time, and that function doesn't involve file descriptors. The problem should really be fixed at the C level (in Modules/socketmodule.c), using something like alarm() or a thread to apply a timeout to getaddrinfo() calls. > Is the best solution to test for a wireless connection through / > proc before trying to download data? That may be a good practical solution. Another workaround that might be useful is to do your DNS lookups only once, then use only IP addresses. John From robert at dollinger.it Fri Feb 9 02:11:15 2007 From: robert at dollinger.it (Robert Dollinger) Date: Fri, 09 Feb 2007 08:11:15 +0100 Subject: Win98 - exceptions.IOError: (13, 'Permission denied') Message-ID: Hi to everyone, I have a Service, that runs on a WinXP machine. The service read a file on a Win98 machine and write the content in a file on the WinXP machine. After tree times I get the error message exceptions.IOError: (13, 'Permission denied'). The following things I have already tested: - The file on Win98 machine could be deleted, so the file is closed correctly. - Stop an restart the service on WinXP, will have no effect - Reboot the Win98 machine solve the problem for three times. So I have the same issue explained above. - I have changed the intervall from 5 sec to 1 minute. After ther first time I get the error message. - Using a Win2000 or WINXP machine instead of the Win98 machine. That works. But unfortunatly the PC to access is a Win98 and I have no influence to decide for upgrade. I can't figure out, what's the problem. This is the code to simulate my actual problem: # -*- coding: iso-8859-1 -*- import win32serviceutil import win32service import win32event import pywintypes import win32file import win32pipe import win32api import win32con import thread import ntsecuritycon import os import sys class MyService(win32serviceutil.ServiceFramework): """NT Service.""" _svc_name_ = "TCTest" _svc_display_name_ = "TCTest" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.stop_event = win32event.CreateEvent(None, 0, 0, None) self.overlapped = pywintypes.OVERLAPPED() self.overlapped.hEvent = win32event.CreateEvent(None,0,0,None) self.thread_handles = [] def SvcDoRun(self): import servicemanager servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '') ) while 1: datei = open(r'\\ipcwin98\test\test.txt', 'r') log = open(r'c:\log.txt', 'a') log.write(datei.read()) datei.close() log.close() if win32event.WaitForSingleObject(self.stop_event, 5000) == win32event.WAIT_OBJECT_0: break servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '') ) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.stop_event) if __name__ == '__main__': win32serviceutil.HandleCommandLine(MyService) Thanks in advanced for your help. bye Robert From JStoneGT at aol.com Tue Feb 13 01:56:21 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Tue, 13 Feb 2007 01:56:21 EST Subject: Newbie question about Class Message-ID: I'm reading the book of "Dive into Python" and got these code pieces: class UserDict: def __init__(self, dict=None): self.data = {} if dict is not None: self.update(dict) My question is,for the statement of: if dict is not None: self.update(dict) Why it's not this one below? if dict is not None: self.data.update(dict) Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.daniels at acm.org Mon Feb 19 01:23:32 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 18 Feb 2007 22:23:32 -0800 Subject: What is more efficient? In-Reply-To: References: Message-ID: <12tighe7684l667@corp.supernews.com> Karlo Lozovina wrote: > Let's say I have a class with few string properties and few integers, and > a lot of methods defined for that class. > > Now if I have hundreds of thousands (or even more) of instances of that > class - is it more efficient to remove those methods and make them > separate functions, or it doesn't matter? > > Thanks... > You'd do best to define the instance variable names in __slots__, and be sure to inherit from object. The methods don't matter (they all hang off the class anyway). The __slots__ will save you one reference per object for the __dict__. -- --Scott David Daniels scott.daniels at acm.org From ullrich at math.okstate.edu Sat Feb 24 06:30:00 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sat, 24 Feb 2007 05:30:00 -0600 Subject: CSV(???) References: Message-ID: On 23 Feb 2007 19:13:10 +0100, Neil Cerutti wrote: >On 2007-02-23, David C Ullrich wrote: >> Is there a csvlib out there somewhere? >> >> And/or does anyone see any problems with >> the code below? >> >> [...] >> >> (Um: Believe it or not I'm _still_ using python 1.5.7. So >> comments about iterators, list comprehensions, string methods, >> etc are irrelevent. Comments about errors in the algorithm >> would be great. Thanks.) > >Two member functions of indexedstring are not used: next and >lookahead. __len__ and __getitem__ appear to serve no real >purpose. Hey, thanks! I didn't realize that using an object with methods that were never called could cause an algorithm to fail... shows how much I know. (Seriously, all I really wanted to know was whether anyone noticed something I overlooked, so that parsecsvline(csvline(fields)) might under some condition not come out the same as fields...) >> def parsecsvline(csvline): >> """Inverts csvline(). Assumes csvline is valid, ie >> is something as returned by csvline(); output undefined >> if csvline is in invalid format""" >> >> s = indexedstring(csvline) >> res = [] >> >> while not s.eos(): >> res.append(s.getfield()) >> >> return res > >You'll be happy to know that iterators and list comprehensions >will make your code better after you upgrade. ;-) Uh, thanks again. You're right, knowing that makes me so happy I could just burst. >In the meantime, I think your (relative lack of) error handling >is OK. GIGO, as they say (garbage in, garbage out). _I_ don't think it's ok. But (i) the code I posted was not supposed to be the final version! It was a preliminary version, posted hoping that someone would notice any errors in the _algorithm_ that existed. (ii) in the intended application parsecsvline will only be applied to the output of csvline, so if the former is indeed a left inverse of the latter there should be no error unless something else has already gone wrong elsewhere. Not that that makes it ok... ************************ David C. Ullrich From parvini_navid at yahoo.com Mon Feb 12 08:37:52 2007 From: parvini_navid at yahoo.com (Navid Parvini) Date: Mon, 12 Feb 2007 05:37:52 -0800 (PST) Subject: Exception Message-ID: <854284.81743.qm@web54505.mail.yahoo.com> Dear All, Would you please tell me if there is a pysignal or method that called when an exception is occurred? (I don't want to use "try" method) Thank you in advance. Navid --------------------------------- Food fight? Enjoy some healthy debate in the Yahoo! Answers Food & Drink Q&A. -------------- next part -------------- An HTML attachment was scrubbed... URL: From S.Mientki-nospam at mailbox.kun.nl Sun Feb 4 08:41:53 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 04 Feb 2007 14:41:53 +0100 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: <1170592091.240194.174070@a34g2000cwb.googlegroups.com> References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> <1170592091.240194.174070@a34g2000cwb.googlegroups.com> Message-ID: Inca wrote: >> Through "My computer" | properties | advanced | Environment Variables" >> you have to reboot. > > The best overall solution is the one where you modify sys.path to add > your own custom paths, I agree, specially in my situation that is the best solution. however Jussi is right in that you do not need > to reboot. You have to restart any applications that relies on using > the updated environment variables (in your case the Delphi program): > > http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/environment_variables.mspx?mfr=true > I think the problem comes from the Delphi interface, both Idle and PyScripter reflect a change PYTHONPATH after a restart. But my Delphi program needs a reboot :-( I'll ask around in the Python4Delphi newsgroup. cheers, Stef Mientki From jonc at icicled.net Sun Feb 4 15:05:26 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sun, 4 Feb 2007 14:05:26 -0600 Subject: It is good to blow up a marketplace full of people buying and selling food In-Reply-To: <_Jqxh.46014$jA.34196@bignews1.bellsouth.net> References: <1170611125.519656.144410@m58g2000cwm.googlegroups.com> <_Jqxh.46014$jA.34196@bignews1.bellsouth.net> Message-ID: <200702041405.26753.jonc@icicled.net> Frank, Could you please try and stick to discussing python related subjects on this mailing list? - Jonathan From stargaming at gmail.com Mon Feb 19 11:19:24 2007 From: stargaming at gmail.com (Stargaming) Date: Mon, 19 Feb 2007 17:19:24 +0100 Subject: (beginners question) howto set self.field4.subfield8='asdf'? In-Reply-To: <1171885138.150935.207890@h3g2000cwc.googlegroups.com> References: <1171877794.747825.294890@t69g2000cwt.googlegroups.com> <1171885138.150935.207890@h3g2000cwc.googlegroups.com> Message-ID: openopt at ukr.net wrote: > Thx > but is there any simpleir way, if using not class, but just struct (or > something like that, MATLAB equivalent for that one)? Use this:: >>> A = type('', (), {}) >>> a = A() >>> a <__main__. object at 0x009E8490> >>> a.foo = 42 >>> a.foo 42 But perhaps using this (with a better name) would be more sensible (according to readability):: >>> class B: pass ... >>> b = B() >>> b.foo = 42 >>> b.foo 42 > I'm thinking of rewriting some optimization solvers (non-smooth, > constrained, with (sub)gradients or patterns provided by user) to > Python and I don't know currently is it possible to easy convert > things like > prob = []; > prob.advanced.ralg.hs = 1 (so in this line all subfields are > generating automatically in MATLAB or Octave) Perhaps something like this would be suitable:: >>> class Autocreating(object): ... def __getattr__(self, attr): ... if hasattr(self, attr) ... setattr(self, attr, Autocreating()) ... return getattr(self, attr) ... >>> a = Autocreating() >>> a.foo = 42 >>> a.foo 42 >>> a.hello.world = 23 >>> a.hello <__main__.Autocreating object at 0x...> >>> a.hello.world 23 But this is perhaps not a good way because it's way too implicite. > I have huge amount of such lines, and implementing separate class for > each one is unreal. You don't have to implement a separate class for *each one*. Use one class for every attribute, you can reuse it. But perhaps something like a dict is better for your purposes, anyways. HTH, Stargaming From etatoby at gmail.com Sat Feb 24 10:39:53 2007 From: etatoby at gmail.com (Toby) Date: 24 Feb 2007 15:39:53 GMT Subject: Endianness conversion Message-ID: <45e05c49$0$20809$5fc30a8@news.tiscali.it> As part of a program I'm writing, I need to save to disk big amounts of data (hundreds of MB, in 8kB chunks) swapping every couple of bytes. I obviously cannot do it in a Python loop. Is there a function I could use in the standard library, or do I have to write my own C extension? Toby From laurent.pointal at wanadoo.fr Sat Feb 17 06:12:12 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sat, 17 Feb 2007 12:12:12 +0100 Subject: WHAT IS THIS? References: Message-ID: <45d6e238$0$27406$ba4acef3@news.orange.fr> Captain wrote: > Just bought a new PC with Windows XP Media Edition. I have two entries in > the "Add or Remove Programs" section of Control Panel, but there is no > corresponding item in the Start Menu. One entry says: Python 2.2.3 and > the > other says: Python 2.2 pywin32 extensions (build203).. The size for each > is > 29.28mb. I gather Python is a programming language, but I am wondering > why > it was installed on my PC, and is it safe to remove it? I have no > intention > of learning the program. Thanks in advance DONT USE UPPERCASE TITLE (thanks) Maybe your PC assembler installed some software which need Python... so, before removing it, ask the vendor. You may too search for *.py *.pyc *.pyo files in directories other than Python, so identify software which may need Python. And you may searchfor extra-libraries in the lib/site-packages subdirectory of Python directory. A+ From llansteffan at hotmail.com Thu Feb 22 08:04:29 2007 From: llansteffan at hotmail.com (justme) Date: 22 Feb 2007 05:04:29 -0800 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? In-Reply-To: <1172144943.794384.73270@s48g2000cws.googlegroups.com> References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> Message-ID: <1172149469.728416.56940@p10g2000cwp.googlegroups.com> On 22 Feb, 11:49, open... at ukr.net wrote: > I don't know to which forum should I post the message > I hope someone related to the Python kernel development will read & > consider the idea > I'm (a former? meanwhile not sure) MATLAB user & it's very annoing > typing each time for example > while i: > print i > ... > instead of > while i > print i > ... > of course if all is written in a single line ':' I guess should not be > omited > > Thank you for you suggestions. > Sorry my bad English. > > WBR, Dmitrey Hi Just a thought... I've also just made the jump from Matlab to Python (or am straddling the two at the moment!) and I find the ':' really useful for delimiting blocks of code. Took a while to get used to it but I reckon it helps me explain my code to non-programmers as they can see the blocks I use. Al From mituller at gmail.com Thu Feb 8 17:15:40 2007 From: mituller at gmail.com (mtuller) Date: 8 Feb 2007 14:15:40 -0800 Subject: Parsing HTML In-Reply-To: <1170963788.882845.124810@k78g2000cwa.googlegroups.com> References: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> <1170963788.882845.124810@k78g2000cwa.googlegroups.com> Message-ID: <1170972940.852050.53830@h3g2000cwc.googlegroups.com> I was asking how to escape the quotation marks. I have everything working in pyparser except for that. I don't want to drop everything and go to a different parser. Can someone else help? > > > I am trying to parse a webpage and extract information. > > BeautifulSoup is a great Python module for this purpose: > > http://www.crummy.com/software/BeautifulSoup/ > > Here's an article on screen scraping using it: > > http://iwiwdsmi.blogspot.com/2007/01/how-to-use-python-and-beautiful-... From greg at cosc.canterbury.ac.nz Fri Feb 2 18:42:33 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Feb 2007 12:42:33 +1300 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: <52i0n7F1p19tbU1@mid.individual.net> James Stroud wrote: > You haven't addressed why the limitation isn't arbitrary. It's not arbitrary because there is a built-in meaning for infix minus, but not for infix tilde. Python doesn't go out of its way to provide operators which aren't used by at least one built-in type. -- Greg From jonc at icicled.net Thu Feb 1 17:23:22 2007 From: jonc at icicled.net (Jonathan Curran) Date: Thu, 1 Feb 2007 16:23:22 -0600 Subject: xml.dom.minidom memory usage In-Reply-To: <45c25a17$0$25086$426a34cc@news.free.fr> References: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> <45c25a17$0$25086$426a34cc@news.free.fr> Message-ID: <200702011623.22881.jonc@icicled.net> Dan, Take a look at http://www.xml.com/pub/a/2003/03/12/py-xml.html. It's a starting point to output XML data via use of SAX. Bruno also mentioned Genshi. I haven't used Genshi myself, but it'd be worth it to take a look at what it has to offer. - Jonathan From Alessandro.Fachin at gmail.com Sun Feb 4 03:09:02 2007 From: Alessandro.Fachin at gmail.com (Alessandro Fachin) Date: Sun, 04 Feb 2007 09:09:02 +0100 Subject: Create a cookie with cookielib References: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> Message-ID: <45c59494$0$36013$4fafbaef@reader4.news.tin.it> Matthew Franz wrote: > I'm not sure what you mean be forge, but if you mean set an arbitrary > cookie manually (vs. one that was provided by the server). just use > add_header() in http://docs.python.org/lib/request-objects.html Yes is exactly what i want to do... i don't known because i looked at cookielib to set cookie data, cookie are simply http header :) Inserting values with add_header() or addheaders() it works. Thank you > It may be possible to use CookieJar for this purpose but I've only > used it for manipulating cookies set by the server... > > And I would agree that Python cookie APIs are less intuitive than > what are available in others such as Jakarta HttpClient.... > > - mdf From boris.smirnov at gmail.com Wed Feb 28 04:58:42 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 28 Feb 2007 01:58:42 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172654773.047745.83250@8g2000cwh.googlegroups.com> Message-ID: <1172656722.333784.143440@j27g2000cwj.googlegroups.com> On Feb 28, 10:45 am, Phil Thompson wrote: > On Wednesday 28 February 2007 9:26 am, boris.smir... at gmail.com wrote: > > > > > > > On Feb 28, 10:22 am, Phil Thompson > > > wrote: > > > On Wednesday 28 February 2007 9:00 am, boris.smir... at gmail.com wrote: > > > > On Feb 28, 9:07 am, boris.smir... at gmail.com wrote: > > > > > On Feb 28, 8:56 am, Phil Thompson > > > > > > wrote: > > > > > > On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > > > > > > > When your programs stops with the error, it should also be > > > > > > > printing a stack trace. This is a list of all the functions that > > > > > > > have been called when Python had the problem. > > > > > > > > You shouldn't have to do anything extra to get the stack trace. > > > > > > > The error is raised in Qt and aborts immediately. It never gets > > > > > > back to Python to generate a trace. > > > > > > > He needs to produce a short and complete test which demonstrates > > > > > > the problem, then we can point out where the QPaintDevice is being > > > > > > created. > > > > > > > Phil > > > > > > OK, but before I do a complete test, could anybody tell/explain me > > > > > why the same file is working on Windows? > > > > > Did anybody already meet with something similar Win vs. Linux? > > > > > > b. > > > > > Here is my simple script: > > > > > import sys > > > > from qt import * > > > > class Optimizer(QWidget): > > > > def __init__(self, parent = 0): > > > > QWidget.__init__(self) > > > > QGridLayout(self) > > > > if __name__ == '__main__': > > > > a = QApplication (sys.argv) > > > > mywidget = Optimizer() > > > > a.exec_loop() > > > > > This produces this: > > > > > python qt_script_bs_070228.py > > > > > QPaintDevice: Must construct a QApplication before a QPaintDevice > > > > > Any suggestions here? > > > > It works fine for me. > > > > > Thanks > > > > > BTW: One question: > > > > when I use "import qt" instead of "from qt import *" I get this error: > > > > Traceback (most recent call last): > > > > File "mscarideidtool_bs_070228.py", line 4, in ? > > > > class Optimizer(QWidget): > > > > NameError: name 'QWidget' is not defined > > > > > What is the difference between "import qt" and "from qt import *" ? I > > > > thought that these are the same. > > > > The first creates a new namespace called "qt" and imports the module's > > > objects into it. To reference those objects you have to include the > > > namespace name. > > > > The second imports the module's objects into the current namespace. > > > > Phil- Hide quoted text - > > > > - Show quoted text - > > > OK, I have to apologize because I didn't mention that I use python > > version 2.2.1, could it be the problem here? Bugs or something? I have > > to use this version since it was delivered with a software that we use > > here. > > So what versions of Qt, PyQt and SIP are you using? Were these included with > the software you are using? If so, what is that software? > > Phil- Hide quoted text - > > - Show quoted text - Stupid question but how can I find out what are the versions of those? I only found qt.py file and there was this: # Generated by SIP 3.3 (build 25) on Fri Jul 26 12:44:13 2002 The version of PyQt and SIP can't find out, but there is a directory PyQt wit .pyc files and SIP.h file. The sofware is MSC.ADAMS from msc.software b. From casevh at gmail.com Tue Feb 27 14:15:13 2007 From: casevh at gmail.com (casevh at gmail.com) Date: 27 Feb 2007 11:15:13 -0800 Subject: finding out the precision of floats In-Reply-To: <1172585380.631673.257410@q2g2000cwa.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> Message-ID: <1172603711.639243.57660@k78g2000cwa.googlegroups.com> > Why should you? It only gives you 28 significant digits, while 64-bit > float (as in 32-bit version of Python) gives you 53 significant > digits. Also note, that on x86 FPU uses 80-bit registers. An then > Decimal executes over 1500 times slower. 64-bit floating point only gives you 53 binary bits, not 53 digits. That's approximately 16 decimal digits. And anyway, Decimal can be configured to support than 28 digits. > > >>> from timeit import Timer > >>> t1 = Timer('(1.0/3.0)*3.0 - 1.0') > >>> t2 = Timer('(Decimal(1)/Decimal(3))*Decimal(3)-Decimal(1)', > > 'from decimal import Decimal')>>> t2.timeit()/t1.timeit() > > 1621.7838879255889 > > If that's not enough to forget about Decimal, take a look at this: > > >>> (Decimal(1)/Decimal(3))*Decimal(3) == Decimal(1) > False > >>> ((1.0/3.0)*3.0) == 1.0 > > True Try ((15.0/11.0)*11.0) == 15.0. Decimal is actually returning the correct result. Your example was just lucky. Decimal was intended to solve a different class of problems. It provides predictable arithmetic using "decimal" floating point. IEEE-754 provides predictable arithmetic using "binary" floating point. casevh From codecraig at gmail.com Tue Feb 27 10:52:37 2007 From: codecraig at gmail.com (abcd) Date: 27 Feb 2007 07:52:37 -0800 Subject: book for a starter In-Reply-To: References: Message-ID: <1172591557.825839.299470@m58g2000cwm.googlegroups.com> I'd pick, Dive Into Python (http://www.diveintopython.org/) ....you can read it online for FREE! From steven.bethard at gmail.com Fri Feb 2 14:23:36 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 02 Feb 2007 12:23:36 -0700 Subject: Checking default arguments In-Reply-To: References: Message-ID: <6vWdncesE4InEl7YnZ2dnUVZ_hmtnZ2d@comcast.com> Igor V. Rafienko wrote: > I was wondering whether it was possible to find out which parameter > value is being used: the default argument or the user-supplied one. > That is: > > def foo(x, y="bar"): > # how to figure out whether the value of y is > # the default argument, or user-supplied? > > foo(1, "bar") => user-supplied > foo(1) => default Why are you trying to make this distinction? That is, why should passing in "bar" be any different from getting the default value "bar" You could do something like:: >>> def foo(x='b a r'): ... if x is foo.func_defaults[0]: ... print 'default' ... else: ... print 'supplied' ... >>> foo('b a r') supplied >>> foo() default But that won't really work if your default value gets interned by Python, like small integers or identifier-like string literals:: >>> def foo(x='bar'): ... if x is foo.func_defaults[0]: ... print 'default' ... else: ... print 'supplied' ... >>> bar = ''.join(chr(i) for i in [98, 97, 114]) >>> foo(bar) supplied >>> foo('bar') default STeVe From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 16:46:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 22:46:29 +0100 Subject: Newbie question: replacing nulls in CSV with preceding value In-Reply-To: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> References: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> Message-ID: <45c258bd$0$21552$426a74cc@news.free.fr> Matt Waite a ?crit : > My first post, my first real python use, please be gentle: > > I have a CSV file, exported from Excel, that has blank records in it, > and I need to fill them in with the values from the record just above > it until it hits a non-blank value. Here's an example of the data, > which is in a file called test2.csv: > > Zone,City,Event > 1,Anytown,Event > ,,Event1 > ,,Event2 > ,,Event44 > 2,Anothertown,Event3 > ,,Event5 > ,,Event7 > > What I need it to look like is: > > Zone,City,Event > 1,Anytown,Event1 > 1,Anytown,Event2 > 1,Anytown,Event44 > 2,Anothertown,Event3 > 2,Anothertown,Event5 > 2,Anothertown,Event7 > > Pretty much everything I've tried has failed, and I've been searching > for hours for something similar and haven't found anything. The best > I've come up with --which is half baked and I don't even know if it > works -- is this: > > import csv > citynew='' > reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb")) > for row in reader: > row['CITY'] == citynew > else: > citynew=row['CITY'] > > The logic here -- in this case trying to fill in the city information > -- would seem to work, but I'm not sure. Did you actually tried it ? And itf yes, do you really think it 'works'? Ok, the solution is quite easy - assuming the very first data row has no blank values, and that either both Zone and City are blank or both are filled: prev_zone = prev_city = '' for row in reader: if row['Zone']: prev_zone, prev_city = row['Zone'], row['City'] else: row['Zone'], row['City'] = prev_zone, prev_city # now do something with row... > And I'm not sure how to write > the results of this back to the file. look for csv.DictWriter.writerow NB : note that you cannot "write back to the file" - just write to *another* file (then eventually os.rename(olfile, newfile)) From sjmachin at lexicon.net Fri Feb 9 10:28:02 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Feb 2007 02:28:02 +1100 Subject: pyExcelerator - Protecting Cells In-Reply-To: <1171006579.885603.4760@j27g2000cwj.googlegroups.com> References: <1171006579.885603.4760@j27g2000cwj.googlegroups.com> Message-ID: <45CC9302.5090106@lexicon.net> On 9/02/2007 6:36 PM, Chris wrote: > I'm sitting with a bit of an issue with pyExcelerator and creating an > Excel file with certain cells protected while the rest of the > spreadsheet is password protected. > > The Protection class under Formatting has 2 variables for cell_locked > and formula_hidden, tbh I only need to alter cell_locked to 0 to make > those cells writable but changing that on a global scale ends up with > everything I write being "writeable" if you re-open the file after it > has been produced. > "tbh" means what? "changing that on a global scale" means what?? Please write a small *test* script (along the lines of those in pyExcelerator's examples directory, without irrelevant/private/otherwise_inappropriate code from your app) which tries to set some cells to locked and some to unlocked. If you can't get it to work: (1) ensure that you have checked the bug register on Sourceforge and applied any patch that seems relevant to your problem (2) come back here with a copy/paste of the actual code that you have run. > I decided to import Formatting into the Worksheet module like this: Why? What made you think that this would achieve your goal? > import Formatting > self.Formatting = Formatting.Protection > > self.__cell_protect = 1 > self.__formula_hidden = 0 > > which is the defaults in the Protection class anyway but now when I do > my create file routine when I try to change the cell_protect variable > to 0 it makes absolutely no effect. Of course it would have no effect. You appear to have given Worksheet objects a gratuitous __cell_protect attribute -- but no code to use it. Protection is like a pattern or a font -- you have to cram it into an XFStyle object which you use as the style arg of the Worksheet.write() method. You will need of course at least 2 different XFStyle objects: one locked, another unlocked. > The code has been written as > such: > > if protection: > work_sheet.set_protect(protection) > work_sheet.set_password(password) > else: > pass What induced you to write the above two statements? > > for each_heading in each_work_sheet[1]: > work_sheet.write(7, heading_cnt, str(each_heading), > header_style) > heading_cnt += 1 > > vert_cnt = 8 > > for each_set in each_work_sheet[2]: > horiz_cnt = 0 > > for data_set in each_set: > work_sheet.cell_protect = 1 Now the Worksheet object has *TWO* useless attributes, one named __cell_protect and one named cell_protect ... > work_sheet.formula_hidden = 1 > > if len(str(data_set)) < 1: > work_sheet.cell_protect = 0 > work_sheet.formula_hidden = 0 > work_sheet.write(vert_cnt, horiz_cnt, ' ') > horiz_cnt += 1 > else: > work_sheet.write(vert_cnt, horiz_cnt, > str(data_set), data_style) > horiz_cnt += 1 > > vert_cnt += 1 > > As you can see I only want to be able to write to cells that have a > string '' which is parsed correctly through to data which was > originally extracted from a database. The problem is that I can only > seem to set it to protect all written cells or not. > HTH, John From no at spam.com Tue Feb 27 19:15:14 2007 From: no at spam.com (Farshid Lashkari) Date: Tue, 27 Feb 2007 16:15:14 -0800 Subject: how to convert an integer to a float? In-Reply-To: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, > i1)' always return 0, can you please tell me how can i convert it from > an integer to float? When two integers are involved in a division, the result will also be a division. If one of the operands is a float, then the result will be a float instead. So try casting one of the values to a float before performing the division: dx = float(abs(i2 - i1))/min(i2, i1) -Farshid From paul at boddie.org.uk Thu Feb 22 11:28:50 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Feb 2007 08:28:50 -0800 Subject: paths in modules In-Reply-To: References: Message-ID: <1172161730.919703.46730@q2g2000cwa.googlegroups.com> On 22 Feb, 17:13, Brandon Mintern wrote: > > toplevel_dir > +-main script > +-wrapper_dir > +-some_wrapper > +-utility_dir > +-some_external_utility [...] > And then in some_wrapper, I would have code like: > > import os > > def use_external_utility(): > f = os.popen('utility_dir/some_external_utility') > lines = f.readlines() > f.close() > return lines And you really want to refer to utility_dir relative to some_wrapper. What you can try is to split the __file__ attribute of some_wrapper - it's a standard attribute on imported modules - in order to refer to the module's parent directory (which should correspond to wrapper_dir): parent_dir, filename = os.path.split(__file__) Then you can join the parent directory to the path of the command: cmd = os.path.join(parent_dir, "utility_dir", "some_external_utility") The __file__ attribute of modules is documented here: http://docs.python.org/ref/types.html#l2h-109 Paul From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Feb 27 16:27:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Feb 2007 22:27:53 +0100 Subject: threading a thread References: Message-ID: <54jm2pF20dq64U2@mid.individual.net> tubby wrote: > Right now I'm just prototyping and the threaded hosts portion > works very well for my needs. I'd just like to add a threaded > ports check and wanted to know if anyone had done something > similar in Python. Taken the vast amount of threads you'll need, there will be a big overhead. Using a different means of concurrency is advisable. BTW, why not use nmap? Regards, Bj?rn -- BOFH excuse #394: Jupiter is aligned with Mars. From bignose+hates-spam at benfinney.id.au Fri Feb 16 05:58:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Feb 2007 21:58:49 +1100 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <87mz3e5pxy.fsf@benfinney.id.au> "exhuma.twn" writes: > Supposing you have two separate processes running on the same box, > what approach would you suggest to communicate between those two > processes. > > Let me list the ones I know of: > > * Sockets > Advantage: Supported per se in nearly every programming language > without even the need to install additional packages This would be my choice. But first, set up a well-defined *protocol* (preferably based on text commands) for the two processes to use for communication; don't have each of them being intricately aware of each others' implementation. > Disadvantage: Lot's of code to write, and it's kind of silly to > communicate via TCP/IP if the processes run on the same machine. You can cut down on the amount of code by using the standard library "cmd" module to handle a command interface, hooking the stdin and stdout of the commandline handler to the socket. If you're already thinking about cooperating processes, you should make them network-neutral anyway from the start. Here's what _The Art of Unix Programming_ has to say on the topic of text protocols: and IPC tactics for peer processes: -- \ "There are only two ways to live your life. One is as though | `\ nothing is a miracle. The other is as if everything is." -- | _o__) Albert Einstein | Ben Finney From jay.dow at gmail.com Wed Feb 14 12:47:24 2007 From: jay.dow at gmail.com (jay.dow at gmail.com) Date: 14 Feb 2007 09:47:24 -0800 Subject: list of range of floats In-Reply-To: <1171474688.756658.248060@a34g2000cwb.googlegroups.com> References: <1171474688.756658.248060@a34g2000cwb.googlegroups.com> Message-ID: <1171475244.832916.79690@l53g2000cwa.googlegroups.com> a = 0.0 b = 10.0 inc = .2 flts = [] while a < b: flts.append(a) a += inc From jeff.templon at gmail.com Tue Feb 20 11:55:39 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 08:55:39 -0800 Subject: How to test if one dict is subset of another? In-Reply-To: <7xy7mtz1q7.fsf@ruckus.brouhaha.com> References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> Message-ID: <1171990539.710698.276050@v45g2000cwv.googlegroups.com> On Feb 20, 9:12 am, Paul Rubin wrote: > do_something() > > you'd just write: > > for j in (index['user']['jeff'] & index['state']['running']): > do_something() Hi, it looks very cool, except that one of the constraints mentioned is that the solution has to work properly on pythons 2.2 and 2.3. production systems, certified OS releases, that sort of stuff ... can't just upgrade a few thousand machines worldwide for my little program ;-) Thanks ... I took the previous poster's suggestion (had also been suggested earlier) and built cached versions of the job lists, indexed on common queries, while building the master job list. JT From fdu.xiaojf at gmail.com Tue Feb 6 21:13:05 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Wed, 07 Feb 2007 10:13:05 +0800 Subject: Can Parallel Python run on a muti-CPU server ? Message-ID: <45C935B1.60606@gmail.com> Hi all, I'm interested in Parallel Python and I learned from the website of Parallel Python that it can run on SMP and clusters. But can it run on a our muti-CPU server ? We are running an origin3800 server with 128 CPUs. Thanks. From skip at pobox.com Sun Feb 11 00:03:08 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 10 Feb 2007 23:03:08 -0600 Subject: pygame and python 2.5 In-Reply-To: <1171168710.785138.265650@a34g2000cwb.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> Message-ID: <17870.41868.352208.705799@montanaro.dyndns.org> >> However, the difference between the open-source people and Microsoft >> is the the open-source people aren't being paid by you for the use of >> their product, so they're not obligated in any way to help you. mensanator> This argument has become tiresome. The Python community mensanator> wants Python to be a big fish in the big pond. That's why mensanator> they make Windows binaries available. I suspect the main reason Windows binaries are produced is because a) Microsoft doesn't ship Python installed on Windows, and b) your garden variety Windows user doesn't have the tools necessary to build Python from source. Not being a Windows user myself I don't understand all the ins and outs of VC6 v. VC7, legal or technical. Is there nothing Microsoft could have done to make VC7 compatible with the existing VC6-based build procedure? Skip From thegeoffmeister at gmail.com Sat Feb 10 20:25:53 2007 From: thegeoffmeister at gmail.com (Geoff Hill) Date: Sun, 11 Feb 2007 01:25:53 GMT Subject: Hacking in python References: Message-ID: The word "hack" can be known as a "smart/quick fix" to a problem. From peter.rabinovitch at alcatel.com Thu Feb 22 08:15:32 2007 From: peter.rabinovitch at alcatel.com (peter rabinovitch) Date: Thu, 22 Feb 2007 08:15:32 -0500 Subject: network simulator in Python ? References: <1172078818.126692.17510@k78g2000cwa.googlegroups.com> Message-ID: <45dd9777$1@news.alcatel.com> Have a look at simpy. Although it doesn't do the protocols you mention, it is a very good (imho)simulation toolkit in which it would be relatively easy to build whatever protocols you need. I am using it for a traffic management simulation project, and have found it very easy to get going and be productive, and my one technical question to the simpy mail list was answered with three good suggestions in an hour. The only drawback may be speed. "DanielJohnson" wrote in message news:1172078818.126692.17510 at k78g2000cwa.googlegroups.com... >I was wondering if anyblody can suggest me a network simulator written > in python in which I can add on my own code and extend its > functionality. > > I am looking for a simulator which will simualte TCP, UDP, RTP and > most networking protocol. The learning curve for ns2 and other > simulator is too high for me at this time and thats why I am > considering Python for it. > > Every help will be appreciated. > > Thanks > From bignose+hates-spam at benfinney.id.au Mon Feb 26 18:57:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 27 Feb 2007 10:57:13 +1100 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: <87slcs1nhi.fsf@benfinney.id.au> "Alan Isaac" writes: > I have a class whose instances should only receive attribute > assignments for attributes that were created at inititialization. > If slots are not appropriate, what is the Pythonic design for this? The Pythonic design is: don't expect to have such control over users of your code. (I encountered this in trying to design an Enum class, with enumeration members as attributes.) Document, in the class doc string and anywhere else you feel appropriate, the fact that attributes shouldn't be added, and let your users deal with their own bugs if they ignore that. -- \ "No one ever went broke underestimating the taste of the | `\ American public." -- Henry L. Mencken | _o__) | Ben Finney From steven.bethard at gmail.com Tue Feb 20 14:59:53 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 20 Feb 2007 12:59:53 -0700 Subject: Python 3.0 unfit for serious work? In-Reply-To: <1171990150.797668.19770@p10g2000cwp.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> Message-ID: Jay Tee wrote: > Yo, > > On Feb 16, 6:07 am, Steven Bethard wrote: >> Python 3.0 is determined not to be hampered by backwards incompatibility >> concerns. It's not even clear yet that your average 2.6 code will work > > Then Python is pretty much determined to remove itself from > consideration > from various kinds of international projects like the one I work on. You snipped the rest of that comment: "It's not even clear yet that your average 2.6 code will work on 3.0 -- though there's a pretty large contingent trying to make this true." If you want to make sure average 2.6 code works on 3.0, please help contribute to Python. You can find out where best to focus your efforts by asking on python-dev: http://mail.python.org/mailman/listinfo/python-dev > If it's not backwards compatible, meaning if 2.4 code doesn't run on > 3.0, it's rather likely that strong pressure will be applied to port > *away* from Python into something less capricious. Well, Python 2.4 code will work on Python 2.6 and 2.7 so just because your code isn't yet compatible with Python 3.0 doesn't mean you should give up on Python. Python 2.2 was released in early 2003 and you said you'd be dropping support for 2.2 in early 2008, so I conclude that since Python 2.5 was released in late 2006, you'll be ready to drop Python 2.5 support (and have 2.6/3.0 compatible code) by late 2011. Sure, it's a long way off, but you're writing 2.2 compatible code *now*. Is it really that bad to wait four years for Python 3.0? STeVe From B.Ogryczak at gmail.com Tue Feb 6 06:46:15 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 6 Feb 2007 03:46:15 -0800 Subject: Python cheatsheets In-Reply-To: References: Message-ID: <1170762374.981099.22010@v45g2000cwv.googlegroups.com> On Jan 7, 10:03 pm, gonzlobo wrote: > Curious if anyone has a python cheatsheet* published? I'm looking for > something that summarizes all commands/functions/attributes. Having > these printed on a 8" x 11" double-sided laminated paper is pretty > cool. > > * cheatsheet probably isn't the right word, but you get the idea. :) http://www.onlamp.com/python/excerpt/PythonPocketRef/ From deets at nospam.web.de Mon Feb 19 09:00:18 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Feb 2007 15:00:18 +0100 Subject: Building Python Pagage for Newer Python Version References: <1171875440.938807.165340@l53g2000cwa.googlegroups.com> Message-ID: <53toriF1tr6efU1@mid.uni-berlin.de> bg_ie at yahoo.com wrote: > Hi, > > I have just downloaded the source for PyXML-0.8.4, which I would like > to build for Python 2.5. How exactly do I go about doing this? python2.5 setup.py install usually does the trick. Diez From sebmegret at gmail.com Fri Feb 23 04:46:29 2007 From: sebmegret at gmail.com (elGringo) Date: 23 Feb 2007 01:46:29 -0800 Subject: connection pool in python? In-Reply-To: References: Message-ID: <1172223989.686517.140380@j27g2000cwj.googlegroups.com> On 23 f?v, 08:44, "Eric CHAO" wrote: > Connection Pool is necessary in web applications with Java and JDBC. > So does python have something like that? > > Thanks. Look at http://www.sqlalchemy.org/ From sjmachin at lexicon.net Sun Feb 11 21:24:18 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 18:24:18 -0800 Subject: Read/write 2D data from/to file..? In-Reply-To: <1171244850.077289.130330@s48g2000cws.googlegroups.com> References: <1171244850.077289.130330@s48g2000cws.googlegroups.com> Message-ID: <1171247058.774325.208430@j27g2000cwj.googlegroups.com> On Feb 12, 12:47 pm, "mech point" wrote: > I was able to read the data from file into a two dimensional array > (lists) > > rows=[map(float,line.split())for line in file("data")] > > but How to write them back into the file. Presuming that it is either mandatory to adopt the same style (or lack thereof) as the input code, and/or futile to suggest otherwise: file('data2','w').write('\n'.join(' '.join(repr(item)for item in row)for row in rows)+'\n') From rkmr.em at gmail.com Mon Feb 12 21:09:21 2007 From: rkmr.em at gmail.com (mark) Date: Mon, 12 Feb 2007 18:09:21 -0800 Subject: python mms library Message-ID: Hi Is there a library for creating mms message in python? thanks mark From osv at javad.com Wed Feb 7 14:03:38 2007 From: osv at javad.com (Sergei Organov) Date: Wed, 07 Feb 2007 22:03:38 +0300 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> <1170872694.018720.301410@m58g2000cwm.googlegroups.com> Message-ID: "sturlamolden" writes: > On Feb 7, 6:17 pm, John Nagle wrote: [...] > MPI does not use threads on SMPs because it performs worse than using > multiple processes. I fail to see how threads in general could perform worse than processes. I do understand that processes are inherently more safe/secure, but when it comes to speed I really can't imagine why it could happen that threads perform worse (poor threads implementation and programming practices aside). Care to give some references? -- Sergei. From openopt at ukr.net Mon Feb 19 06:38:58 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 19 Feb 2007 03:38:58 -0800 Subject: (beginners question) howto set self.field4.subfield8='asdf'? In-Reply-To: References: <1171877794.747825.294890@t69g2000cwt.googlegroups.com> Message-ID: <1171885138.150935.207890@h3g2000cwc.googlegroups.com> Thx but is there any simpleir way, if using not class, but just struct (or something like that, MATLAB equivalent for that one)? I'm thinking of rewriting some optimization solvers (non-smooth, constrained, with (sub)gradients or patterns provided by user) to Python and I don't know currently is it possible to easy convert things like prob = []; prob.advanced.ralg.hs = 1 (so in this line all subfields are generating automatically in MATLAB or Octave) I have huge amount of such lines, and implementing separate class for each one is unreal. Thank you in advance, Dmitrey From gherron at digipen.edu Tue Feb 27 19:50:27 2007 From: gherron at digipen.edu (Gary Herron) Date: Tue, 27 Feb 2007 16:50:27 -0800 Subject: import parent In-Reply-To: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> References: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> Message-ID: <45E4D1D3.9040803@digipen.edu> Greg at bag.python.org wrote: > How does one get access to the class that imported a module. For example: > foo imports bar -- how does bar access foo? > > Thanks. > > If bar wants to access foo, it just imports it. If foo imports bar as well, then you have circular imports, but Python can handle this with no problem. There can be a problem with circular imports if you try to import specific names from the module, and the circularity happens before those names are defined. But just: foo: import bar ... bar: import foo ... works fine. However... as several others have pointed out, circular imports are often a sign that your software design is not very well thought out. It's usually better to have your thought process, your design and your imports organized in a hierarchal fashion. Gary Herron From http Tue Feb 20 03:12:48 2007 From: http (Paul Rubin) Date: 20 Feb 2007 00:12:48 -0800 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> Message-ID: <7xy7mtz1q7.fsf@ruckus.brouhaha.com> "Jay Tee" writes: > for j in jobs: > if (j.get('user') == 'jeff' and j.get('state')=='running') : > do_something() Sounds like you need some backing data structures, like indexes in a database, e.g. (untested, uses the cool new defaultdicts of 2.5): index = defaultdict(lambda: defaultdict(set)) for j in jobs: for k in j's dict: index[k][j.get(k)].add(j) Now for > if j.subset_attr({'user' : 'jeff', 'state' : 'running'}) : > do_something() you'd just write: for j in (index['user']['jeff'] & index['state']['running']): do_something() From larry.bates at websafe.com Tue Feb 13 18:02:54 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Feb 2007 17:02:54 -0600 Subject: _ssl.pyd is buggy? In-Reply-To: References: Message-ID: <45D2439E.3080507@websafe.com> Laszlo Nagy wrote: > > Hello, > > I wrote a small program that uses xmlrpc over https. It should work as a > win32 application and as a win32 service too. There is a file called > Processor.py that contains the main thread of the program. It is called > from two files: win32_Application.py and win32_Service.py. The > application works perfectly. The service does not. I can start it from > the services mmc console, but it does not created logfiles, and does > nothing. It cannot be stopped and I have to kill pythonservice.exe. The > event log shows this: > > > Information: The AmazonOfferDownloaderService service has started. > Application error: Faulty application: python.exe, version: 0.0.0.0, > faulty modul: _ssl.pyd, version: 0.0.0.0, memory address: 0x00019b87. > > Is it possible that my _ssl.pyd is faulty? Please help me. > > Python version: 2.4.3 (#69, Mar 29 2006) > Windows version: Windows XP Professional, service pack 2, Hungarian (I > translated the above messages from the event log....) > > Thanks, > > Laszlo > > >>>> Here is the code for the application: > > import thread,threading,time > > from Processor import * > from servicelog import * > from win32_Config import * > > stopped = threading.Event() > stopped.clear() > processor = Processor(stopped) > thread.start_new_thread(processor.Process,()) > logger = getLogger('win32_Application') > logger.info("Staring as application. Please press CTRL+C to stop service.") > while 1: > try: > time.sleep(1) > except: > break > logger.info("Stopping application " + SERVICE_NAME) > stopped.set() > while not processor.stopped.isSet(): > logger.debug("Waiting for the processor to finish...") > time.sleep(1) > > logger.info("Application stopped.") > >>>> Here is the code for the service: > > from win32_Config import * > from Processor import * > from servicelog import * > > import win32serviceutil, win32service > import pywintypes, win32con, winerror > from win32event import * > from win32file import * > from win32pipe import * > from win32api import * > from ntsecuritycon import * > > import traceback > import thread,threading > > class Service(win32serviceutil.ServiceFramework): > _svc_name_ = SERVICE_NAME > _svc_display_name_ = SERVICE_DISPLAY > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.stopped = threading.Event() > self.stopped.clear() > self.logger = getLogger(SERVICE_NAME) > > def SvcStop(self): > self.logger.info("Got SvcStop, trying to stop service...") > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > self.stopped.set() > > def SvcDoRun(self): > """Write an event log record - in debug mode we will also see > this message printed.""" > try: > import servicemanager > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STARTED, > (self._svc_name_, '') > ) > self.logger.info("Started.") > self.logger.debug("Creating processor instance") > processor = Processor(self.stopped) > self.logger.debug("Starting processor thread") > thread.start_new_thread(processor.Process,()) > self.logger.debug("Waiting for the processor thread to finish") > self.stopped.wait() > self.logger.debug("Stopping") > time.sleep(1) > while not processor.stopped.isSet(): > > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) > time.sleep(5) > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STOPPED, > (self._svc_name_, "") > ) > self.logger.info("Stopped") > except: > self.logger.error('',exc_info = sys.exc_info()) > > > if __name__=='__main__': > win32serviceutil.HandleCommandLine(Service) > > I see some problems. You don't use time sleep in services. You wait for a stop signal and if you don't get it by the time you reach your timeout, you loop. I'm not sure what you are trying to accomplish with the threading module, but you should start with a simple service first. I don't think you will need the threading at all. Here is a skeleton that might help: class Service(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.timeout=5000 # 5000 milliseconds or 5 seconds #--------------------------------------------------------------------- # Create an event which we will use to wait on. # The "service stop" request will set this event. #--------------------------------------------------------------------- self.hWaitStop=win32event.CreateEvent(None, 0, 0, None) return def SvcStop(self): #--------------------------------------------------------------------- # Before we do anything, tell SCM we are beginning the stop process. #--------------------------------------------------------------------- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) #--------------------------------------------------------------------- # And set my event, note you don't stop here, you just set the flag # so that you will exit from your while loop in SvcDoRun #--------------------------------------------------------------------- win32event.SetEvent(self.hWaitStop) return def SvcDoRun(self): import servicemanager #--------------------------------------------------------------------- # Make entry in the event log that this service started #--------------------------------------------------------------------- servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) while 1: #------------------------------------------------------------------- # Wait for service stop signal, if I timeout, loop again #------------------------------------------------------------------- rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # # Check to see if self.hWaitStop happened # if rc == win32event.WAIT_OBJECT_0: # # Stop signal encountered # break else: # # Do your work here # pass #--End while-- #--------------------------------------------------------------------- # Log stopped message to EventLog #--------------------------------------------------------------------- servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '')) return Note: I pieced this together from a working service, it has NOT been tested. It should be VERY close. If you don't have it already you might want to pick up a copy of Python Programming on Win32 by Mark Hammond and Andy Robinson. It helped me a LOT. -Larry From python at gakman.com Fri Feb 9 08:50:41 2007 From: python at gakman.com (Gerald Kaszuba) Date: Sat, 10 Feb 2007 00:50:41 +1100 Subject: pycallgraph 0.1.0 Message-ID: <108b15f0702090550l1d675c84w7cd83db377e5b50e@mail.gmail.com> Hi I've just released the first version of Python Call Graph. I haven't tested it too much so don't expect it not to crash :) An example of its output is: http://pycallgraph.slowchop.com/files/examples/mongballs-client.png It's easy to use... you just need Graphviz installed and in your path and a few lines of code changes. More details at http://pycallgraph.slowchop.com/ If you have any problems, don't hesitate to ask here or email me directly. Enjoy! Gerald From http Tue Feb 20 14:54:07 2007 From: http (Paul Rubin) Date: 20 Feb 2007 11:54:07 -0800 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> <1171990539.710698.276050@v45g2000cwv.googlegroups.com> <1171992831.871231.86450@h3g2000cwc.googlegroups.com> <7x3b50d8ri.fsf@ruckus.brouhaha.com> <1171999619.755238.294080@m58g2000cwm.googlegroups.com> Message-ID: <7xfy90sizk.fsf@ruckus.brouhaha.com> "Jay Tee" writes: > Python 2.2.3 (#1, Oct 26 2003, 11:49:53) > ImportError: No module named sets Hmm, well I think the sets module in 2.3 is written in Python, so you could drop it into your application for use in 2.2. Better would be to use the C version from 2.4 if you can. Or you could fake it with dicts. Sets are really just dicts under the skin. Instead of set([1,2,3]) you'd use {1:True, 2:True, 3:True}. To intersect two of them (untested): def intersection(d1,d2): if len(d2) < len(d1): # swap them so d1 is the smaller one d1,d2 = d2,d1 r = {} for k in d1.iterkeys(): if k in d2: r[k] = True return r The d1,d2 swap is just an optimization, since access is constant-time you want to scan the smaller dictionary to minimize the number of lookups. From jstroud at mbi.ucla.edu Sat Feb 3 03:03:40 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 03 Feb 2007 08:03:40 GMT Subject: How much introspection is implementation dependent? In-Reply-To: <1170465120.175164.103350@s48g2000cws.googlegroups.com> References: <1170465120.175164.103350@s48g2000cws.googlegroups.com> Message-ID: George Sakkis wrote: > On Feb 2, 6:56 pm, James Stroud wrote: > >> Hello, >> >> I wanted to automagically generate an instance of a class from a >> dictionary--which might be generated from yaml or json. I came up with this: >> >> (snip) >> >> == >> >> #! /usr/bin/env python >> >> # automagical constructor >> def construct(cls, adict): >> dflts = cls.__init__.im_func.func_defaults >> vnames = cls.__init__.im_func.func_code.co_varnames >> >> argnames = vnames[1:-len(dflts)] >> argvals = [adict.pop(n) for n in argnames] >> >> return cls(*argvals, **adict) >> >> def test(): >> >> class C(object): >> def __init__(self, arg1, arg2, kwa3=3): >> self.argsum = arg1 + arg2 >> self.kwsum = kwa3 >> def __str__(self): >> return "%s & %s" % (self.argsum, self.kwsum) >> >> # now a dict for autmagical generation >> adict = {'arg1':1, 'arg2':2, 'kwa3':42} >> >> print '======== test 1 ========' >> print adict >> print construct(C, adict) >> >> adict = {'arg1':1, 'arg2':2} >> print >> print '======== test 2 ========' >> print adict >> print construct(C, adict) >> >> if __name__ == "__main__": >> test() > > What's the point of this ? You can call C simply by C(**adict). Am I > missing something ? > > George > Never mind. You're right. py> class C(object): ... def __init__(self, a, b, c=4): ... print a,b,c ... py> C(**adict) 10 5 4 <__main__.C object at 0x762530> I guess I thought that, were it this easy, it would have been done in pyaml. James From sjmachin at lexicon.net Wed Feb 28 09:53:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2007 06:53:39 -0800 Subject: finding out the precision of floats In-Reply-To: <1172662682.590738.301630@k78g2000cwa.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> Message-ID: <1172674419.411077.4210@t69g2000cwt.googlegroups.com> On Feb 28, 10:38 pm, "Bart Ogryczak" wrote: > [1] eg. consider calculating interests rate, which often is defined as > math.pow(anualRate,days/365.0). In what jurisdiction for what types of transactions? I would have thought/hoped that the likelihood that any law, standard or procedure manual would define an interest calculation in terms of the C stdlib would be somewhere in the region of math.pow(epsilon, HUGE), not "often". More importantly, the formula you give is dead wrong. The correct formula for converting an annual rate of interest to the rate of interest to be used for n days (on the basis of 365 days per year) is: (1 + annual_rate) ** (n / 365.0) - 1.0 or math.pow(1 + annual_rate, n / 365.0) - 1.0 if you prefer. > BTW, math.* functions do not return Decimals. For which Bell Labs be praised, but what's your point? Cheers, John From jeffrey.aylesworth at gmail.com Mon Feb 26 20:10:29 2007 From: jeffrey.aylesworth at gmail.com (jeff) Date: 26 Feb 2007 17:10:29 -0800 Subject: getting terminal display size? In-Reply-To: <12u70nr9lcu4se5@corp.supernews.com> References: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> <12u4g4ci5gqu46c@corp.supernews.com> <12u4gbepet1ek62@corp.supernews.com> <1172537489.610807.288630@p10g2000cwp.googlegroups.com> <12u70nr9lcu4se5@corp.supernews.com> Message-ID: <1172538629.523218.163640@v33g2000cwv.googlegroups.com> On Feb 26, 8:01 pm, Grant Edwards wrote: > On 2007-02-27, jeff wrote: > > > I don't really understand any of that; can you right me a function > > that'll return the size as a tuple? > > What do you think I posted? > > -- > Grant Edwards grante Yow! I selected E5... but > at I didn't hear "Sam the Sham > visi.com and the Pharoahs"! nevermind, I figured it outr, it just looked confusing From steve at REMOVEME.cybersource.com.au Sun Feb 25 19:45:51 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 26 Feb 2007 11:45:51 +1100 Subject: Nested Parameter Definitions References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> <1172430363.360956.5300@q2g2000cwa.googlegroups.com> Message-ID: On Sun, 25 Feb 2007 11:06:03 -0800, Virgil Dupras wrote: > On Feb 25, 1:00 pm, "Paddy" wrote: >> I blogged on finding a new-to-me feature of Python, in that you are >> allowed to nnest parameter definitions: >> >> >>> def x ((p0, p1), p2): >> >> ... return p0,p1,p2 [snip] > I didn't know about it either. Without the call example, I would have > had a hard time to try to figure out what these extra brackets are > for. For this reason, I think that an explicit unpack is more > readable, and thus better. And now that you do know, it is not hard to figure it out at all. Nested parameters are no harder to figure out than *args or arg=value. It's something that you learn, once, and then it is easy forever. To my mind, def x ((p0, p1), p2) _is_ an explicit unpack. It just takes place in the parameter definition, where you can see it even if the source code is not available, not in the body of the function code, where you may or may not even be able to find it. -- Steven D'Aprano From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Feb 18 17:33:32 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 18 Feb 2007 23:33:32 +0100 Subject: function & class References: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> Message-ID: <53s2hsF1tr4fuU1@mid.individual.net> jupiter wrote: > My problem is I want to use threading You're right. Why do you think you want to use (multi-)threading? > and I might need to pass values between function and classes. I am > not sure how this can be done. I have read about classes and I > know they are like function however does not return anything where > as function does. If I define class and then function in this > class how do I access this function ????? I think you could read a tutorial about OOP, for example one of those: http://www.google.de/search?q=python+oop+tutorial Feel free to post here for further questions. > I am not sure and confused about classes and functions as how to > go about them is there any simple way to understand difference > between them and when to use what and how to pass data/reference > pointer between them ? BTW, please use some punctuation. Reading your multiline sentences isn't easy. Regards, Bj?rn -- BOFH excuse #393: Interference from the Van Allen Belt. From Alessandro.Fachin at gmail.com Sun Feb 11 08:47:51 2007 From: Alessandro.Fachin at gmail.com (Alessandro Fachin) Date: Sun, 11 Feb 2007 14:47:51 +0100 Subject: urllib2 request htaccess page through proxy Message-ID: <45cf1e70$0$32731$4fafbaef@reader1.news.tin.it> I write this simply code that should give me the access to private page with htaccess using a proxy, i don't known because it's wrong... import urllib,urllib2 #input url url="http://localhost/private/file" #proxy set up proxy_handler = urllib2.ProxyHandler({'http': 'http://myproxy:8888'}) #htaccess set up user="matteo" password="matteo" passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, user, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(proxy_handler,authhandler) urllib2.install_opener(opener) #open the url req=urllib2.Request(url) data=urllib2.urlopen(req).read() print data i get no access on access.log from apache2 and nothing from the proxy in tcpdump log. If i use only the proxy with a page that doesn't use htaccess it works... if anyone could help,regards... Traceback (most recent call last): File "proxy.py", line 22, in ? data=urllib2.urlopen(req).read() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 396, in error result = self._call_chain(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 741, in http_error_401 host, req, headers) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 720, in http_error_auth_reqed return self.retry_http_basic_auth(host, req, realm) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 730, in retry_http_basic_auth return self.parent.open(req) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 402, in error return self._call_chain(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 480, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Authorization Required From aisaac at american.edu Mon Feb 12 07:33:45 2007 From: aisaac at american.edu (Alan Isaac) Date: Mon, 12 Feb 2007 12:33:45 GMT Subject: randomly generate n of each of two types References: <3YOzh.1133$yg7.205@trnddc08> <1171272184.544941.277510@s48g2000cws.googlegroups.com> Message-ID: wrote in message news:1171272184.544941.277510 at s48g2000cws.googlegroups.com... > >>> r = [x for x in test.random_types(10)] > >>> r > [False, False, False, False, False, False, False, False, False, False, > True, True, True, True, True, True, True, True, True, True] > > I think it needs a cast to a float: Mea culpa. I **always** import division from __future__ and tend to assume everyone else does too. Thanks, Alan From Finger.Octopus at gmail.com Fri Feb 9 06:31:24 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 9 Feb 2007 03:31:24 -0800 Subject: Problem - Win32 Programming In-Reply-To: <1171016671.740414.30730@p10g2000cwp.googlegroups.com> References: <1171016671.740414.30730@p10g2000cwp.googlegroups.com> Message-ID: <1171020684.637291.16590@v45g2000cwv.googlegroups.com> What shoud I do to fix it? From usable.thought at gmail.com Fri Feb 16 11:15:51 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 08:15:51 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> Message-ID: <1171642551.277929.233540@l53g2000cwa.googlegroups.com> On Feb 16, 10:29 am, Tim Golden wrote: > I would ask if you had *any* other Python installation > -- say a cygwin one -- which might just be getting in the way? It's a cygwin problem, guddammit. I was wondering if this might be the case - I should have mentioned in my initial post that I've got a whole Cygwin setup, including Python. I know the conflict is the problem because just now I opened up a command shell in XP (not the Cywgin bash window), and instead of typing "python" and getting nothing, I tried "which python" - which when you think about it, shouldn't even work in a XP shell. But somehow Cygwin is mingling some of its capabilities with the XP shell, because "which python" actually gets an answer - "/usr/bin/python," which is Cygwin. Now the question is how to fix this - I don't want to uninstall the Cygwin version. Instead I need some way of unknotting Cygwin's intrusion into what should be an XP-only shell, or else a way of giving priority when in that shell (and not the bash shell, which I also use) to the Python executable residing at C:\Python25. From gagsl-py at yahoo.com.ar Tue Feb 20 22:29:54 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Feb 2007 00:29:54 -0300 Subject: code-object References: Message-ID: En Tue, 20 Feb 2007 22:39:43 -0300, LG escribi?: >>>> code = compile('print "hello everyone, how are you? "', '', > 'exec') >>>> exec code > hello everyone, how are you? >>>> print code > ", line 1> > > how to print the code object ? > like the one on .pyc Do you want the source code back? You need a decompiler. decompyle may work but it's outdated. -- Gabriel Genellina From marc.omorain at gmail.com Mon Feb 12 05:43:20 2007 From: marc.omorain at gmail.com (marc.omorain at gmail.com) Date: 12 Feb 2007 02:43:20 -0800 Subject: Progress when parsing a large file with SAX Message-ID: <1171277000.671586.191250@q2g2000cwa.googlegroups.com> Hi there, I have a 28mb XML file which I parse with SAX. I have some processing to do in the startElement / endElement callbacks, which slows the parsing down to about 60 seconds on my machine. My application is unresponsive for this time, so I would like to show a progress bar. I could show a spinner to show that the application is responsive, but I would prefer to show a percentage. Is there any way to query the parser to see how many bytes of the input file have been processed so far? Thanks, Marc From ptmcg at austin.rr.com Wed Feb 14 09:31:14 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 Feb 2007 06:31:14 -0800 Subject: replacing substrings within strings In-Reply-To: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> Message-ID: <1171463474.135988.86560@s48g2000cws.googlegroups.com> On Feb 14, 6:08 am, "amadain" wrote: > Hi > I was wondering if there was a nicer way to swap the first 2 > characters in a string with the 4th and 5th characters other than: > > darr=list("010203040506") > aarr=darr[:2] > barr=darr[4:6] > darr[:2]=barr > darr[4:6]=aarr > result="".join(darr) > > The above code works fine but I was wondering if anybody had another > way of doing this? > > A "4th and 5th characters" -> darr[4:6] You must be referring to the leading '0' as the 0th character, then. -- Paul From tjreedy at udel.edu Wed Feb 14 03:24:15 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Feb 2007 03:24:15 -0500 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> <1171437825.977798.249420@q2g2000cwa.googlegroups.com> Message-ID: "jm.suresh at no.spam.gmail.com" wrote in message news:1171437825.977798.249420 at q2g2000cwa.googlegroups.com... I am OK with calls being stacked, but I wondering will the local variables be stacked given that return statement is followed by the function call? def test(): x = 22 y = 33 z = x+y return anotherFunction(z) In this function will all the local variables (x,y,z) be pushed into the stack before calling anotherFunction(z) or Python will find out that the locals are no longer needed as anotherFunction(z) is just returned? ================= To add to Gabriel's answer: Questions of this sort are implementation specific. CPython will allocate the objects on the heap. But I believe at present something will go on the C stack with each function call. I suspect that the C array that typically implements the local namespace is included but don't specifically know. The local names are deleted, and the associated heap objects released if that make the reference count 0, as part of the return process. No optimization of the sort you indicate is done. Indeed, the heap objects could have other references, and the namespace array is fixed size, so I am not sure there is anything that could, in general, be done. In any case, Python never deletes without at least implicit instruction to do so. The maximun recursion depth CPython will attempt is governed by an internal variable that you can get and set to adjust to your problem and hardware: >>> sys.getrecursionlimit() 1000 >>> sys.setrecursionlimit(500) >>> sys.getrecursionlimit() 500 Terry Jan Reedy From larry.bates at websafe.com Fri Feb 9 19:58:32 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 09 Feb 2007 18:58:32 -0600 Subject: Matching Strings In-Reply-To: References: Message-ID: rshepard-at-appl-ecosys.com wrote: > On 2007-02-10, rshepard at nospam.appl-ecosys.com wrote: > >> if item == selName: > > Slicing doesn't seem to do anything -- if I've done it correctly. I > changed the above to read, > > if item[2:-2] == selName: > > but the output's the same. > > Rich Use the interpreter to test things: a="(u'ground water',)" a[2:-2] "'ground water'" a[3:-3] 'ground water' That is what you are looking for. -Larry From bjourne at gmail.com Mon Feb 5 08:44:24 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 5 Feb 2007 14:44:24 +0100 Subject: in place-ness of list.append In-Reply-To: <17863.3720.339689.188664@montanaro.dyndns.org> References: <17863.3720.339689.188664@montanaro.dyndns.org> Message-ID: <740c3aec0702050544v5fc7563cpa334a93745bfcb87@mail.gmail.com> On 2/5/07, skip at pobox.com wrote: > > Bart> #-------------------------------------------------- > Bart> def addnumber(alist, num): > Bart> """ work around the inplace-ness of .append """ > Bart> mylist = alist[:] > Bart> mylist.append(num) > Bart> return mylist > Bart> #-------------------------------------------------- > > Such an operation will be O(N**2), and thus expensive if performed > frequently on lists of moderate length. I've never been tempted to do this. How can that be? Making a copy of a list is O(N), isn't it? -- mvh Bj?rn From jonc at icicled.net Thu Feb 1 15:12:36 2007 From: jonc at icicled.net (Jonathan Curran) Date: Thu, 1 Feb 2007 14:12:36 -0600 Subject: xml.dom.minidom memory usage In-Reply-To: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> References: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> Message-ID: <200702011412.36075.jonc@icicled.net> Dan, The DOM (Document Object Model) is such that it loads all the elements of the XML document into memory before you can do anything with it. With your file containing millions of child nodes this will eat up as much memory as you have. A solution to this is to use the SAX method of parsing XML documents and working on it. SAX is such that it only reads the XML doc. a node (or a few nodes) at a time. Unfortunately, the use of DOM or SAX completely depends on what kind of processing you need to be done on the XML document. If it is editing a record at a time (from what I've gathered from your code) it would be wise to use SAX. I highly suggest looking into this method of processing. - Jonathan Curran From solrick51 at hotmail.com Thu Feb 8 06:50:24 2007 From: solrick51 at hotmail.com (solrick51 at hotmail.com) Date: 8 Feb 2007 03:50:24 -0800 Subject: Python design project In-Reply-To: <1170726592.725078.29030@a34g2000cwb.googlegroups.com> References: <1170337417.236975.44070@l53g2000cwa.googlegroups.com> <45c313d5$0$8726$ed2619ec@ptn-nntp-reader02.plus.net> <1170673772.977486.172770@a75g2000cwd.googlegroups.com> <1170726592.725078.29030@a34g2000cwb.googlegroups.com> Message-ID: <1170935424.863110.189190@p10g2000cwp.googlegroups.com> Hi Josh, Thank you for replying my message, sorry for the late reply, i was ill for two days.. I thought about the things you said, and think that it would be interesting, if fonts hit eachother the fonts would be merging. stuck together. so in a kind of way you create 'a new font' . I think the mutate part works also in that, by mutating, you can also create a new form "family'. But I think that the fonts must not unrecognizable mutate. the reproducing thing would be nice, so you also get the 'families' like family of a, family of b... and so on... I think that the family must remain at each other presence, stuck together, and when a touches b you get a new form and family. 2 think that all the things could transform, except for the serifs, kerning. 3 does flash work with vector? flash is pixel based isn't? what doe you think about the project, i'm verry interesting in more things oppinions. do you think that the designer creates the final work here, because of the programming or do you think that the fonts of the computer does it? Best, Rick From jstroud at mbi.ucla.edu Tue Feb 13 01:13:59 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 12 Feb 2007 22:13:59 -0800 Subject: Testers please In-Reply-To: References: Message-ID: martien friedeman wrote: > I have written this tool that allows you to look at runtime data and > code at the same time. > And now I need people to test it. > > The easiest way to see what I mean is to look at some videos: > http://codeinvestigator.googlepages.com/codeinvestigator_videos > > It requires Apache and Sqlite. > > It works for me with a Firefox browser on Linux. Amazing! From eopadoan at altavix.com Wed Feb 7 12:09:24 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Wed, 7 Feb 2007 15:09:24 -0200 Subject: Object type check In-Reply-To: <1170867552.247093.198800@j27g2000cwj.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> Message-ID: > Of cource i restrict them to particular types! In C# you cannot pass > something bad > this way because the compiler will just catch it! And you cant pass something 'good' that immitates another object interface (a file-like object for example) > I see what you mean by "duck typing". So you suggest the "do nothing > at all" direction, > better document my code so other can see what is expected, right ? I would add UnitTests to it. -- EduardoOPadoan (eopadoan->altavix::com) From nil at dev.nul Sun Feb 11 11:24:53 2007 From: nil at dev.nul (Christian Stapfer) Date: Sun, 11 Feb 2007 17:24:53 +0100 Subject: can't find a way to display and print pdf through python. References: <200702110647.l1B6l22s027328@nsa.veriwave.com> Message-ID: krishnakant Mane wrote in message news:mailman.3852.1171176596.32031.python-list at python.org... > On 11/02/07, Vishal Bhargava wrote: >> Use Report Lab... > I mentioned in my first email that I am already using reportlab. > but I can only generate pdf out of that. > I want to display it on screen and I also will be giving a print > button which should do the printing job. > by the way I use wxpython for gui. Under Windows you could do it by embedding Adobe's ActiveX control in your application. Don't know about Linux, though. Perhaps you could just convert your PDF to a raster image for display (eg. by using ImageMagick's convert) under Linux? Regards, Christian From paul at boddie.org.uk Thu Feb 15 06:49:16 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 Feb 2007 03:49:16 -0800 Subject: threading and multicores, pros and cons In-Reply-To: <1171494879.866830.102710@m58g2000cwm.googlegroups.com> References: <7xodnx2vir.fsf@ruckus.brouhaha.com> <7x7iulqlvx.fsf@ruckus.brouhaha.com> <1171488267.433565.228110@a75g2000cwd.googlegroups.com> <7xejosctev.fsf@ruckus.brouhaha.com> <1171494879.866830.102710@m58g2000cwm.googlegroups.com> Message-ID: <1171540156.791003.62330@a75g2000cwd.googlegroups.com> On 15 Feb, 00:14, "sjdevn... at yahoo.com" wrote: > > Yeah, it's the Window equivalent to fork. Does true copy-on-write, so > you can do efficient multiprocess work. Aside from some code floating around the net which possibly originates from some book on Windows systems programming, is there any reference material on ZwCreateProcess, is anyone actually using it as "fork on Windows", and would it be in any way suitable for an implementation of os.fork in the Python standard library? I only ask because there's a lot of folklore about this particular function (everyone seems to repeat more or less what you've just said), but aside from various Cygwin mailing list threads where they reject its usage, there's precious little information of substance. Not that I care about Windows, but it would be useful to be able to offer fork-based multiprocessing solutions to people using that platform. Although the python-dev people currently seem more intent in considering (and now hopefully rejecting) yet more syntax sugar [1], it'd be nice to consider matters seemingly below the python-dev threshold of consideration and offer some kind of roadmap for convenient parallel processing. Paul [1] http://mail.python.org/pipermail/python-dev/2007-February/070939.html From martin at v.loewis.de Sat Feb 3 03:49:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 03 Feb 2007 09:49:03 +0100 Subject: Build Python 2.5 wit VC6.0 ? In-Reply-To: References: Message-ID: <45C44C7F.1010900@v.loewis.de> Alexander Eisenhuth schrieb: > does somebody have experience in building with VC6.0. On my first try > there where missing C-Modules. Is that true. VC6.0 is not supported? It is supported, but not actively maintained. Contributions are welcome. Try the 2.5 maintenance branch first, though; it may have fixed your problem. > PC: What Python version supports VC6.0? The last version where the official Windows binaries were built with VC6 was Python 2.3. Regards, Martin From researchbase at gmail.com Sun Feb 11 02:23:23 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 11 Feb 2007 12:53:23 +0530 Subject: can't find a way to display and print pdf through python. In-Reply-To: <200702110706.l1B76hUa028502@nsa.veriwave.com> References: <200702110706.l1B76hUa028502@nsa.veriwave.com> Message-ID: On 11/02/07, Vishal Bhargava wrote: > Are you trying to do real time or post real time. > -Vishal post real time. I want to first display the report on screen by default and the user at his choice will click the print button and the report will be printed. regards. Krishnakant. From marcin.ciura at poczta.NOSPAMonet.pl Mon Feb 12 15:54:48 2007 From: marcin.ciura at poczta.NOSPAMonet.pl (Marcin Ciura) Date: Mon, 12 Feb 2007 21:54:48 +0100 Subject: Gosper arithmetic in Python Message-ID: Hello, I hacked together a module implementing exact real arithmetic via lazily evaluated continued fractions. You can download it from http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py an use as an almost drop-in replacement for the math module if you don't care too much about performance. I'd be happy to hear any feedback and suggestions. Cheers, Marcin From joshbloom at gmail.com Mon Feb 5 20:48:29 2007 From: joshbloom at gmail.com (joshbloom at gmail.com) Date: 5 Feb 2007 17:48:29 -0800 Subject: Recursive zipping of Directories in Windows In-Reply-To: <1170618143.449135.37580@v33g2000cwv.googlegroups.com> References: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> <1170618143.449135.37580@v33g2000cwv.googlegroups.com> Message-ID: <1170726509.797022.28930@j27g2000cwj.googlegroups.com> On Feb 4, 12:42 pm, "Jandre" wrote: > On Feb 1, 9:39 pm, Larry Bates wrote: > > > > > Jandre wrote: > > > Hi > > > > I am a python novice and I am trying to write a python script (most of > > > the code is borrowed) to Zip a directory containing some other > > > directories and files. The script zips all the files fine but when it > > > tries to zip one of the directories it fails with the following > > > error: > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > > > The script I am using is: > > > > import zipfile, os > > > > def toZip( directory, zipFile ): > > > """Sample for storing directory to a ZipFile""" > > > z = zipfile.ZipFile( > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > > ) > > > def walker( zip, directory, files, root=directory ): > > > for file in files: > > > file = os.path.join( directory, file ) > > > # yes, the +1 is hacky... > > > archiveName = file[len(os.path.commonprefix( (root, > > > file) ))+1:] > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > > > print file > > > os.path.walk( directory, walker, z ) > > > z.close() > > > return zipFile > > > > if __name__ == "__main__": > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > > > I have tried to set the permissions on the folder, but when I check > > > the directory permissions it is set back to "Read Only" > > > > Any suggestions? > > > > Thanks > > > Johan Balt > > > Couple of quick suggestions that may help: > > > 1) don't use 'file' as a variable name. It will mask > > the builtin file function. If it hasn't bitten you before > > it will if you keep doing that. > > > 2) If you put the target .zip file in the directory you are > > backing what do you expect the program to do when it comes > > to the file you are creating as you walk the directory? You > > haven't done anything to 'skip' it. > > > 3) Your commonprefix and +1 appears to result in same > > information that the easier to use os.path.basename() > > would give you. Double check me on that. > > > I don't see anything that references C:\\aaa\temp in your > > code. Does it exist on your hard drive? If so does it > > maybe contain temp files that are open? zipfile module > > can't handle open files. You must use try/except to > > catch these errors. > > > Hope info helps. > > > -Larry > > Thank you Larry. > I've changed the code as epr your advice. The code is now: > > import zipfile, os > > def toZip( directory, zipFile ): > """Sample for storing directory to a ZipFile""" > z = zipfile.ZipFile( > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > ) > def walker( zip, directory, files, root=directory ): > for f in files: > f = os.path.join( directory, f ) > archiveName = os.path.basename(f) > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > print f > os.path.walk( directory, walker, z ) > z.close() > return zipFile > > if __name__ == "__main__": > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > I still get the same error: > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Python24\Scripts\dirZip.py", line 20, in ? > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > File "C:\Python24\Scripts\dirZip.py", line 14, in toZip > os.path.walk( directory, walker, z ) > File "C:\Python24\lib\ntpath.py", line 329, in walk > func(arg, top, names) > File "C:\Python24\Scripts\dirZip.py", line 12, in walker > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > File "C:\Python24\lib\zipfile.py", line 405, in write > fp = open(filename, "rb") > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp' > > c:\\aaa\\temp is a directory in the directory I an trying to zip. I > want to use this script to back up my work once a day and would like > to > keep the directory structure as is. I can zip the files in c:\aaa\tem > fine so I guess that there aren't any open files in the directory. > Any more ideas? Hi Jandre, Your code is treating the directory as a file and trying to open it and read its bytes to zip them. You'll need to differentiate between files and directories. You'll need to check out the Zip module to see how it expects files that should be nested within folders. I believe you'll need to set the archive name for the nested files to something like \\temp\\file.ext etc. -Josh From DustanGroups at gmail.com Wed Feb 21 18:21:25 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 Feb 2007 15:21:25 -0800 Subject: Question about classes and possible closure. In-Reply-To: References: Message-ID: <1172100085.140141.83730@j27g2000cwj.googlegroups.com> On Feb 21, 4:30 pm, "Steven W. Orr" wrote: > This is all an intro learning experience for me, so please feel free to > explain why what I'm trying to do is not a good idea. > > In the Cookbook, they have a recipe for how to create global constants. > > ----------------- > class _const: > class ConstError(TypeError): pass > def __setattr__(self,name,value): > if self.__dict__.has_key(name): > raise self.ConstError, "Can't rebind const(%s)"%name > self.__dict__[name]=value > > import sys > sys.modules[__name__]=_const() > ---------------- > > I'd like to be able to create constants within a class. (Yes I understand > that uppercase names is a far better and easier convention but this is a > learning experience for me.) > > I can't get this to work, but my idea is that MyClass is defined thusly: > > class ConstError(TypeError): pass > class Myclass: > def mprint(self): > print "C1 = ", self._C1 Looking ahead, this should be "self.consts._C1", not "self._Cl". > # Define a subclass to create constants. It refs upself to access > # the uplevel copy of self. It's better to stick with the conventions. But regardless, you have to be consistent, as we see in a moment. > class _const: > class ConstError(TypeError): pass This is redundant. Even though this ConstError and the one defined before the Myclass definition are in completely different scopes, so there's no conflict, I doubt this is what you meant to do. > def __setattr__(_upself,name,value): Notice your first argument here is "_upself", with an underscore. > if upself.__dict__.has_key(name): Now you're using "upself", without an underscore, which is undefined. > raise self.ConstError, "Can't rebind const(%s)"%name Now you're using "self", which is also undefined. > else: > print "Just set something" > upself.__dict__[name]=value Once again, "upself" instead of "_upself". Just follow the convention: always use "self". > > # I want the const instance to be contained in this class so I > # instantiate here in the constructor. > def __init__(self): > upself = self Why "upself = self"? You could just as easily use "self". Follow the conventions. > upself.consts = const() I'm guessing this is your error? That should be "upself.consts = self._const()" > upself.consts._C1 = 0 > setattr(upself.consts, "_C1", 44) Obviously, this is going to raise an error, because you're redefining _Cl. > self = upself Again, why the weird juggling between self and upself? First of all, self and upself are references to the same object right now, so "self = upself" has no after-effect at all. Second of all, even if it did, all it would be doing is reassigning the local variable "self" to a different object; it has no effect on the object you're working with. > Then the call in another file is this: > #! /usr/bin/python > from c2 import Myclass > foo = Myclass() > foo.mprint() > # end > > Is it possible to nest a class in another class and is it possible to make > this work? Yes, it is possible to nest a class in another class. Yes, it is possible to make this work. However, it is good practice to post your error message along with your code, so we don't have to guess. Here's an untested rewrite of your code: class Myclass: def mprint(self): print "C1 = ", self.consts._C1 # Define a subclass to create constants. It refs upself to access # the uplevel copy of self. class _const: class ConstError(TypeError): pass def __setattr__(_upself,name,value): if _upself.__dict__.has_key(name): raise _upself.ConstError, "Can't rebind const(%s)"%name else: print "Just set something" _upself.__dict__[name]=value # I want the const instance to be contained in this class so I # instantiate here in the constructor. def __init__(self): self.consts = const() self.consts._C1 = 0 # This will raise an error!!!! setattr(self.consts, "_C1", 44) > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > happened but none stranger than this. Does your driver's license say Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net From jscrerar at compuserve.com Tue Feb 6 17:10:19 2007 From: jscrerar at compuserve.com (Jim) Date: 6 Feb 2007 14:10:19 -0800 Subject: Recursive zipping of Directories in Windows In-Reply-To: <1170794826.829468.276830@a34g2000cwb.googlegroups.com> References: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> <1170618143.449135.37580@v33g2000cwv.googlegroups.com> <1170726509.797022.28930@j27g2000cwj.googlegroups.com> <1170794826.829468.276830@a34g2000cwb.googlegroups.com> Message-ID: <1170799819.565910.277710@m58g2000cwm.googlegroups.com> On Feb 6, 2:47 pm, "MRAB" wrote: > On Feb 6, 1:48 am, "joshbl... at gmail.com" wrote: > > > > > On Feb 4, 12:42 pm, "Jandre" wrote: > > > > On Feb 1, 9:39 pm, Larry Bates wrote: > > > > > Jandre wrote: > > > > > Hi > > > > > > I am a python novice and I am trying to write a python script (most of > > > > > the code is borrowed) to Zip a directory containing some other > > > > > directories and files. The script zips all the files fine but when it > > > > > tries to zip one of the directories it fails with the following > > > > > error: > > > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > > > > > The script I am using is: > > > > > > import zipfile, os > > > > > > def toZip( directory, zipFile ): > > > > > """Sample for storing directory to a ZipFile""" > > > > > z = zipfile.ZipFile( > > > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > > > > ) > > > > > def walker( zip, directory, files, root=directory ): > > > > > for file in files: > > > > > file = os.path.join( directory, file ) > > > > > # yes, the +1 is hacky... > > > > > archiveName = file[len(os.path.commonprefix( (root, > > > > > file) ))+1:] > > > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > > > > > print file > > > > > os.path.walk( directory, walker, z ) > > > > > z.close() > > > > > return zipFile > > > > > > if __name__ == "__main__": > > > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > > > > > I have tried to set the permissions on the folder, but when I check > > > > > the directory permissions it is set back to "Read Only" > > > > > > Any suggestions? > > > > > > Thanks > > > > > Johan Balt > > > > > Couple of quick suggestions that may help: > > > > > 1) don't use 'file' as a variable name. It will mask > > > > the builtin file function. If it hasn't bitten you before > > > > it will if you keep doing that. > > > > > 2) If you put the target .zip file in the directory you are > > > > backing what do you expect the program to do when it comes > > > > to the file you are creating as you walk the directory? You > > > > haven't done anything to 'skip' it. > > > > > 3) Your commonprefix and +1 appears to result in same > > > > information that the easier to use os.path.basename() > > > > would give you. Double check me on that. > > > > > I don't see anything that references C:\\aaa\temp in your > > > > code. Does it exist on your hard drive? If so does it > > > > maybe contain temp files that are open? zipfile module > > > > can't handle open files. You must use try/except to > > > > catch these errors. > > > > > Hope info helps. > > > > > -Larry > > > > Thank you Larry. > > > I've changed the code as epr your advice. The code is now: > > > > import zipfile, os > > > > def toZip( directory, zipFile ): > > > """Sample for storing directory to a ZipFile""" > > > z = zipfile.ZipFile( > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > > ) > > > def walker( zip, directory, files, root=directory ): > > > for f in files: > > > f = os.path.join( directory, f ) > > > archiveName = os.path.basename(f) > > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > > > print f > > > os.path.walk( directory, walker, z ) > > > z.close() > > > return zipFile > > > > if __name__ == "__main__": > > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > > > I still get the same error: > > > Traceback (most recent call last): > > > File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework > > > \scriptutils.py", line 310, in RunScript > > > exec codeObject in __main__.__dict__ > > > File "C:\Python24\Scripts\dirZip.py", line 20, in ? > > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > > File "C:\Python24\Scripts\dirZip.py", line 14, in toZip > > > os.path.walk( directory, walker, z ) > > > File "C:\Python24\lib\ntpath.py", line 329, in walk > > > func(arg, top, names) > > > File "C:\Python24\Scripts\dirZip.py", line 12, in walker > > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > > > File "C:\Python24\lib\zipfile.py", line 405, in write > > > fp = open(filename, "rb") > > > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp' > > > > c:\\aaa\\temp is a directory in the directory I an trying to zip. I > > > want to use this script to back up my work once a day and would like > > > to > > > keep the directory structure as is. I can zip the files in c:\aaa\tem > > > fine so I guess that there aren't any open files in the directory. > > > Any more ideas? > > > Hi Jandre, > > > Your code is treating the directory as a file and trying to open it > > and read its bytes to zip them. You'll need to differentiate between > > files and directories. > > > You'll need to check out the Zip module to see how it expects files > > that should be nested within folders. I believe you'll need to set the > > archive name for the nested files to something like \\temp\\file.ext > > etc. > > In my experience, zip files don't contain nested folders, instead they > contain a 'flat' list of files. Files in subfolders are represented by > relative path names containing slashes and empty subfolders are > represented by relative paths ending in a slash,.for example > "File1.txt", "Folder1/File2.dat", "Folder2/Folder3/". This seems to > work for me! :-)- Hide quoted text - > > - Show quoted text - What's the matter with PKZIP? It's been around forever. From http Tue Feb 20 12:44:01 2007 From: http (Paul Rubin) Date: 20 Feb 2007 09:44:01 -0800 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> <1171990539.710698.276050@v45g2000cwv.googlegroups.com> <1171992831.871231.86450@h3g2000cwc.googlegroups.com> Message-ID: <7x3b50d8ri.fsf@ruckus.brouhaha.com> "Jay Tee" writes: > >>> l1= [3, 4, 7, 2] > >>> l2 = [2, 3] > >>> l2 = [2, 3, 99] > >>> l1 & l2 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for &: 'list' and 'list' > > what am I missing? They are sets, not lists. from sets import Set as set # use in 2.3 and earlier l1= set([3, 4, 7, 2]) l2 = set([2, 3]) l2 = set([2, 3, 99]) print l1 & l2 From rschroev_nospam_ml at fastmail.fm Sat Feb 3 14:50:28 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 03 Feb 2007 19:50:28 GMT Subject: confused about resizing array in Python In-Reply-To: References: Message-ID: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Ruan schreef: > My confusion comes from the following piece of code: > > memo = {1:1, 2:1} > def fib_memo(n): > global memo > if not n in memo: > memo[n] = fib_memo(n-1) + fib_memo(n-2) > return memo[n] > > I used to think that the time complexity for this code is O(n) due to its > use of memoization. > > However, I was told recently that in Python, dictionary is a special kind of > array and to append new element to it or to resize it, it is in fact > internally inplemented by creating another array and copying the old one to > it and append a new one. That's not correct. Python dictionaries are highly optimized and I believe the time complexity is amortized constant (i.e. O(1)) for both insertions and lookups. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From jonc at icicled.net Fri Feb 2 12:25:49 2007 From: jonc at icicled.net (Jonathan Curran) Date: Fri, 2 Feb 2007 11:25:49 -0600 Subject: Spring Python 0.2.0 is released In-Reply-To: <1170393447.301368.124140@l53g2000cwa.googlegroups.com> References: <1170393447.301368.124140@l53g2000cwa.googlegroups.com> Message-ID: <200702021125.49457.jonc@icicled.net> Greg, You have managed to peak my interest. I'll be dabbling with this in the next few hours. This looks very promising, keep up the good work. - Jonathan From jgrzebyta at NO.gazeta.pl.SPAM Mon Feb 19 13:31:06 2007 From: jgrzebyta at NO.gazeta.pl.SPAM (Jacol) Date: Mon, 19 Feb 2007 18:31:06 +0000 Subject: How to detect closing of wx.Panel? References: Message-ID: Morpheus wrote: > On Mon, 19 Feb 2007 01:18:11 +0000, Jacol wrote: > >> Hi everybody, >> >> I have poblem with detecting closing of wx.Panel by user. How to detect >> that event? > > Don't know why you want to do that, but you could register with the > enclosing (hosting) widget. In my program a panel is related to a plugin's object. I mean if a panel is closed the object have to be deleted also. Currently it doesn't work & i have e memory leak. But i think i'll fixed a panel with its object directly. Currently i did it like that: mainframe(wx.Frame) subobject---> pluginsmanager -->object (a hash session=>object ) subobject---> panel The panel send to pluginsmanager its own session no and received from that XRC. But it is too complicated. I have to do it more simpler. More @ pentrezy.cvs.sf.net// Best wishes, Jacek From paul at boddie.org.uk Fri Feb 2 07:08:21 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Feb 2007 04:08:21 -0800 Subject: Python does not play well with others In-Reply-To: <7x64alp986.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> Message-ID: <1170418101.540654.307320@l53g2000cwa.googlegroups.com> On 2 Feb, 03:46, Paul Rubin wrote: > > I'd say the functionality that John wants is the same that pretty much > everyone wants, and it's much easier to get for other languages than > for Python. If the hosting provider doesn't want to install MySQLdb then it may not be a technical issue - perhaps they just can't be bothered to install it, possibly because there's no demand or benefit to the bottom line in doing so. That said, I think that a large part of the community does no-one any favours by "fashionably" requiring the most cutting edge software, insisting on Python 2.5 in some cases, in order for their stuff to work. Then again, getting stuff to work across several versions (and combinations of several versions of several packages) is an issue of release engineering, and it's no coincidence that companies have made good business out of this kind of thing. Perhaps Python needs a "backports" project where newer software is backported to older Python releases. Alternatively, given the increasing prominence of virtual server hosting, people might be advised to consider one of those hosting plans: the benefits of being able to install almost anything, often with modern operating system distributions whose packages are updated, surely outweigh the administrative demands and price differences in at least some situations. Paul From gagsl-py at yahoo.com.ar Thu Feb 15 22:44:14 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 00:44:14 -0300 Subject: IOError: [Errno 4] Interrupted system call References: <1171594649.279210.139470@l53g2000cwa.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 23:57:29 -0300, escribi?: > i'm getting the same error when trying to read results from popen2 > within a pyQt window. is this a threading issue? is my pyQt window > responsible for interrupting the read? i'm fairly new to python so > i'm struggling to figure this out. can you recommend any possible > methods of preventing this? for instance, could acquiring a thread > lock before calling popen solve the problem? I dont know pyQt but in general, blocking operations (like a syncronous read) can return EINTR when a signal arrives in the middle. Just retrying the operation would be enough; by example, if you have a read() inside a loop, just ignore the exception and continue. -- Gabriel Genellina From nagle at animats.com Sat Feb 3 12:49:19 2007 From: nagle at animats.com (John Nagle) Date: Sat, 03 Feb 2007 09:49:19 -0800 Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" In-Reply-To: References: Message-ID: <8u3xh.51957$QU1.46603@newssvr22.news.prodigy.net> Gabriel Genellina wrote: > En Sat, 03 Feb 2007 06:12:33 -0300, Peter Otten <__peter__ at web.de> > escribi?: > >> John Nagle wrote: >> >>> How do I suppress "DeprecationWarning: Old style callback, use >>> cb_func(ok, >>> store) instead". A library is triggering this message, the library is >>> being fixed, but I need to make the message disappear from the >>> output of a >>> CGI program. >> >> >> import warnings >> warnings.filterwarnings("ignore", message="Old style callback, use >> cb_func(ok, store) instead") Thanks. Actually, just copying the message into the string doesn't work; the matching argument is a regular expression, so "(" has special meaning. But the general idea is right. John Nagle From sjmachin at lexicon.net Mon Feb 5 19:45:55 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Feb 2007 16:45:55 -0800 Subject: Why? In-Reply-To: <1170721943.034518.223210@l53g2000cwa.googlegroups.com> References: <1170721943.034518.223210@l53g2000cwa.googlegroups.com> Message-ID: <1170722755.375900.45660@v33g2000cwv.googlegroups.com> On Feb 6, 11:32 am, "NoName" wrote: > # -*- coding: cp1251 -*- > from glob import glob > > src= "C:\\0000\\????? ?????\\*.*" > print glob(src) > > ['C:\\0000\\\xcd\xee\xe2\xe0\xff \xef\xe0\xef\xea\xe0\\ksdjfk.txt', 'C: > \\0000\\\xcd\xee\xe2\xe0\xff \xef > \xe0\xef\xea\xe0\\\xeb\xfb\xe2\xee\xe0\xeb\xee\xe0\xeb.txt'] > > Why not "C:\\0000\\????? ?????\\ksdjfk.txt" and etc? Search this newsgroup for "glob unicode" From marcin.ciura at poczta.NOSPAMonet.pl Wed Feb 28 14:28:55 2007 From: marcin.ciura at poczta.NOSPAMonet.pl (Marcin Ciura) Date: Wed, 28 Feb 2007 20:28:55 +0100 Subject: finding out the precision of floats In-Reply-To: <1172684085.170332.323490@z35g2000cwz.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172684085.170332.323490@z35g2000cwz.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > I'm not doing 'real world' calcultations, I'm making an app to help > teach children maths. I need numerical values that behave well as > decimals. I also need them to have an arbitrary number of significant > figures. Floats are great but they won't help me with either. Amongst > other things, I need 3.0*0.1==0.3 to be True. I guess that speed is not at premium in your application, so you might try my continued fractions module, advertised here a few weeks ago: http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py It represents rational numbers exactly, and irrational numbers with an arbitrary accuracy, i.e. unlike Decimal it implements exact rather than multiple-precision arithmetic. Once you create an expression, you can pull from it as many decimal digits as you wish. The subexpressions dynamically adjust their accuracy, so that you always get exact digits. Regards, Marcin From paul at boddie.org.uk Thu Feb 22 16:46:46 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Feb 2007 13:46:46 -0800 Subject: Newbie question: Install Tkinter with Python2.5 In-Reply-To: <45de03c6$0$8891$9b622d9e@news.freenet.de> References: <45de03c6$0$8891$9b622d9e@news.freenet.de> Message-ID: <1172180806.514444.155690@l53g2000cwa.googlegroups.com> TK wrote: > > how can I install Tkinter with Python2.5? I can install Python2.5 > (tarball) in the usual way but there is no Tkinter? What's wrong? I see that Tcl/Tk detection has been moved in the Python source distribution (since the "good old days" when I last had to deal with this kind of thing) from the configure machinery to the setup.py program. However, a few things worth checking include (1) whether you not only have the Tcl/Tk libraries but also the Tcl/Tk headers/ includes and (2) whether they're installed in standard places or somewhere else. Look for things like libtcl8.4.so, libtk8.4.so as well as tcl.h and tk.h. If appropriate, check your distribution's packages and make sure you have the developer packages (eg. tcl8.4-dev, tk8.4-dev) installed. Paul From mdfranz at gmail.com Sat Feb 3 14:09:32 2007 From: mdfranz at gmail.com (Matthew Franz) Date: Sat, 3 Feb 2007 13:09:32 -0600 Subject: Create a cookie with cookielib In-Reply-To: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> References: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> Message-ID: <33acb3db0702031109u116dce7au1f1446a1937c03d9@mail.gmail.com> I'm not sure what you mean be forge, but if you mean set an arbitrary cookie manually (vs. one that was provided by the server). just use add_header() in http://docs.python.org/lib/request-objects.html It may be possible to use CookieJar for this purpose but I've only used it for manipulating cookies set by the server... And I would agree that Python cookie APIs are less intuitive than what are available in others such as Jakarta HttpClient.... - mdf On 2/3/07, Alessandro Fachin wrote: > Hi, i am trying to forge a new cookie by own with cookielib. But i don't > still have success. This a simply code: > > import cookielib, urllib, urllib2 > login = 'Ia am a cookie!' > cookiejar = cookielib.CookieJar() > urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) > values = {'user':login} > data = urllib.urlencode(values) > request = urllib2.Request("http://localhost/cookie.php", data) > url = urlOpener.open(request) > print url.info() > page = url.read(500000) > print page > print cookiejar > > the output of this is: > > Date: Sat, 03 Feb 2007 10:20:05 GMT > Server: Apache > X-Powered-By: PHP/5.1.6 > Set-Cookie: user=Alex+Porter; expires=Sat, 03-Feb-2007 11:20:05 GMT > Content-Length: 11 > Connection: close > Content-Type: text/html; charset=UTF-8 > > Array > ( > ) > ]> > > And here is the code of cookie.php that i've create for this example: > > setcookie("user", "Alex Porter", time()+3600); > ?> > // Print a cookie > echo $_COOKIE["user"]; > // A way to view all cookies > print_r($_COOKIE); > ?> > > if anyone could help... Thank you > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matthew Franz http://www.threatmind.net/ From Michel.Al1 at gmail.com Thu Feb 8 14:26:39 2007 From: Michel.Al1 at gmail.com (k0mp) Date: 8 Feb 2007 11:26:39 -0800 Subject: begin to parse a web page not entirely downloaded In-Reply-To: References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> <45cb63d4$0$6842$4d3efbfe@news.sover.net> <1170958856.700750.3080@a75g2000cwd.googlegroups.com> Message-ID: <1170962799.432246.122620@l53g2000cwa.googlegroups.com> On Feb 8, 8:06 pm, Bj?rn Steinbrink wrote: > On Thu, 08 Feb 2007 10:20:56 -0800, k0mp wrote: > > On Feb 8, 6:54 pm, Leif K-Brooks wrote: > >> k0mp wrote: > >> > Is there a way to retrieve a web page and before it is entirely > >> > downloaded, begin to test if a specific string is present and if yes > >> > stop the download ? > >> > I believe that urllib.openurl(url) will retrieve the whole page before > >> > the program goes to the next statement. > > >> Use urllib.urlopen(), but call .read() with a smallish argument, e.g.: > > >> >>> foo = urllib.urlopen('http://google.com') > >> >>> foo.read(512) > >> ' ... > > >> foo.read(512) will return as soon as 512 bytes have been received. You > >> can keep caling it until it returns an empty string, indicating that > >> there's no more data to be read. > > > Thanks for your answer :) > > > I'm not sure that read() works as you say. > > Here is a test I've done : > > > import urllib2 > > import re > > import time > > > CHUNKSIZE = 1024 > > > print 'f.read(CHUNK)' > > print time.clock() > > > for i in range(30) : > > f = urllib2.urlopen('http://google.com') > > while True: # read the page using a loop > > chunk = f.read(CHUNKSIZE) > > if not chunk: break > > m = re.search('', chunk ) > > if m != None : > > break > > > print time.clock() > > > print > > > print 'f.read()' > > print time.clock() > > for i in range(30) : > > f = urllib2.urlopen('http://google.com') > > m = re.search('', f.read() ) > > if m != None : > > break > > A fair comparison would use "pass" here. Or a while loop as in the > other case. The way it is, it compares 30 times read(CHUNKSIZE) > against one time read(). > > Bj?rn That's right my test was false. I've replaced http://google.com with http://aol.com And the 'break' in the second loop with 'continue' ( because when the string is found I don't want the rest of the page to be parsed. I obtain this : f.read(CHUNK) 0.1 0.17 f.read() 0.17 0.23 f.read() is still faster than f.read(CHUNK) From kbk at shore.net Tue Feb 13 00:05:31 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 13 Feb 2007 00:05:31 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200702130505.l1D55V59013755@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 417 open ( -6) / 3565 closed (+12) / 3982 total ( +6) Bugs : 960 open ( -3) / 6498 closed (+19) / 7458 total (+16) RFE : 266 open ( +6) / 251 closed ( +1) / 517 total ( +7) New / Reopened Patches ______________________ stream writing support in wave.py (2007-02-05) http://python.org/sf/1652328 opened by tom tarfile append behavior (2007-02-05) CLOSED http://python.org/sf/1652681 opened by Witten operator.c slice functions need to parse ssize_t (2007-02-07) http://python.org/sf/1654417 opened by Andy Wingo sys.excepthook shows relevant bindings. (2007-02-08) http://python.org/sf/1654974 opened by Nefarious CodeMonkey, Jr. socketmodule fails to build because missing NETLINK_DNRTMSG (2007-02-11) http://python.org/sf/1657276 opened by Aleksandr Koltsoff Add syntax for dynamic attribute access (2007-02-11) http://python.org/sf/1657573 opened by Ben North documentation for element interface (2007-02-12) http://python.org/sf/1657613 opened by Tim Mitchell Patches Closed ______________ CodeContext visibility (2006-08-15) http://python.org/sf/1540869 closed by kbk Auto-completion list placement (2006-12-23) http://python.org/sf/1621265 closed by kbk Make Python Editor Useful Without Full IDLE (2005-01-26) http://python.org/sf/1110205 closed by kbk allow using normal indent width in shell in IDLE (2005-05-06) http://python.org/sf/1196946 closed by kbk configHandler support for raw data (2007-02-01) http://python.org/sf/1650174 closed by kbk tarfile append behavior (2007-02-05) http://python.org/sf/1652681 closed by gustaebel except too broad (2006-08-15) http://python.org/sf/1540849 closed by kbk Creating dicts for dict subclasses (2006-12-14) http://python.org/sf/1615701 closed by rhettinger Fix dict and set docs, re: immutability (2006-01-05) http://python.org/sf/1397711 closed by rhettinger Remove bad PREDICT in ceval.c (2006-03-04) http://python.org/sf/1443159 closed by rhettinger make trace.py --ignore-dir work (2006-10-05) http://python.org/sf/1571379 closed by montanaro Bugfix for #847665 (XMLGenerator dies in namespace mode) (2006-04-02) http://python.org/sf/1463026 closed by loewis New / Reopened Bugs ___________________ IDLE Hung up after open script by command line... (2006-09-20) CLOSED http://python.org/sf/1562193 reopened by faramir2 Nested Objects scope problem (2007-02-05) CLOSED http://python.org/sf/1652387 reopened by kkelchev Nested Objects scope problem (2007-02-05) CLOSED http://python.org/sf/1652387 reopened by kkelchev Nested Objects scope problem (2007-02-05) CLOSED http://python.org/sf/1652387 reopened by kkelchev Nested Objects scope problem (2007-02-05) CLOSED http://python.org/sf/1652387 opened by kkelchev logging formatter %(lineno)d does not work (2007-02-06) http://python.org/sf/1652788 opened by lx_jakal Double free/corruption? (2007-02-06) http://python.org/sf/1653121 opened by Jarek Zgoda print >> f, "Hello" produces no error: normal? (2007-02-06) http://python.org/sf/1653416 opened by E.-O. Le Bigot Python misbehaves when installed in / (patch attached) (2007-02-06) http://python.org/sf/1653457 opened by Chris Webb Problems in datetime.c and typeobject.c. (2007-02-07) CLOSED http://python.org/sf/1653736 opened by ked-tao crash / abort during install (2007-02-06) CLOSED http://python.org/sf/1653753 opened by SAndreason configure does not check/warn/stop for tk/tcl (2007-02-06) CLOSED http://python.org/sf/1653757 opened by SAndreason popen - wrong order on fileobjects in tuple returned (2007-02-07) CLOSED http://python.org/sf/1653940 opened by Emil Lind Installer should split tcl/tk and tkinter install options. (2007-02-07) http://python.org/sf/1654408 opened by Ron Adam thread join() with timeout hangs on Windows 2003 x64 (2007-02-07) http://python.org/sf/1654429 opened by bentoi thirdparty extensions, --enable-shared, static linking (2007-02-08) http://python.org/sf/1655392 opened by Marien Zwart hotshot.stats.load (2004-02-19) http://python.org/sf/900092 reopened by bcannon 3.4.1 comparison methods content (2007-02-09) CLOSED http://python.org/sf/1655683 opened by Jeffrey Miller email.Generator docs contain a bad off-site link (2007-02-08) CLOSED http://python.org/sf/1655800 opened by Forest Wilkinson Typo in Docs (2007-02-09) CLOSED http://python.org/sf/1656078 opened by Thomas Guettler I think, I have found this bug on time.mktime() (2007-02-10) http://python.org/sf/1656559 opened by S?rgio Monteiro Basto shutil.copyfileobj description is incomplete (2007-02-10) http://python.org/sf/1656578 opened by Witten tarfile.TarFile fileobject use needs clarification (2007-02-10) CLOSED http://python.org/sf/1656581 opened by Witten 'Ok' key in options dialog does nothing (2007-02-11) http://python.org/sf/1657034 opened by torhu random.betavariate(-0,5, -0,5) (2007-02-12) CLOSED http://python.org/sf/1658430 opened by Alain Spineux Bugs Closed ___________ IDLE Hung up after open script by command line... (2006-09-20) http://python.org/sf/1562193 closed by kbk HP-UX11.23: module zlib missing (2007-01-31) http://python.org/sf/1648960 deleted by jabt Nested Objects scope problem (2007-02-05) http://python.org/sf/1652387 closed by kkelchev Nested Objects scope problem (2007-02-05) http://python.org/sf/1652387 closed by gbrandl Nested Objects scope problem (2007-02-05) http://python.org/sf/1652387 closed by kkelchev Nested Objects scope problem (2007-02-05) http://python.org/sf/1652387 closed by gbrandl Quitter object masked (2006-05-01) http://python.org/sf/1479785 closed by kbk Arguments tooltip wrong if def contains tuple (2003-08-20) http://python.org/sf/791968 closed by kbk subprocess fails on GetStdHandle in interactive GUI (2005-02-17) http://python.org/sf/1124861 closed by astrand Problems in datetime.c and typeobject.c. (2007-02-07) http://python.org/sf/1653736 closed by loewis crash / abort during install (2007-02-06) http://python.org/sf/1653753 closed by sandreas41 configure does not check/warn/stop for tk/tcl (2007-02-07) http://python.org/sf/1653757 closed by loewis popen - docs - wrong order on fileobjects in tuple returned (2007-02-07) http://python.org/sf/1653940 closed by gbrandl isSequenceType returns True for dict subclasses (<> 2.3) (2006-10-11) http://python.org/sf/1575169 closed by rhettinger builtin enumerate overflows (2006-06-26) http://python.org/sf/1512504 closed by rhettinger 3.4.1 comparison methods content (2007-02-09) http://python.org/sf/1655683 closed by loewis email.Generator docs contain a bad off-site link (2007-02-09) http://python.org/sf/1655800 closed by loewis --enable-shared links extensions to libpython statically (2006-11-22) http://python.org/sf/1600860 closed by loewis Typo in Docs (2007-02-09) http://python.org/sf/1656078 closed by gbrandl tarfile.TarFile fileobject use needs clarification (2007-02-10) http://python.org/sf/1656581 closed by gustaebel decimals compare badly to floats (2007-02-01) http://python.org/sf/1650053 closed by rhettinger XMLGenerator.startElementNS dies on EMPTY_NAMESPACE attribut (2003-11-23) http://python.org/sf/847665 closed by loewis random.betavariate(-0,5, -0,5) (2007-02-12) http://python.org/sf/1658430 closed by gbrandl New / Reopened RFE __________________ [PATCH] Debuggers need a way to change the locals of a frame (2007-02-07) http://python.org/sf/1654367 opened by Fabio Zadrozny dict(key,values) initializer (2007-02-10) http://python.org/sf/1656538 opened by George Sakkis Drop-Handler for Python files (2007-02-10) http://python.org/sf/1656675 opened by Marek Kubica RFE Closed __________ itertools.count wraps around after maxint (2005-10-13) http://python.org/sf/1326277 closed by rhettinger From vithi99 at hotmail.com Thu Feb 1 20:18:49 2007 From: vithi99 at hotmail.com (vithi) Date: 1 Feb 2007 17:18:49 -0800 Subject: win32com.client In-Reply-To: References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170292629.986774.88240@a34g2000cwb.googlegroups.com> Message-ID: <1170379129.022674.121600@v45g2000cwv.googlegroups.com> Hi, If you are saying win32com in part of the python then you are wrong. Here is a prove:- IDLE 1.2 >>> import win32com Traceback (most recent call last): File "", line 1, in import win32com ImportError: No module named win32com >>> you try in your computer On Jan 31, 7:17 pm, "Gabriel Genellina" wrote: > En Wed, 31 Jan 2007 22:17:10 -0300, vithi escribi?: > > > This is not I was looking for. There is a module call > > "win32com.client" in python some people used it If any body know about > > it let me know. > > > On Jan 31, 1:45 pm, Gary Herron wrote: > >> vithi wrote: > >> > Hi > >> > Any one tell me where I can get (or download) python modules win32com > >> > or win32com.client because I have to use "Dispatch" thanks > > >> You want the "python for windows" extension, available from > >> http://sourceforge.net/projects/pywin32/ > > Yes. You get the win32com module from the above url. It's part of that > package, by Mark Hammond, and a lot of people uses it. > > -- > Gabriel Genellina From grahamd at dscpl.com.au Sun Feb 4 19:25:28 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 4 Feb 2007 16:25:28 -0800 Subject: Python does not play well with others In-Reply-To: <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> Message-ID: <1170635127.959645.199560@j27g2000cwj.googlegroups.com> On Feb 5, 9:45 am, John Nagle wrote: > Graham Dumpleton wrote: > > On Feb 4, 1:05 pm, Paul Rubin wrote: > > >>"Paul Boddie" writes: > > >>>Probably the biggest inhibitor, as far as I can see, has been the > >>>server technology chosen. Many hosting providers have historically > >>>offered no better than CGI for Python, whilst PHP runs within Apache > >>>itself, and it has previously been stated that mod_python has been > >>>undesirable with regard to isolating processes from each other. > >>>Consequently, a number of Python people seem to have held out for > >>>other "high performance" solutions, which various companies now offer. > > >>Your point that shared hosting with Python isn't so easy because of > >>insufficient isolation between apps is valid. Maybe Python 3.0 can do > >>something about that and it seems like a valid thing to consider while > >>fleshing out the 3.0 design. > > > To clarify some points about mod_python, since these posts do not > > properly explain the reality of the situation and I feel people are > > getting the wrong impression. > > > First off, when using mod_python it is possible to have it create > > multiple sub interpreters within each Apache child process. > > Realistically, mod_python is a dead end for large servers, > because Python isn't really multi-threaded. The Global Python > Lock means that a multi-core CPU won't help performance. That is not true if 'prefork' MPM is used for Apache which is how most people seem to run it. This is because each Apache child process only run one request at a time and so there isn't normally going to be any contention on the GIL at all. The only case where there would be contention in this arrangement is if the request handlers within Apache had spawned off distinct threads themselves to do stuff. Even then, in this arrangement the main request handler is usually not doing anything and is just waiting for the created thread to finish what it was doing. Thus if only one thread was spawned to do some work or a blocking operation to allow the main thread to timeout, then again there isn't really any contention as only one thread is actually doing anything. If you are trying to embed very intensive operations with threads within Apache then I would suggest it is not really the best design you could use anyway as such things would be much better farmed off to a long running backend process using XML-RPC or some other interprocess communication mechanism. If one is using the "worker" MPM then yes there will be some contention if multiple requests are being handled by mod_python at the same time within the same Apache child process. The downside of this is lessened however by the fact that there are still multiple Apache child processes and Apache will spread requests across all the Apache child processes, thus the amount that may be running concurrently within any one process is less. The basic problem of GIL contention here is no different to a single Python backend process which is handling everything behind Apache. In some respects the Apache approach actually works better as there are multiple processes spreading the load. Your comment on the GIL is therefore partly unjustified in that respect for Apache and mod_python. Your statement in some respect still stands for Python itself when run as a single process, but you linked it to mod_python and Apache which lessens the impact through its architecture of using multiple child processes. Finally we have 'winnt' MPM, again, because this is all in the one process you will have GIL contention in a much more substantial manner. However, I'd suggest that most wouldn't choose Apache on Windows as a major deployment platform. > FastCGI, though, can get all the CPUs going. It takes more > memory, though, since each instance has a full copy of Python > and all the libraries in use. How is that any different to Apache child processes. Each Apache child process has a full copy of Python and the libraries in use. Each Apache child process can be making use of different CPUs. Further, static file requests, plus other requests against PHP, mod_perl etc can when mod_python is also running be on separate CPUs within the same child process when 'worker' MPM is being used. Thus you haven't lost all forms or parallelism that may be possible, it is only within the mod_python world that there will be some GIL contention and only with 'worker' and 'winnt' MPMs, not 'prefork'. It isn't going to lock out non Python stuff from making use of additional CPUs. > (FastCGI is a straightforward transaction processing engine. > Each transaction program is launched in a separate process, and, > once done with one transaction, can be used to do another one > without reloading. When things are slow, the extra transaction processes > are told to exit; when load picks up, more of them are forked. > Security is comparable to CGI.) Apache will also kill off excess child processes when it deems they are no longer required, or create new ones as demand dictates. So, I am still not sure where the big issue is, the architecture of Apache limits the impact of GIL contention in ways that Python alone doesn't. Graham From pDOTpagel at gsf.de Fri Feb 9 09:13:18 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Fri, 9 Feb 2007 14:13:18 +0000 (UTC) Subject: Glob returning an empty list when passed a variable References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: Neil Webster wrote: > area_name_string = '"*% s*"' % (Area_name) > os.chdir(Input) > filename = glob.glob(area_name_string) Too many quotation marks. >>> Area_name='Foo' >>> '"*% s*"' % (Area_name) '"*Foo*"' Unless there are files with funny names containing '"' you will not get a match. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From __peter__ at web.de Tue Feb 27 04:33:12 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Feb 2007 10:33:12 +0100 Subject: Interactive os.environ vs. os.environ in script References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> <1172562212.691747.150310@m58g2000cwm.googlegroups.com> <1172566324.278334.284760@s48g2000cws.googlegroups.com> Message-ID: boris.smirnov at gmail.com wrote: > On Feb 27, 9:31 am, Peter Otten <__pete... at web.de> wrote: >> boris.smir... at gmail.com wrote: >> > Is there another possibility of how to solve it just by adding some >> > lines in script? >> >> I think you have to wrap your script in a shell script >> >> #!/bin/sh >> export LD_LIBRARY_PATH=/path/Linux/rh_linux >> python shrink_bs_070226.py >> >> To avoid that you can have the python script invoke itself, e. g.: >> >> #!/usr/bin/env python >> import os >> if os.environ.get("YADDA") != "whatever": >> print "fix environment" >> os.environ["YADDA"] = "whatever" >> os.system("yadda.py") >> raise SystemExit >> >> print "YADDA is now %r" % os.environ["YADDA"] >> print "do your real stuff" >> >> Peter > > Thanks for the reply. > > If I that good understood I did this: > ********************************** > import sys, re, glob, shutil > import os > > > if os.environ["LD_LIBRARY_PATH"].count('/path/Linux/rh_linux') !=1: > os.environ["LD_LIBRARY_PATH"]=os.environ["LD_LIBRARY_PATH"]+':'+'/ > path/Linux/rh_linux' > os.system("shrink_bs_070226.py") > raise SystemExit > > from qt import * > *********************** > > Is that correct. If yes then it not works. If not then, what's wrong? I don't know. You are not quoting the actual code you are using (from qt import * is definitely not in line 29, and the #!/path/to/your/python is missing). Do you have more than one python version installed? then you may have to put #!/usr/bin/python2.2 or similar in the first line of your script. Peter From google at mrabarnett.plus.com Wed Feb 28 17:54:26 2007 From: google at mrabarnett.plus.com (MRAB) Date: 28 Feb 2007 14:54:26 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172640476.259853.245530@8g2000cwh.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> Message-ID: <1172703266.063800.153890@s48g2000cws.googlegroups.com> On Feb 28, 5:27 am, "troy.melh... at gmail.com" wrote: > > Hi Jeremy, that's the problem I'm having. Where should I type that " > > python setup.py install" ? Once again I'm using Windows system and not > > Unix. Should I move the file to a specific folder under Python 2.5 and > > then type " python setup.py install" in IDLE or Command Line window? > > I get the error "SyntaxError: invalid syntax" with the word "setup" > > hi andy, > > you want to run the windows command prompt, which is called "cmd.exe" > in windows xp. press the "start menu", then select "run", then type > "cmd.exe" without the quotes. > [snip] FYI, a quicker way to the command prompt is Start->All Programs- >Accessories->Command Prompt. From rw at smsnet.pl Mon Feb 5 06:52:30 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 5 Feb 2007 03:52:30 -0800 Subject: python references In-Reply-To: <1170670211.817241.127310@v33g2000cwv.googlegroups.com> References: <1170670211.817241.127310@v33g2000cwv.googlegroups.com> Message-ID: <1170676349.997054.196350@j27g2000cwj.googlegroups.com> dustin.getz at gmail.com wrote: > >>> from Numeric import zeros > >>> p=zeros(3) > >>> p > array([0,0,0]) > >>> p[0] > 0 > >>> x=p[0] `x' is now a reference to immutable integer object with value 0, not to first element of array `p' > >>> x=10 now `x' is a reference to immutable integer object with value 10, array doesn't change > >>> p > array([0,0,0]) #actual behavior > #array([10,0,0]) #desired behavior > > I want x to be a C++-esque reference to p[0] for convenience in a > vector3 class. i dont want accessor methods. i know python can do > this, but it's been a long time since I used it and am unsuccessful in > my googling and docreading. a little help please? You can have such a reference to mutable objects. Consider this: >>> p = [[0,0,0], [0,0,0]] >>> x = p[0] # reference to mutable list object >>> x[0] = 10 >>> p [[10, 0, 0], [0, 0, 0]] -- HTH, Rob From wolf_tracks at invalid.com Thu Feb 8 19:32:43 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 08 Feb 2007 16:32:43 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> <45CBB3CA.7010501@invalid.com> Message-ID: <45CBC12B.2030802@invalid.com> Robert Kern wrote: > W. Watson wrote: > >> Here's the program I ran. >> >> ### begin >> #!/usr/bin/python >> >> # Check mysys >> >> import sys >> print sys.executable >> >> ### end >> >> It put up a black screen in a flash and disappeared. > > Run it from the terminal or execute those lines in the interactive interpreter > in IDLE. Also, you may want to use the Tutor list, instead of comp.lang.python. > It is more geared towards the questions you are asking. > > http://mail.python.org/mailman/listinfo/tutor > I just installed python2.5 and the original program that uses 2.4 works. Thanks for your help. Looks like on this machine that I'll be using 2.4 to continue my education on python. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two million years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From marc at penninga.info Thu Feb 15 10:10:52 2007 From: marc at penninga.info (Marc) Date: 15 Feb 2007 07:10:52 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <1171552252.836469.255740@a75g2000cwd.googlegroups.com> On 15 feb, 07:21, James Stroud wrote: > I guess we differ on what is obvious. This seems obvious to me: > > [1] + (1,) => [1, 1] > (1,) + [1] => (1, 1) > > simply becuase the operand on the left should take precendence because > its "__add__" is called and its "__add__" returns a list. In essence, as > we know the obviously correct behavior for __add__ and __radd__, then it > would be the obviously correct behavior that the above would follow. Given those obviouses, the following seems to me: [1] + (1,) => [1, (1,)] That's the trouble with obvious -- my obvious may not be so obvious to you (and vice versa). That's why the Zen of Python says "In the face of ambiguity, refuse the temptation to guess." (Although it also says "Flat is better than nested", but I'll ignore that for now.) Basically -- if you want Perl, you know where to find it ;-) Marc From http Thu Feb 8 03:32:12 2007 From: http (Paul Rubin) Date: 08 Feb 2007 00:32:12 -0800 Subject: Referencing vars, methods and classes by name References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> <1170922898.358949.194340@h3g2000cwc.googlegroups.com> Message-ID: <7x7iut2goj.fsf@ruckus.brouhaha.com> "Sagari" writes: > $a = 'b'; > $obj =& new $a(); // instantiating class b() Classes are first class objects in python: class b: ..... # define class b We could assign the class object to a variable a = b and make an instance: obj = a() # same as "obj = b()" Continuing that example we could make a dispatch table of classes: class b: ... class c: ... class d: ... table = [b, c, d] # 3 element array, each element is a class i = 1 a = table[i] # this means a = c obj = a() # instantiate c From tiarno at sas.com Fri Feb 23 15:13:25 2007 From: tiarno at sas.com (Tim Arnold) Date: Fri, 23 Feb 2007 15:13:25 -0500 Subject: Finding non ascii characters in a set of files References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:pan.2007.02.23.18.41.03.317525 at gmx.net... > In , Tim Arnold wrote: > >> Here's what I do (I need to know the line number). >> >> import os,sys,codecs >> def checkfile(filename): >> f = codecs.open(filename,encoding='ascii') >> >> lines = open(filename).readlines() >> print 'Total lines: %d' % len(lines) >> for i in range(0,len(lines)): >> try: >> l = f.readline() >> except: >> num = i+1 >> print 'problem: line %d' % num >> >> f.close() > > I see a `NameError` here. Where does `i` come from? And there's no need > to read the file twice. Untested: > > import os, sys, codecs > > def checkfile(filename): > f = codecs.open(filename,encoding='ascii') > > try: > for num, line in enumerate(f): > pass > except UnicodeError: > print 'problem: line %d' % num > > f.close() > > Ciao, > Marc 'BlackJack' Rintsch well, I take it back....that code doesn't work, or at least it doesn't for my test case. but thanks anyway, I'm sticking to my original code. the 'i' came from for i in range. --Tim From gh at gregor-horvath.com Sun Feb 18 04:44:26 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sun, 18 Feb 2007 10:44:26 +0100 Subject: Complex HTML forms In-Reply-To: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> References: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> Message-ID: George Sakkis schrieb: > I'd like to gather advice and links to any existing solutions (e.g. > libraries, frameworks, design patterns) on general ways of writing > complex web forms, as opposed to the typical {name:value} flat model. > A particular case of what I mean by complex is hierarchical forms. For http://toscawidgets.org/ http://docs.turbogears.org/1.0/SimpleWidgetForm -- Greg From __peter__ at web.de Fri Feb 16 08:08:24 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Feb 2007 14:08:24 +0100 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <9ZhBh.1$963.0@newsfe03.lga> Message-ID: Edward K Ream wrote: >> There could be something like from __future__ import print_function > > To repeat: this would be compatible only with Python 2.6. Indeed. Don't lose your nerves over that bunch of casual readers of your thread :-) Peter From sjmachin at lexicon.net Sun Feb 11 15:50:36 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 12:50:36 -0800 Subject: Regular Expressions In-Reply-To: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> Message-ID: <1171227036.789128.188720@q2g2000cwa.googlegroups.com> On Feb 12, 3:35 am, "deviantbunnyl... at gmail.com" wrote: > > That's a little harsh -- regexes have their place, together with pointer > > arithmetic, bit manipulations, reverse polish notation and goto. The > > problem is when people use them inappropriately e.g. using a regex when a > > simple string.find will do. > > > > A quote attributed variously to > > > Tim Peters and Jamie Zawinski says "Some people, when confronted with a > > > problem, think 'I know, I'll use regular expressions.' Now they have two > > > problems." > > > I believe that is correctly attributed to Jamie Zawinski. > > > -- > > Steven > > So as a newbie, I have to ask. I've played with the re module now for > a while, I think regular expressions are super fun and useful. As far > as them being a problem I found they can be tricky and sometimes the > regex's I've devised do unexpected things...(which I can think of two > instances where that unexpected thing was something that I had hoped > to get into further down the line, yay for me!). So I guess I don't > really understand why they are a "bad idea" to use. Regexes are not "bad". However people tend to overuse them, whether they are overkill (like Gabriel's date-splitting example) or underkill -- see your next sentence :-) > I don't know of > any other way yet to parse specific data out of a text, html, or xml > file without resorting to regular expressions. > What other ways are there? Text: Paul Maguire's pyparsing module (Google is your friend); read David Mertz's book on text processing with Python (free download, I believe); modules for specific data formats e.g. csv HTML: htmllib and HTMLParser (both in the Python library), BeautifulSoup (again GIYF) XML: xml.* in the Python library. ElementTree (recommended) is included in Python 2.5; use xml.etree.cElementTree. HTH, John From jeff.templon at gmail.com Fri Feb 23 04:04:37 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 23 Feb 2007 01:04:37 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> Message-ID: <1172221477.057173.22390@q2g2000cwa.googlegroups.com> On Feb 23, 8:48 am, I V wrote: > While that's true, C++ compiler vendors, for example, take backwards > compatibility significantly less seriously, it seems to me. A year or so > ago, I tried compiling something I'd written for g++ 2, using a > then-recent-ish g++ 3; it failed spectacularly. Likewise with Visual C++ 6 > and a Visual C++ 2005. The suggestion that "working programmers" > will reject python if a major version change introduces some backwards > incompatibilities is not borne out by the experience of any other > language I am aware of. The experience with C++ in our project is similar to yours. I think the real reason is that the compiler tries to be more true to the standard than to past implementations; past implementations accepted incorrect syntax, newer "improved" compilers broke backwards compatibility by rejecting the incorrect syntax. Can't blame 'em, C++ syntax is hard ... don't try this at home, kids ... On the other hand, C++ is firmly established as a "serious" language in our community while python is not. So the programmers tend to be more forgiving. There is no perception that compiler developers are *trying* to be difficult by changing the language to break backwards compatibility. That's the difference I think. JT From kavithapython at yahoo.co.in Wed Feb 28 04:46:03 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Wed, 28 Feb 2007 09:46:03 +0000 (GMT) Subject: newbie question(file-delete trailing comma) In-Reply-To: <45E54325.5080506@ensim.com> Message-ID: <261568.87252.qm@web7802.mail.in.yahoo.com> Thanks Sanket,,, But still doesnt solve my problem,,, now my file contains: aa,ba,b,ca,b,c, and so on,,, the comma at the end is deleted,,,but the file contains some junk values,,, kavitha sanket kathalkar wrote: Solution to this problem is: ----------------------------------------------------------------------------------- some=getAllData()------>dictionary tmpstr="" f=open("test.txt", "w") for value in some.values(): tmpstr+= '\%s\,' % value f.writelines(tmpstr.strip(","))---->strings seperated by comma ----------------------------------------------------------------------------------- Thanks sanket kavitha thankaian wrote: > ok,,, > my script writes a dictionary to a file.but i need only the values > from the dictionary which should be sepearted by a comma,,,so i did as > following: > some=getAllData()------>dictionary > f=open("test.txt", "w") > for value in some.values(): > f.writelines('\%s\,' % value )---->strings seperated by comma > when i execute the above code,my test.txt file has the following: > a,b,c,d, > now i need to delete the comma at the end,,,this is my problem,,, > kavitha > > > */Mikael Olofsson /* wrote: > > kavitha thankaian wrote: > > i get an error when i try to delete in file and rename it as out > > file,,the error says > > "permission denied". > > Perhaps you should give us both the exact code you are running and the > complete traceback of the error. That could make things easier. There > can be numerous reasons for "permission denied". > > > actually i need something like following: > > > > in_file = open('in.txt','w') > > for line in in_file: > > line.strip().strip(',') > > > > but when i run the above code,i get an error"bad file descriptor" > > Of course you do! You are opening the file for writing, but your code > attempts to read the file. Probably, you think that the code would > change the lines in the file itself, which it does not, even if it > would > be possible to read from a file opened for writing. > > What's wrong with the code that Mohammad posted? Note that you might > need to close out_file in his code. > > /MiO > -- > http://mail.python.org/mailman/listinfo/python-list > > > ------------------------------------------------------------------------ > Here?s a new way to find what you're looking for - Yahoo! Answers > --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Sat Feb 17 17:20:26 2007 From: fumanchu at amor.org (fumanchu) Date: 17 Feb 2007 14:20:26 -0800 Subject: message processing/threads In-Reply-To: References: Message-ID: <1171750826.501242.280970@a75g2000cwd.googlegroups.com> On Feb 11, 9:30 pm, Jonathan Curran wrote: > I need a program running in the background to process > messages (FIFO order) which I would send using > soap/xmlrpc/pyro (haven't decided yet). According to > my thinking I would need to make this a threaded > application. One thread to process the messages > and the other thread(s) would be used to listen for > messages and insert it into the message queue. You just described a threaded HTTP server ;) (although they aren't strictly FIFO). If you did decide on SOAP or XML-RPC, feel free to grab CherryPy instead of writing your own listener. http://www.cherrypy.org Robert Brewer System Architect Amor Ministries fumanchu at amor.org From boris.smirnov at gmail.com Wed Feb 7 14:56:00 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 7 Feb 2007 11:56:00 -0800 Subject: calling python from msc.adams Message-ID: <1170878159.947213.59670@l53g2000cwa.googlegroups.com> Hello all, i need to call python from msc.adams. the syntax is "mdi -c python exit" I have created a linux script called "run_python" with this content: mdi -c python $* exit then a call this script with a command: run_python script.py param1 param2 .... paramN Everything looks OK, but the problem is that also the last "exit" parameter in run_python script is taken as an input into script.py together with param1 param2 .... paramN. But I need this exit parameter not to send to python but to mdi. Is there anybody who could give me any hint of how to do it? Thank you very much. Regards, Boris From bignose+hates-spam at benfinney.id.au Sat Feb 3 00:18:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Feb 2007 16:18:39 +1100 Subject: Checking default arguments References: Message-ID: <878xffu8cw.fsf@benfinney.id.au> igorr at ifi.uio.no (Igor V. Rafienko) writes: > I was wondering whether it was possible to find out which parameter > value is being used: the default argument or the user-supplied one. > That is: > > def foo(x, y="bar"): > # how to figure out whether the value of y is > # the default argument, or user-supplied? If it doesn't make a difference, use "bar". If it *does* make a difference, use a unique object: ===== wombat.py ===== Y_DEFAULT = object() def foo(x, y=Y_DEFAULT): if y is Y_DEFAULT: # no value for y was supplied else: # y value was specified by caller ===== ===== fnord.py ===== import wombat foo("spam") # 'y' argument gets unique default object foo("spam", "eggs") # 'y' argument is supplied by caller ===== By using a unique object, and comparing on "is", you make it clear that this is never going to match any other value that is created elsewhere in the program. Of course, the "consenting adults" maxim applies: if a perverse user wnats to call 'foo("spam", wombat.Y_DEFAULT)' this doesn't prevent it, but then they've explicitly asked for it. -- \ "A lot of people are afraid of heights. Not me, I'm afraid of | `\ widths." -- Steven Wright | _o__) | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Sun Feb 18 02:57:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 18 Feb 2007 18:57:46 +1100 Subject: Need an identity operator because lambda is too slow References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> <1171779581.504807.113440@v45g2000cwv.googlegroups.com> Message-ID: On Sat, 17 Feb 2007 22:19:41 -0800, Raymond Hettinger wrote: > [Deron Meranda >>] I'm looking for something in >> Python which would act like an identity operator, or I-combinator: a >> do-nothing function. The best I know of is: (lambda x: x), but it is >> not ideal. > > File a feature request on SourceForge and assign to me. This has come > up a couple of times and would be trivial to implement in the operator > or functools modules. I'm surprised. The Original Poster specified [quote] What python needs is something like a built-in "operator.identity" function, which acts like "lambda x:x", but which the byte compiler could recognize and completely optimize away so there is no function call overhead. [end quote] I would have guessed that optimizing the call away would require support from the compiler. -- Steven. From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 05:26:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 16 Feb 2007 21:26:09 +1100 Subject: KeyboardInterrupt not caught References: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> Message-ID: On Fri, 16 Feb 2007 01:47:43 -0800, ruka_at_ wrote: > Hi, > why is KeyboardInterrupt not caught (xp)? > import sys > try: > inp = sys.stdin.read() > except (KeyboardInterrupt, SystemExit): > print "kbd-interr,SystemExit" > except EOFError: > print "eof encountered" I don't think you ever get an EOFError from stdin. If you type ^D immediately, stdin.read() returns an empty string. > except: > print "caught all" > self.showtraceback() I don't imagine you'll get any other exceptions either. Not that it matters, but what's self? > print "normal end" > > result after script startet and ^C hit: >>ctrl_test.py > normal end > Traceback (most recent call last): > File "C:\work\py_src\ctrl_test.py", line 11, in ? > print "normal end" > KeyboardInterrupt It works as expected for me. I seem to have a vague recollection that the keyboard interrupt under Windows isn't ^C but something else... ^Z maybe? -- Steven. From bearophileHUGS at lycos.com Mon Feb 26 15:58:56 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Feb 2007 12:58:56 -0800 Subject: Add images together In-Reply-To: <1172521836.797866.96220@z35g2000cwz.googlegroups.com> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> <54gtc3F214sakU1@mid.uni-berlin.de> <1172521836.797866.96220@z35g2000cwz.googlegroups.com> Message-ID: <1172523536.033424.122230@a75g2000cwd.googlegroups.com> iceman: > What i am trying to do > is to calculate a color-over-time-function for each pixel. Are you using PIL? What does it means color-over-time-function? Bye, bearophile From http Thu Feb 15 01:32:52 2007 From: http (Paul Rubin) Date: 14 Feb 2007 22:32:52 -0800 Subject: threading and multicores, pros and cons References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> <7xzm7gt2sg.fsf@ruckus.brouhaha.com> <7xr6ssdkqo.fsf@ruckus.brouhaha.com> Message-ID: <7xodnwszfv.fsf@ruckus.brouhaha.com> John Nagle writes: > But there are dumb thread implementations that make > a system call for every lock. Yes, a sys call on each lock access would really be horrendous. But I think that in a modern cpu, LOCK XCHG costs as much as hundreds of regular instructions. Doing that on every adjustment of a Python reference count is enough to impact the interpreter significantly. It's not just mutating user data; every time you use an integer, or call a function and make an arg tuple and bind the function's locals dictionary, you're touching refcounts. The preferred locking scheme in Linux these days is called futex, which avoids system calls in the uncontended case--see the docs. From jstroud at mbi.ucla.edu Thu Feb 22 00:30:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 21 Feb 2007 21:30:26 -0800 Subject: Question about classes and possible closure. In-Reply-To: References: Message-ID: James Stroud wrote: > Steven W. Orr wrote: > >> This is all an intro learning experience for me, so please feel free >> to explain why what I'm trying to do is not a good idea. >> >> In the Cookbook, they have a recipe for how to create global constants. >> >> ----------------- >> class _const: >> class ConstError(TypeError): pass >> def __setattr__(self,name,value): >> if self.__dict__.has_key(name): >> raise self.ConstError, "Can't rebind const(%s)"%name >> self.__dict__[name]=value >> >> import sys >> sys.modules[__name__]=_const() >> ---------------- >> >> I'd like to be able to create constants within a class. (Yes I >> understand that uppercase names is a far better and easier convention >> but this is a learning experience for me.) >> >> I can't get this to work, but my idea is that MyClass is defined thusly: >> >> class ConstError(TypeError): pass >> class Myclass: >> def mprint(self): >> print "C1 = ", self._C1 >> >> # Define a subclass to create constants. It refs upself to access >> # the uplevel copy of self. >> class _const: >> class ConstError(TypeError): pass >> def __setattr__(_upself,name,value): >> if upself.__dict__.has_key(name): >> raise self.ConstError, "Can't rebind const(%s)"%name >> else: >> print "Just set something" >> upself.__dict__[name]=value >> >> # I want the const instance to be contained in this class so I >> # instantiate here in the constructor. >> def __init__(self): >> upself = self >> upself.consts = const() >> upself.consts._C1 = 0 >> setattr(upself.consts, "_C1", 44) >> self = upself >> >> Then the call in another file is this: >> #! /usr/bin/python >> from c2 import Myclass >> foo = Myclass() >> foo.mprint() >> # end >> >> Is it possible to nest a class in another class and is it possible to >> make this work? >> >> TIA >> > > > I see no reason to nest classes, ever, as each creates a seperate name > space. Better would be to de-nest _const and make it available to all of > your classes, otherwise you have lost some of its reusability. A class > is esentially the definition of a behavior and so nesting assumes that > the nesting confers upon the outer class that having a nested class > changes its behavior. This is what composition is for. If you want a > reference to a class in your code, then make an assignment: > > > # Const.py > class ConstError(TypeError): pass > > class Const: > def __setattr__(self, name, value): > if hasattr(self, name): > raise ConstError, "Can't rebind const(%s)" % name > else: > print "Just set something" > self.__dict__[name] = value > > > # Myclass.py > import Const > > class Myclass: > > def mprint(self): > print "C1 = ", self.consts._C1 > > def __init__(self): > self.consts = Const() > self.consts._C1 = 0 > # This will raise an error!!!! > self.consts._C1 = 44 > > > This makes a lot more sense and follows the "flat is better than nested" > rule. Notice how, otherwise, ConstError would be triple nested. Now you > can import Const and have constants in all your classes. > > I also pythonized some of your code. > > James should be self.consts = Const.Const() James From enleverlesX.XmcX at XmclaveauX.com Mon Feb 5 12:49:52 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 5 Feb 2007 18:49:52 +0100 Subject: Count nb call of a function, without global var or decorator References: <45c75b0f$0$5090$ba4acef3@news.orange.fr> <52p5c5F1p0r0cU1@mid.individual.net> Message-ID: <45c77058$0$25945$ba4acef3@news.orange.fr> Re! >>> why you didn't use an iterator? If the iterator is extern (to the function), it's like decorator, or global var. If it is internal, it's huge, compare to this.count=this.count+1 (or this.count+=1) @+ Michel Claveau From deets at nospam.web.de Mon Feb 12 08:21:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Feb 2007 14:21:42 +0100 Subject: Progress when parsing a large file with SAX References: <1171277000.671586.191250@q2g2000cwa.googlegroups.com> <53b0r2F1rqg29U1@mid.uni-berlin.de> Message-ID: <53b7v6F1qkl6qU1@mid.uni-berlin.de> Anastasios Hatzis wrote: > Diez B. Roggisch wrote: > > ... > > I got the same problem with large XML as Marc. > > So you deserve also my thanks for the example. :-) > >> class PercentageFile(object): >> >> def __init__(self, filename): >> self.size = os.stat(filename)[6] >> self.delivered = 0 >> self.f = file(filename) >> >> def read(self, size=None): >> if size is None: >> self.delivered = self.size >> return self.f.read() >> data = self.f.read(size) >> self.delivered += len(data) >> return data >> > > I guess some client impl need to call read() on a wrapped xml file until > all portions of the file are read. You should fed the PercentageFile-object to the xml-parser, like this: parser = xml.sax.make_parser() pf = PercentageFile(filename) parser.parse(pf) >> @property >> def percentage(self): >> return float(self.delivered) / self.size * 100.0 >> > > @property? > > What is that supposed to do? It's making percentage a property, so that you can access it like this: pf.percentage instead of pf.percentage() Google python property for details, or pydoc property. Diez From horpner at yahoo.com Fri Feb 2 09:01:21 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 15:01:21 +0100 Subject: division by 7 efficiently ??? References: <1170361512.204099.191740@a75g2000cwd.googlegroups.com> Message-ID: On 2007-02-01, Michael Yanowitz wrote: > I think it is off by 1 in small numbers, off by a little more with large > numbers: >>>> def div7 (N): > ... return (N>>3) + ((N-7*(N>>3))>>3) > ... >>>> div7 (70) > 9 >>>> div7 (77) > 10 >>>> div7 (700) > 98 >>>> div7 (7) > 0 >>>> div7 (10) > 1 >>>> div7 (14) > 1 >>>> div7 (21) > 2 >>>> div7 (700) > 98 >>>> div7 (7000) > 984 > Heh, heh. That's reminding of the "fabulous" O(n) Dropsort algorithm I saw linked from Effbot's blog. -- Neil Cerutti I'm tired of hearing about money, money, money, money, money. I just want to play the game, drink Pepsi, wear Reebok. --Shaquille O'Neal From scott.daniels at acm.org Tue Feb 27 23:31:43 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 27 Feb 2007 20:31:43 -0800 Subject: Walk thru each subdirectory from a top directory In-Reply-To: <1172529799.827628.321760@p10g2000cwp.googlegroups.com> References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <1172529799.827628.321760@p10g2000cwp.googlegroups.com> Message-ID: <12ua1bo77j0n724@corp.supernews.com> Adam wrote: > On Feb 26, 9:28 pm, silverburgh.me... at gmail.com wrote: >> i am trying to use python to walk thru each subdirectory from a top >> directory. Here is my script: .... > > This bit below is from one of my first programs as I'm currently > learning. It is designed to go form the root down and return the full > paths of everything it finds into a list. (I then check the reults for > files paths that exceed a certain length - but you don't need to know > that.) > > > def findallfiles(self, base): > self.results = [] > for root,dirs,files in os.walk(base): > os.chdir(root) ^^^ Mistake here, don't change directories during os.walk ^^^ > self.scan = glob.glob("*") > for r in self.scan: > if root[-1] == "\\": > self.results.append(root + r) > else: > self.results.append(root + "\\" + r) > return self.results def produce_all_files(base): for root, dirs, files in os.walk(base): for r in files: yield os.path.join(root, r) ### possibly also (but I'd only go for files) #for r in dirs: # yield os.path.join(root, r) def findallfiles(base): return list(produce_all_files(base)) -- --Scott David Daniels scott.daniels at acm.org From aisaac at american.edu Tue Feb 20 14:03:58 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 20 Feb 2007 19:03:58 GMT Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <7xd54a6jof.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > There's even a sentiment in some pythonistas to get rid of the [] and {} > notations for lists and dicts, using list((1,2,3)) and dict((1,2),(3,4)) > for [1,2,3] and {1:2, 3:4} respectively. Well then for consistency they must want tuple((1,2,3)) for (1,2,3). Oh oh, that must be tuple(tuple((1,2,3))), no wait ... Alan Isaac From robert.kern at gmail.com Tue Feb 27 19:59:50 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Feb 2007 18:59:50 -0600 Subject: Tuples from List In-Reply-To: References: Message-ID: rshepard at nospam.appl-ecosys.com wrote: > While it should be easy for me to get what I need from a list, it's > proving to be more difficult than I expected. > > I start with this list: > > [ 6.24249034e-01+0.j 5.11335982e-01+0.j 3.67333773e-01+0.j > 3.01189122e-01+0.j 2.43449050e-01+0.j 1.82948476e-01+0.j > 1.43655139e-01+0.j 9.91225725e-02+0.j] No, that's a numpy array. > and I want a list of floats of only the first 6 digits for each value. If I > write: > for i in listname: > print i > > I get this: > > (0.624249034424+0j) > (0.511335982206+0j) > (0.367333773283+0j) > (0.301189121704+0j) > (0.243449050439+0j) > (0.182948475822+0j) > (0.14365513894+0j) > (0.0991225725344+0j) Those aren't tuples, but complex numbers. > I know it's embarrassingly simple, but the correct syntax eludes my > inexperienced mind. What I want is a list [0.62424, 0.51133, ...] so that I > can normalize those values. > > What is the correct syntax, please? # Extract the real components (since the imaginary components are all 0): eigvals = eigvals.real # Normalize the eigenvalues: eigvals /= eigvals.sum() -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mike.klaas at gmail.com Fri Feb 16 16:48:29 2007 From: mike.klaas at gmail.com (Klaas) Date: 16 Feb 2007 13:48:29 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: <1171662509.736715.54400@t69g2000cwt.googlegroups.com> On Feb 16, 6:01 am, "Edward K Ream" wrote: > That's the proof. Can you find a flaw in it? Casting this in terms of theorem proving only obfuscates the discussion. Here is how to maintain a single codebase for this feature: 1. Convert all your print statements to 3.0 print functions, named something else (say, print2()) 2. define a module called compat26 containing: def print2(*args, **kwargs): # code to convert the above to print statements (better still, sys.stdout.write()) 3. in your code: try: from compat26 import print2 except (ImportError, SyntaxError): # python 3.0 print2 = print -Mike From millball54 at yahoo.com Sun Feb 4 07:45:28 2007 From: millball54 at yahoo.com (millball54 at yahoo.com) Date: 4 Feb 2007 04:45:28 -0800 Subject: Hi, I'm new to python In-Reply-To: <1169937837.925954.109310@a75g2000cwd.googlegroups.com> References: <1169905027.776723.194140@a75g2000cwd.googlegroups.com> <1169937837.925954.109310@a75g2000cwd.googlegroups.com> Message-ID: <1170593128.438565.152200@m58g2000cwm.googlegroups.com> Thanks very much guys for your help.. Its been greatly appreciated. From Eric.Gabrielson at gmail.com Tue Feb 6 18:35:43 2007 From: Eric.Gabrielson at gmail.com (Eric.Gabrielson at gmail.com) Date: 6 Feb 2007 15:35:43 -0800 Subject: Coordinate Grid Points In-Reply-To: References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> <1170727428.120082.47690@a75g2000cwd.googlegroups.com> Message-ID: <1170804943.418026.243480@q2g2000cwa.googlegroups.com> On Feb 5, 6:33 pm, James Stroud wrote: > Eric.Gabriel... at gmail.com wrote: > > On Feb 5, 3:29 pm, James Stroud wrote: > > >>Eric.Gabriel... at gmail.com wrote: > > >>>Hello, > >>> I am very knew to python and am attempting to write a program > >>>in python that a friend of mine is having to write in java. I am doing > >>>this for fun and would like some help as to how i can generate random > >>>coordinate points (x,y) and compare them with user inputted coordinate > >>>points. For example how will I be able to access the separate values, > >>>the x from the x,y position. I think I understand everything except > >>>1)the random coordinate points 2) the getting the users inputted x and > >>>y values in one line ("Please guess a coordinate point from (1,1) to > >>>(20,20): ") as opposed to ("Please enter an x value:" and "Please > >>>enter a y value") and finally 3) acessing the x value from the x,y > >>>coordinate function. the assignment description is located here http:// > >>>www.cs.washington.edu/education/courses/142/07wi/homework/ > >>>homework.html if you would like to see a more in depth discription of > >>>the game. > > >>>Many Thanks, > >>>Eric > > >>For 1: see the random module (e.g. random.randint) > >>For 2: see the "eval" function and "raw input" > >>For 2 (without cheating): see the re module. For example: > >>***************************************************************************** > >> ***map(int, re.compile("\(?(\d+),(\d+)\)?").search(inpt).groups())**** > >>***************************************************************************** > >>(Giving you the latter because eval will do this for you anyway.) > > >>Also see "raw_input". > > >>James > > > Thank you very much for your response i will play around with the code > > when I have some time ( hopefully later tonight) but could you please > > breakdown what the part that I surrounded with asterisks, I think I > > recognize it but don't understand it. > > > Eric > > "re" is the regular expression module for python. "re.compile()" > compiles the regular expression into a regular expression object with > certain attributes, one of which is "search". "search" searches a > string, here "inpt", and this produces a "match" (actually a > _sre.SRE_Match) object that has, as one of its attributes, a "groups()" > method that returns matches to the grouped expressions inside the > regular expression, i.e. expressions surrounded by un-escaped parentheses. > > Inside of the quotes is a regular expression string, (that, in general, > should be preceded immediately by a lowercase r--but is not here because > it doesn't matter in this case and I forgot to). map() maps a callable > (here int) to the list of groups returned by groups(). Each group is a > string matching r"\d+" which is an expression for one or more digits. > Each group is converted into an integer and map returns a list of > integers. I escaped the enclosing parentheses and put question marks > (match zero or one) so that the enclosing parentheses would be optional. > This makes all of the following evaluate to [20, 20]: > > "20,20" > "(20,20" > "20,20)" > "(20,20)" > > Except for typos, the middle two would be quite uncommon for user input, > but would match the expression. Note also, that I didn't allow for > whitespace anywhere, which might be expected. Arbitrary whitespace is > matched by r"\s*". > > James Thank you for your help so far, it has been useful but i haven't quite gotten time to figure it out. In the mean time i was posting in a different forum and got given some help (to define a "point" class) I took that advice and am now getting an error relating to it that i have no idea how to fix and was wondering if you might be able to give me a hand. Anyways heres my error: ************************************************************************************************************************ ***File "C:/Documents and Settings/Eric/Desktop/Python/2d guessing game.py", line 11, in *** *** randp = Point(random.randint(1, 20), random.randint(1, 20)) *** ***TypeError: default __new__ takes no parameters *** ************************************************************************************************************************ and heres my code: ************************************************************************************************************************ #Import Random Module import random #classify "Point" class Point(object): def _init_(self, x, y): self.x = x self.y = y #generate random coordinate point randp = Point(random.randint(1, 20), random.randint(1, 20)) #print randp #get user input x = int(raw_input("Enter guessed x value (1-20): ")) y = int(raw_input("Enter guessed y value (1-20): ")) #compare input to randomly generated point attempts = 0 while True: userp = Point(x, y) attempts += 1 if userp.y == randp.y and userp.x == randp.x: print "You got it right!" break elif userp.y == randp.y: if userp.y > randp.x: print "Go west" elif userp.x < randp.x: print "Go east" x = int(raw_input("Enter new x guess: ")) userp = Point(x, y) elif userp.y < randp.y: if userp.x > randp.x: print "Go northwest" elif userp.x < randp.x: print "Go northeast" x = int(raw_input("Enter new x guess: ")) y = int(raw_input("Enter new y guess: ")) userp = Point(x, y) elif userp.x == randp.x: if userp.y > randp.y: print "Go south" elif userp.y < randp.y: print "Go north" y = int(raw_input("Enter new y guess: ")) userp = Point(x, y) print " " print "Number of guesses", attempts ************************************************************************************************************************ From george.sakkis at gmail.com Fri Feb 2 15:33:47 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 2 Feb 2007 12:33:47 -0800 Subject: Python does not play well with others In-Reply-To: <7xr6t89wkw.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> Message-ID: <1170448427.755864.20320@l53g2000cwa.googlegroups.com> On Feb 2, 2:41 pm, Paul Rubin wrote: > "Chris Mellon" writes: > > How about because thats what you pay them for? Seriously. Do you even > > think about what you're saying? Python needs to move MySQL (and only > > MySQL, of course) into the core because installing packages is too > > much of a burden for hosting companies? > > What does "batteries included" mean to you? To me, it means you don't > have to install add-ons. So let's make a 500MB executable and add Numpy, Zope, Django, PIL, pretty much everything actually. Even better, make CheeseShop just a frontend to a build system that adds and updates automatically submitted packages to the core. Problem solved ! . George From franz.steinhaeusler at gmx.at Thu Feb 1 14:57:53 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Thu, 01 Feb 2007 20:57:53 +0100 Subject: Ubunu - Linux - Unicode - encoding References: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> <1m4tymklxmhra.1lcm42759ok57.dlg@40tude.net> Message-ID: <39h4s2h1eck0agttvgl95ntp3oj5smrt0k@4ax.com> On Thu, 1 Feb 2007 16:42:02 +0100, Alan Franzoni wrote: >Il Thu, 01 Feb 2007 16:02:52 +0100, Franz Steinhaeusler ha scritto: > >> The case: >> I have a file on a WindowsXP partition which has as contents german >> umlauts and the filename itself has umlauts like i????k.txt > >Could you please tell us a) which filesystem is that partition using (winxp >may be installed on fat32 or ntfs partitions) and b) which driver are you >using to read that partition (may be vfat, ntfs or fuse/ntfs-3g) and, last >but not least, c) which options are passed to that driver? Hallo Alan, thank you for answering. a) FAT32 b) hm, don't know, I mounted it in fstab as FAT32# in fstab there is: c)/dev/hda1 /winxp auto rw,user,auto 0 One problem is still, and is a little OT perhaps here, but nevertheless,: If I copy files with german umlauts (??? and strong 's' ?), these filenames are not copied properly, and that characters are replaces by little square symbols. Is there anythin to set up on ubuntu to copy this properly. I have only installed the english language, maybe that is the problem. -- Franz Steinhaeusler From silovana.vjeverica at com.gmail Fri Feb 23 07:05:35 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Fri, 23 Feb 2007 13:05:35 +0100 Subject: Module trouble [newbie] References: <54830uF1ukj2kU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Are you sure the above is what you really used for your test? Because your > output features a single 100, which the above lacks a print-statement for. Yeah, I cancelled the message, but synchronization allready happened. :) Problem was in some other place. One more question: is calling import inside function definition poor design? e.g. def foo(): doSomething: import someModule someModule.doSomethin -- http://www.nacional.hr/articles/view/23894/23 From steve at holdenweb.com Wed Feb 7 17:21:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Feb 2007 22:21:30 +0000 Subject: string.find for case insensitive search In-Reply-To: References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: Don Morrison wrote: > string.find is deprecated as per the official python documentation. > but the str.find() method isn't. > take a look at the "re" module > A possibility. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gagsl-py at yahoo.com.ar Mon Feb 19 00:11:33 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 02:11:33 -0300 Subject: Getting a class name References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> <1171818881.871094.295870@v33g2000cwv.googlegroups.com> <45d8df9d$0$28886$426a74cc@news.free.fr> <1171843008.635203.50290@v45g2000cwv.googlegroups.com> Message-ID: En Sun, 18 Feb 2007 20:56:48 -0300, Fuzzyman escribi?: > [somebody] wrote: >> >>> > def getCodeName(deap=0): >> >>> > return sys._getframe(deap+1).f_code.co_name >> >> >>> > class MyClass (object): >> >>> > name = getCodeName() + '!' >> >> >>> What's the advantage over MyClass.__name__? >> > I were asking, why do you want a "name" attribute since "__name__" >> > already exists and has the needed information. And worst, using an >> > internal implementation function to do such task. >> >> This might be useful to avoid metaclass hacks when trying to initialize >> a class attribute that would require the class name. (my 2 cents) > > It's still an ugly hack. :-) > (But a nice implementation detail to know about none-the-less.) Having class decorators would be nice... -- Gabriel Genellina From bjourne at gmail.com Thu Feb 15 04:15:56 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 15 Feb 2007 10:15:56 +0100 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <740c3aec0702150115i76f00334jc674d2b30cbb1e3@mail.gmail.com> On 2/15/07, James Stroud wrote: > I guess we differ on what is obvious. This seems obvious to me: > > [1] + (1,) => [1, 1] > (1,) + [1] => (1, 1) I agreed with you up to this point. But this seems more obvious to me: [1] + (1,) => [1, 1] (1,) + [1] => [1, 1] In other languages and situations, types are widened, 1 + 1.0 = 1.0 + 1.0. And list is "wider" than tuple. -- mvh Bj?rn From fuzzyman at gmail.com Mon Feb 19 15:25:56 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 19 Feb 2007 12:25:56 -0800 Subject: Getting a class name In-Reply-To: References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> <1171818881.871094.295870@v33g2000cwv.googlegroups.com> <45d8df9d$0$28886$426a74cc@news.free.fr> <1171843008.635203.50290@v45g2000cwv.googlegroups.com> Message-ID: <1171916756.796893.133000@v45g2000cwv.googlegroups.com> On Feb 19, 5:11 am, "Gabriel Genellina" wrote: > En Sun, 18 Feb 2007 20:56:48 -0300, Fuzzyman escribi?: > > > > > [somebody] wrote: > >> >>> > def getCodeName(deap=0): > >> >>> > return sys._getframe(deap+1).f_code.co_name > > >> >>> > class MyClass (object): > >> >>> > name = getCodeName() + '!' > > >> >>> What's the advantage over MyClass.__name__? > >> > I were asking, why do you want a "name" attribute since "__name__" > >> > already exists and has the needed information. And worst, using an > >> > internal implementation function to do such task. > > >> This might be useful to avoid metaclass hacks when trying to initialize > >> a class attribute that would require the class name. (my 2 cents) > > > It's still an ugly hack. :-) > > (But a nice implementation detail to know about none-the-less.) > > Having class decorators would be nice... > Yes - and Guido said he wouldn't be opposed to the idea when it was poitned out that they would be very useful for both IronPython and Jython to implement features of their underlying platforms. I haven't heard anyone (other than you) mention them recently though... Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -- > Gabriel Genellina From rkmr.em at gmail.com Tue Feb 20 23:08:43 2007 From: rkmr.em at gmail.com (mark) Date: Tue, 20 Feb 2007 20:08:43 -0800 Subject: getting a thread out of sleep Message-ID: Right now I have a thread that sleeps for sometime and check if an event has happened and go back to sleep. Now instead I want the thread to sleep until the event has occured process the event and go back to sleep. How to do this? thanks mark class eventhndler(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: time.sleep(SLEEPTIME) ''''do event stuff''' From steve at REMOVE.THIS.cybersource.com.au Mon Feb 26 16:54:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Feb 2007 08:54:46 +1100 Subject: Help on Dict References: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> Message-ID: On Mon, 26 Feb 2007 18:16:13 +0000, Dennis Lee Bieber wrote: > On Mon, 26 Feb 2007 17:58:34 +1100, Steven D'Aprano > declaimed the following in > comp.lang.python: > >> >> Which I think was deliberate. The Original Poster asked a reasonable >> question in a stupid way (Python is case-insensitive -- are we supposed > case-Sensitive Gah!!!! Finger-fart. I was *thinking* _sensitive_, but my fingers typed _insensitive_. I hate it when that happens. -- Steven. From arnodel at googlemail.com Wed Feb 28 15:22:03 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 28 Feb 2007 12:22:03 -0800 Subject: finding out the precision of floats In-Reply-To: References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172684085.170332.323490@z35g2000cwz.googlegroups.com> Message-ID: <1172694123.419841.281230@t69g2000cwt.googlegroups.com> On Feb 28, 7:28 pm, Marcin Ciura wrote: > I guess that speed is not at premium in your application, > so you might try my continued fractions module, > advertised here a few weeks ago:http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py Thanks for the link, I've had a quick glance and it seems great. I'll have to take a closer look to see if I can use it for this app, but in general it looks like a very useful piece of code. -- Arnaud From fccoelho at gmail.com Thu Feb 22 09:51:02 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 06:51:02 -0800 Subject: plugin development best practices In-Reply-To: <545o3qF1v23j6U1@mid.uni-berlin.de> References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> <1172154115.054296.214120@t69g2000cwt.googlegroups.com> <545o3qF1v23j6U1@mid.uni-berlin.de> Message-ID: <1172155861.892583.224240@v45g2000cwv.googlegroups.com> On Feb 22, 12:36 pm, "Diez B. Roggisch" wrote: > > Simple plugin system proposal: > > > have a package (directory with __init__.py) called plugins where the > > actual plugins are modules in this directory. > > > When the main script imports the plugins package, all plugin modules > > would be available as plugins.pluginA, plugins.pluginB , etc. > > > A registry of available plugins would be available as a simple > > dir(plugins). > > > code in the main script than wished to use a given plugin, would only > > have to look in the registry before calling any code from a given > > plugin. > > > What is wrong/missing with this simple framework? > > Nothing wrong. It's just one way of doing it. But it requires you to have > all plugins being part of one module, in one location. Depending on what > you want to do, this won't suffice. For example if your app is installed in > a system path you aren't supposed to write to - how do you install your > individual plugin? easy_install allows you to install to a folder that is > contained in the PYTHONPATH, and then you can discover entrypoints. > > But please, do as we suggested: read the past discussions. > > Depending on what _you_ actually want to accomplish, you're proposal is > enough. But don't expect it to become the "one plugin system to rule them > all"-solution. > > diez Oh, I have read all the links that have been suggested, but I am looking for the simplest possible solution. I have no intention to create the "next Plugin system" I am just trying to solve my own problem and in the process leave a record of a fruitfull discussion about plugin systems. BTW I have yet to check TRAC's plugin system. From duncanm255 at hotmail.com Thu Feb 1 07:35:30 2007 From: duncanm255 at hotmail.com (D) Date: 1 Feb 2007 04:35:30 -0800 Subject: Tkinter Scrolling Message-ID: <1170333328.141317.275130@q2g2000cwa.googlegroups.com> I'm sure this is a simple question to the Tkinter experts - I have a very basic Tkinter application that consists of 1 master window and buttons within that window. My problem is that, I need to be able to scroll (up and down) when I get to the point that the buttons go off the screen. What's the easiest way to do this? Thanks in advance. From bg_ie at yahoo.com Mon Feb 26 09:01:49 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 26 Feb 2007 06:01:49 -0800 Subject: Copy a module build to another machine Message-ID: <1172498509.462232.242990@t69g2000cwt.googlegroups.com> Hi, I have downloaded the source for PyXML-0.8.4, which has no binaries available for Python 2.5. Therefore I built it myself doing something like this - python2.5 setup.py build python2.5 setup.py install having installed cygwin (with gcc). Now lets say I'd like to install PyXML-0.8.4 on a number of other machines running the same os, what files would I need to copy, and to where, in order to install PyXML with just the line - python2.5 setup.py install In other words, I don't want to have to install cygwin on all these machines and build for each machine. Instead I want to create a simple install. Thanks for your help, Barry. From cvanarsdall at mvista.com Mon Feb 5 14:32:59 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Mon, 05 Feb 2007 11:32:59 -0800 Subject: Finding cpu time spent on my program In-Reply-To: <1170703427.559432.155740@k78g2000cwa.googlegroups.com> References: <1170664629.719220.249570@k78g2000cwa.googlegroups.com> <1170703427.559432.155740@k78g2000cwa.googlegroups.com> Message-ID: <45C7866B.60502@mvista.com> kyosohma at gmail.com wrote: > On Feb 5, 2:37 am, "jm.sur... at no.spam.gmail.com" > wrote: > >> I am trying to measure the time the processor spends on some >> operation, and I want this measure to not depend on the current load >> of the machine. But doing the following prints different values each >> time a run. >> >> import time >> c1 = time.clock() >> for x in xrange(0xFFFFF): pass >> >> c2 = time.clock() >> print "Time spent is %f" % (c2-c1) >> >> Is there a way to measure the number of cpu cycles spent on my program >> alone irrespective of the current load etc of the machine. >> There's an performance testing suite that you might also find useful. Check out TAU: Tuning and Analysis Utilities toolkit (simple google search will take you to the page). You can get some serious numbers using that thing and they have python support as well as some tools for automatically profiling an entire application. Check it out. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From devicerandom at gmail.com Mon Feb 12 13:13:22 2007 From: devicerandom at gmail.com (devicerandom at gmail.com) Date: 12 Feb 2007 10:13:22 -0800 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Message-ID: <1171304001.949621.110870@p10g2000cwp.googlegroups.com> > Most of the above should be straight-forward. I used type(cmd.Cmd)(name, > bases, classdict) instead of just type(name, bases, classdict) because > cmd.Cmd is a classic class. It seems it works. It is not so straight-forward to me because I don't know about new-style types and classes very well, but I'm looking at type() and it makes full sense. I'll also look into new style classes. Thanks a lot. Anyway, just for the sake of asking: since I have no formal CS education (I'm a biophysics ph.d. student), I wonder if there is some kind of design pattern/coding tool that could work better/help me along simple inheritance for coding plugin architectures (inheritance probably works well in this case, but I'd like to know what's in the swiss army knife). Thanks again, Massimo From tiedon_jano at hotmail.com Sat Feb 3 10:27:06 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sat, 03 Feb 2007 15:27:06 GMT Subject: compound statement from C "?:" In-Reply-To: References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> Message-ID: Peter Otten kirjoitti: > Isn't that obvious? Don't do it in one line: > > if n == 1: > print "I saw a car" > else: > print "I saw %d cars" % n > > I guess that most of us will have read, understood, and verified (are there > any errors or cases that should be covered but aren't) those four lines > faster than any of the "smart" constructs, including the official 2.5 > ternary operator. Now modify all proposed versions to print > > I didn't see any cars > I saw 7 cars missing > > for n=0 and n=-7, respectively, and you will see 1 light :-) > > Peter > It's naturally clear that a combination of if-elifs-else is more adaptable to different situations, but the OP's question was: I would like to do the equivalent if python of the C line: printf("I saw %d car%s\n", n, n != 1 ? "s" : "") In this question I thought I recognized the familiar tool=hammer==>problem:nail pattern of thought and tried to show that in addition to the ternary operator Python has other ways of resolving that particular problem of his. I'm certainly not an advocate of one-liners because at their extreme they easily result in write-only solutions. Cheers, Jussi From gagsl-py at yahoo.com.ar Mon Feb 5 20:04:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 22:04:26 -0300 Subject: Why? References: <1170721943.034518.223210@l53g2000cwa.googlegroups.com> Message-ID: En Mon, 05 Feb 2007 21:32:23 -0300, NoName escribi?: > # -*- coding: cp1251 -*- > from glob import glob > > src= "C:\\0000\\????? ?????\\*.*" print "src=",src print "repr(src)=",repr(src) > print glob(src) for fn in glob(src): print fn > > > > > > ['C:\\0000\\\xcd\xee\xe2\xe0\xff \xef\xe0\xef\xea\xe0\\ksdjfk.txt', 'C: > \\0000\\\xcd\xee\xe2\xe0\xff \xef > \xe0\xef\xea\xe0\\\xeb\xfb\xe2\xee\xe0\xeb\xee\xe0\xeb.txt'] > > Why not "C:\\0000\\????? ?????\\ksdjfk.txt" and etc? glob returns a list; when you print a list, it uses repr() on its elements. It *looks* strange, but has the right contents. See the above modifications. -- Gabriel Genellina From eisenhau at nb.sympatico.ca Thu Feb 8 17:11:55 2007 From: eisenhau at nb.sympatico.ca (Reid) Date: Thu, 08 Feb 2007 22:11:55 GMT Subject: Newbie Question Message-ID: Hello all I am just starting to play with programing again as a hobby. I have heard good things about python. I have not really looked into the language much. My question is, will python make programs with a gui under windows xp. If it will do this I will explore the language more, if not I will try some other language. Reid From rhamph at gmail.com Wed Feb 21 06:17:35 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 21 Feb 2007 03:17:35 -0800 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: <1171976910.217520.53970@l53g2000cwa.googlegroups.com> References: <1171976910.217520.53970@l53g2000cwa.googlegroups.com> Message-ID: <1172056655.098669.120900@a75g2000cwd.googlegroups.com> On Feb 20, 6:08 am, "John Machin" wrote: > >>> for x in b: > > ... tot += x > ... print repr(x), repr(tot) > ... > 0.20000000000000001 0.20000000000000001 > 0.20000000000000001 0.40000000000000002 > 0.20000000000000001 0.60000000000000009 > 0.20000000000000001 0.80000000000000004 > 0.10000000000000001 0.90000000000000002 > 0.10000000000000001 1.0 > > > > As you can see, 0.1 and 0.2 can't be represented exactly as floating > point numbers. Consequently there is only a rough chance that they > will add up to what you think they should add up to. Although your point is correct, this is actually a myth about repr. The goal of repr is to be able to round-trip all numbers, so eval(repr(n)) == n. From that perspective it would be perfectly legal if it printed out a nice and short "0.2" or "0.1". As for the actual value, although you can't express all non-repeating base-10 values with non-repeating base-2, you can express base-2 with base-10. It just gets a little long: >>> '%.60f' % 0.2 '0.200000000000000011102230246251565404236316680908203125000000' >>> '%.60f' % 0.1 '0.100000000000000005551115123125782702118158340454101562500000' Unfortunately this method of printing out floats won't work for smaller values, since the %f formatting limits the number of decimal places. But if you want a more compact exact representation I have bodged together a way of printing out floats in base-16: >>> hexfloat(0.2) hexfloat('0.33333333333334') >>> hexfloat(0.1) hexfloat('0.1999999999999A') Interesting, if a bit confusing. From cyberco at gmail.com Tue Feb 6 15:26:16 2007 From: cyberco at gmail.com (cyberco) Date: 6 Feb 2007 12:26:16 -0800 Subject: Python cheatsheets In-Reply-To: <45c8bcdc$0$27369$ba4acef3@news.orange.fr> References: <1170762374.981099.22010@v45g2000cwv.googlegroups.com> <45c8bcdc$0$27369$ba4acef3@news.orange.fr> Message-ID: <1170793576.161017.116320@s48g2000cws.googlegroups.com> > If you have a good color printer, try PQRChttp://www.limsi.fr/Individu/pointal/python/pqrc/ That is a very usefull document to use besides Richard Gruets quick ref. The only disadvantage is that it's a PDF document, pity there's no HTML version. 2B From sickcodemonkey at gmail.com Sun Feb 18 21:37:02 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Sun, 18 Feb 2007 21:37:02 -0500 Subject: Python Threads In-Reply-To: <2adc542f0702181516g7bbfb08ga721b568cb528404@mail.gmail.com> References: <2adc542f0702181516g7bbfb08ga721b568cb528404@mail.gmail.com> Message-ID: <2adc542f0702181837g3c433742ha0fedd775d8cc0fa@mail.gmail.com> Well if this cannot be done, can a thread call a function in the main method? I have been trying and have not been successive. Perhaps I am using thread incorrectly. On 2/18/07, Sick Monkey wrote: > > Is there anyway to get 2 python threads to talk to one another? > > I have a GUI which is spawning a thread to make a large calculation (that > way the GUI does not appear to be non responsive). I am trying to attach a > progress bar to the threaded action. As the thread is calculating data, I > would like it to communicate with the other (progress) thread to update it. > > On windows, when I spawn the progress bar without using threads, the > progress bar stalls.... <> So I thought by > spawning the progress bar by using a thread, it would not stall....... If > anyone can think of another technique.... I am all ears. > > ~~~~~~~~~~START SAMPLE~~~~~~~~~~~~~~~~~~~~~~~~ > def progressBar(status): > mroot = Tkinter.Tk(className='Worker Bee') > metric = Meter(mroot, relief='ridge', bd=3) > metric.pack(fill='x') > metric.set(status, 'Starting ...') > > def fetchFiles(file1,file2,file3): > method = '' > print file1 > print file2 > print file3 > f1 = fopen(file1) > a = f1.readlines(); f1.close() > d1 = {} > for c in a: > for m in mailsrch.findall(c): > d1[m.lower()] = None > > ####I Would like to Update the progress bar running in the other > thread here. > ## set status = .33 and update progress bar. > if file2 == '': > domain(d1,file3) > #... > > def startProc(): > status = 0 > thread.start_new_thread(fetchFiles, (f1name,f2name,f3name,)) > thread.start_new_thread(progressBar, (status,)) > > ~~~~~~~~~~END SAMPLE~~~~~~~~~~~~~~~~~~~~~~~~ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Fri Feb 16 16:28:35 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Feb 2007 22:28:35 +0100 Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: On 2007-02-16, ifti_crazy at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language > but i am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net > > so will you please guide me which GUI based language has worth > with complete OOPS Characteristics > > will wait for the answer > > hope to have a right direction from you Programmer Heck, yeah! Python rules! It will be perfect for your next language acquisition. (Well, what else did you excect a denizen of a Python group to tell you?) -- Neil Cerutti Baseball has the great advantage over cricket of being sooner ended. --George Bernard Shaw From duncan.booth at invalid.invalid Wed Feb 28 11:33:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Feb 2007 16:33:45 GMT Subject: Python Source Code Beautifier References: <1gvfzpau4gxx3$.1r9poiuldqrtm$.dlg@40tude.net> Message-ID: Alan Franzoni wrote: > Yeah, that's right, it could have semantic differences, but that > shouldn't be the case anyway. I mean, if I don't define an __iadd__ > method, writing > > a += n > > or > > a = a + n > > is just the same, right? > > > So, if I bother to define an __iadd__ method, I should make sure it > works just the same, or I would introduce a very strange and > hard-to-understand behaviour. > If a is mutable and has an appropriate __iadd__ method which mutates it then the first of those will mutate the original object and the second will create a new object. That might not matter much if 'a' is the only name referring to the object, but if there are any other ways to access it then it will matter. Compare: >>> lst = [1, 2, 3] >>> n = ['oops'] >>> a = lst >>> a = a + n >>> a [1, 2, 3, 'oops'] >>> lst [1, 2, 3] >>> lst = [1, 2, 3] >>> n = ['oops'] >>> a = lst >>> a += n >>> a [1, 2, 3, 'oops'] >>> lst [1, 2, 3, 'oops'] From Afro.Systems at gmail.com Wed Feb 28 01:33:57 2007 From: Afro.Systems at gmail.com (Tzury) Date: 27 Feb 2007 22:33:57 -0800 Subject: Python, Embedded linux and web development In-Reply-To: <1172579243.995924.87580@m58g2000cwm.googlegroups.com> References: <1172578332.957236.247800@8g2000cwh.googlegroups.com> <1172579243.995924.87580@m58g2000cwm.googlegroups.com> Message-ID: <1172644437.735708.47030@8g2000cwh.googlegroups.com> On Feb 27, 2:27 pm, "Paul Boddie" wrote: > On 27 Feb, 13:12, "Tzury" wrote: > > > > > c) small web application that will be used as front end to configure > > the system (flat files and sqlite3 db are the back-end). > > > Our platform is base on the Intel PXA270 processor (XSCALE family, > > which is ARM compatible) running at 312MHz. > > You might want to read this article which got mentioned fairly > recently either on comp.lang.python or on some blog or other: > > http://www.linuxdevices.com/articles/AT5550934609.html > > Paul Thanks for the quick response. good article From horpner at yahoo.com Tue Feb 6 21:14:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 07 Feb 2007 02:14:01 GMT Subject: Trouble fixing a broken ASCII string - "replace" mode in codec not working. References: Message-ID: On 2007-02-06, Robert Kern wrote: > John Nagle wrote: >> File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch >> sitetext = sitetext.encode('ascii','replace') # force to clean ASCII >> >> UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in >> position 29151: ordinal not in range(128) >> >> Why is that exception being raised when the codec was told 'replace'? > > The .encode('ascii') takes unicode strings to str strings. > Since you gave it a str string, it first tried to convert it to > a unicode string using the default codec ('ascii'), just as if > you were to have done unicode(sitetext).encode('ascii', > 'replace'). > > I think you want something like this: > > sitetext = sitetext.decode('ascii', 'replace').encode('ascii', 'replace') This is the cue for the translate method, which will be much faster and simpler for cases like this. You can build the translation table yourself, or use maketrans. >>> asciitable = string.maketrans(''.join(chr(a) for a in xrange(127, 256)), ... '?'*127) You'd only want to do that once. Then to strip off the non-ascii: sitetext.translate(asciitable) I used a similar solution in an application I'm working on that must uses a Latin-1 byte-encoding internally, but displays on stdout in ascii. -- Neil Cerutti From larry.bates at websafe.com Wed Feb 7 16:14:06 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 07 Feb 2007 15:14:06 -0600 Subject: string.find for case insensitive search In-Reply-To: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: <45CA411E.2000409@websafe.com> Johny wrote: > Is there a good way how to use string.find function to find a > substring if I need to you case insensitive substring? > Thanks for reply > LL > Maybe something like: x="my string I'm going to SEarCH" hasword='SEARCH' in x.upper() location=x.upper().find('SEARCH') print hasword True print location 23 -Larry From george.sakkis at gmail.com Mon Feb 19 23:39:29 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 19 Feb 2007 20:39:29 -0800 Subject: Bypassing __setattr__ for changing special attributes Message-ID: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> I was kinda surprised that setting __class__ or __dict__ goes through the __setattr__ mechanism, like a normal attribute: class Foo(object): def __setattr__(self, attr, value): pass class Bar(object): pass >>> f = Foo() >>> f.__class__ = Bar >>> print f.__class__ is Foo True Is there a way (even hackish) to bypass this, or at least achieve somehow the same goal (change f's class) ? George From http Sat Feb 10 15:44:57 2007 From: http (Paul Rubin) Date: 10 Feb 2007 12:44:57 -0800 Subject: Question about strftime References: <1171139392.261505.9350@l53g2000cwa.googlegroups.com> Message-ID: <7xfy9dwxme.fsf@ruckus.brouhaha.com> silverburgh.meryl at gmail.com writes: > date = strftime("%Y%m%d_%H%M%S", gmtime()) > print date > > I run the script at 2:18 pm, but I get this: 20070210_201837 > Can you please tell me why I get '20'? instead of '14' (which is 2:00 > pm)? Wrong time zone? Maybe you want localtime() instead of gmtime(). From greg at cosc.canterbury.ac.nz Tue Feb 6 18:59:36 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 07 Feb 2007 12:59:36 +1300 Subject: Coordinate Grid Points In-Reply-To: <1170804943.418026.243480@q2g2000cwa.googlegroups.com> References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> <1170727428.120082.47690@a75g2000cwd.googlegroups.com> <1170804943.418026.243480@q2g2000cwa.googlegroups.com> Message-ID: <45C91668.6070109@cosc.canterbury.ac.nz> Eric.Gabrielson at gmail.com wrote: > class Point(object): > def _init_(self, x, y): The name of the __init__ method needs *two* underscores at each end, i.e. def __init__(self, x, y): -- Greg From aboudouvas at panafonet.gr Wed Feb 7 17:06:11 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 7 Feb 2007 14:06:11 -0800 Subject: Object type check In-Reply-To: <45ca4035$0$4321$426a74cc@news.free.fr> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <45ca32ed$0$32232$426a74cc@news.free.fr> <1170879597.935278.240000@m58g2000cwm.googlegroups.com> <45ca4035$0$4321$426a74cc@news.free.fr> Message-ID: <1170885971.374044.181150@v45g2000cwv.googlegroups.com> > And so what ? Once an exception got caught, what are you going to do ? You have absolutely right, that's the reason i rejected this. > You're starting to see the light, my friend !-) > > > Strange world the dynamic one.... > > If that's too dynamic for you, then run for your life Hehe...you know, it is a little bit strange if you are used to Delphi, C# or any other statically-typed language and suddenly you starting programming in a dynamic one, really strange! :) All of the efforts all these years to declare everything correct, to fight with the compiler (and to always have him win...), to ...[put whatever here] and now Python...What can i say!... Thanks for the help! From __peter__ at web.de Thu Feb 15 13:24:44 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 15 Feb 2007 19:24:44 +0100 Subject: TKinter newbie References: Message-ID: Gigs_ wrote: > Hi Im new to gui programming > > from Tkinter import * # get widget classes > from tkMessageBox import askokcancel # get canned std dialog > > class Quitter(Frame): # subclass our GUI > def __init__(self, parent=None): # constructor method > Frame.__init__(self, parent) > self.pack() > widget = Button(self, text='Quit', command=self.quit) > widget.pack(side=LEFT) > def quit(self): > ans = askokcancel('Verify exit', "Really quit?") > if ans: Frame.quit(self) > > class Demo(Frame): > def __init__(self, parent=None): > Frame.__init__(self, parent) > self.pack() > Label(self, text="Basic demos").pack() > for (key, value) in demos.items(): > func = (lambda key=key: self.printit(key)) > Button(self, text=key, command=func).pack(side=TOP, > fill=BOTH) > Quitter(self).pack() # here > def printit(self, name): > print name, 'returns =>', demos[name]() > > > My problem is in class Demo. How is the best way to use class Quitter in > class Demo? > should it be: > Quitter(self).pack() > Quitter(self) > ... You are calling the Quitter's pack() method twice, once in Quitter.__init__() and then again in Demo.__init__(). I would remove the call in Quitter.__init__(). If you do that you can use your Quitter class with other layout managers which require other configuration methods, e. g. Quitter(...).grid(...). Peter From http Fri Feb 2 14:10:04 2007 From: http (Paul Rubin) Date: 02 Feb 2007 11:10:04 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> Message-ID: <7xtzy48jg3.fsf@ruckus.brouhaha.com> "Paul Boddie" writes: > If the hosting provider doesn't want to install MySQLdb then it may > not be a technical issue - perhaps they just can't be bothered to > install it, possibly because there's no demand or benefit to the > bottom line in doing so. Why should the hosting provider need to devote attention to something like that? MySQLdb or something like it should be included with Python, not added separately by the hosting provider. Python is really making more demands on hosting providers than comparable languages do. PHP hosting providers don't have to install a separate PHP to MySQL interface gizmo as far as I know. From rbonvall at alumnos.inf.utfsm.cl Thu Feb 8 12:00:45 2007 From: rbonvall at alumnos.inf.utfsm.cl (Roberto Bonvallet) Date: Thu, 8 Feb 2007 17:00:45 +0000 (UTC) Subject: C parsing fun References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> <1170683733.434435.171350@j27g2000cwj.googlegroups.com> <1170687265.764375.96560@p10g2000cwp.googlegroups.com> Message-ID: K?roly Kiripolszky wrote: > I've found a brute-force solution. In the preprocessing phase I simply > strip out the comments (things inside comments won't appear in the > result) and replace curly brackets with these symbols: #::OPEN::# and > #::CLOSE::#. This fails when the code already has the strings "#::OPEN::#" and "#::CLOSE::" in it. -- Roberto Bonvallet From sjdevnull at yahoo.com Mon Feb 12 14:24:17 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 12 Feb 2007 11:24:17 -0800 Subject: c++ for python programmers In-Reply-To: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <1171308257.175361.86910@a34g2000cwb.googlegroups.com> Thomas Nelson wrote: > I realize I'm approaching this backwards from the direction most > people go, but does anyone know of a good c/c++ introduction for > python programmers? I would stick with C unless you need to edit C++ code. (Calling them C/C++ doesn't make much sense as they're separate languages). The biggest sticking points aren't going to be helped much by a Python background, so I'd just use one of the tutorials recommended over in comp.lang.c (Richard Heathfield had a useful link at one point). From fumanchu at amor.org Sat Feb 10 11:40:58 2007 From: fumanchu at amor.org (fumanchu) Date: 10 Feb 2007 08:40:58 -0800 Subject: Maximum TCP Server Connections In-Reply-To: References: Message-ID: <1171125658.075475.97850@h3g2000cwc.googlegroups.com> On Feb 10, 4:52 am, Steve Holden wrote: > Sorry this question isn't strictly Python-related. Does any one know how > many simultaneous TCP connections it's practical to expect a TCP-based > server application to support (on the OS of your choice)? I'm looking > for the restrictions imposed by the operating environment rather than > the application itself. Data point: When using winsock2, the number of simultaneous TCP connections is limited by the FD_SETSIZE preprocessor constant, which is often 64. It must be set before including winsock2.h. See Google and http:// www.aminus.org/blogs/index.php/fumanchu/2006/12/23/ cherrypy_3_has_fastest_wsgi_server_yet#c38647 Note also that many TCP servers use one thread per child socket, in which case you can hit a memory limit. IIRC, each Python thread on Windows uses a 1 MB stack: http://mail.python.org/pipermail/python- win32/2005-June/003346.html Robert Brewer System Architect Amor Ministries fumanchu at amor.org From steven.bethard at gmail.com Sun Feb 11 01:01:34 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 10 Feb 2007 23:01:34 -0700 Subject: Retry:Question about optparse/OptionParser callback. In-Reply-To: References: Message-ID: Steven W. Orr wrote: > I'm writing a program that needs to process options. Due to the nature > of the program with its large number of commandline options, I would > like to write a callback to be set inside add_option. > > Something like this: > > parser.add_option("-b", action="callback", callback=optionhandlr, dest='b') What do you want your callback to do? Actually, a better question is, what do you want to happen when the user specifies "-b" at the command line? STeVe From beliavsky at aol.com Tue Feb 20 13:46:31 2007 From: beliavsky at aol.com (Beliavsky) Date: 20 Feb 2007 10:46:31 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: Message-ID: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> On Feb 16, 10:17 am, Steven D'Aprano wrote: > On Fri, 16 Feb 2007 09:49:03 -0500, Jean-Paul Calderone wrote: > > On Sat, 17 Feb 2007 01:32:21 +1100, Steven D'Aprano > >> [snip] > > >>I don't think that follows at all. print is only a problem if you expect > >>your code to work under both Python 2.x and 3.x. I wouldn't imagine > >>that many people are going to expect that: I know I don't. > > > I think some people are confused that the language "Python 3.x" has "Python" > > in its name, since there is already a language with "Python" in its name, > > with which it is not compatible. > > There is no language "Python 3" -- yet. We're still all guessing just > how compatible it will be with Python 2. > > To be precise, there is an experimental Python 3, but the specifications > of the language are not fixed yet. > > As for the name... big deal. C and C++ and Objective C are completely > different languages.Fortran 77 and Fortran 90 aren't exactly the same; > nobody expects the same code to run unmodified on Forth 77 and FigForth, > or any of another three dozen varieties of Forth. The attitudes towards backwards compatibility of the Fortran standards committee and the Python BDFL is very different. Fortran 90 was a superset of Fortran 77, so standard-conforming Fortran 77 programs have the same meaning when compiled with an F90 compiler. The committee does not consider changing things like the meaning of 1/2. Even though WRITE provides a superset of the functionality of PRINT, the committee would not dream of breaking so much code by removing PRINT. No feature is deleted without being declared obsolescent in a previous standard, which makes it easier to plan ahead. In practice Fortran 95 compilers accept deleted features, but they are required to a have a switch that identifies non-standard code. I think the C and C++ committees also take backwards compatibility seriously, in part because they know that working programmers will ignore them if they break too much old code. From Eric_Dexter at msn.com Sat Feb 3 01:55:21 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 2 Feb 2007 22:55:21 -0800 Subject: Where Does One Begin? In-Reply-To: References: Message-ID: <1170485721.683685.178470@v33g2000cwv.googlegroups.com> On Feb 2, 4:34 pm, John Nagle wrote: > Mister Newbie wrote: > > I have no programming experience. I want to learn Python so I can make > > simple, 2D games. Where should I start? Can you recommend a good book? > > > Thank you. > > Blender GameKit. > > John Nagle I would mention that blender is a great program but it is complaining about me having version 2.5 of python and not 2.4 or at least it claims I don't have python. pygame is probily a good program to start with as long as you keep in mind that it is possible that up to 50% of the p.c. laptops may not be able to run it. I don't want you to think of me as a complainer just a greedy graphics collector. Python- Allegro this is another intresting one but it requires .net and I haven't broke into it yet and the docs are pretty lite and it isn't ready for into stuff yet. I believe that both tkinter and wxwindows have canvas where you can use dots but that is alot of work for intro to programming type stuff but is more cross pc than pygame is.. From laurent.pointal at limsi.fr Wed Feb 21 04:24:55 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 21 Feb 2007 10:24:55 +0100 Subject: converting u'11\xa022' to '11\xa022' In-Reply-To: References: Message-ID: Gabriel Genellina a ?crit : > En Wed, 21 Feb 2007 00:31:32 -0300, alf escribi?: >> 2-list of supported encodings? > I don't know how to query the list, except by reading the documentation > for the codecs module. >>> from encodings import aliases >>> aliases.aliases {'iso_ir_6': 'ascii', '1140': 'cp1140', 'tis620': 'tis_620', 'iso8859': 'latin_1', 'chinese': 'gb2312', 'mskanji': 'cp932', 's_j is': 'shift_jis', 'iso_celtic': 'iso8859_14', 'ebcdic_cp_wt': 'cp037', 'utf_16_be', 'latin3': 'iso8859_3', 'iso_ir_148': 'iso88 59_9', 'ebcdic_cp_ca': 'cp037', 'tis_620_0': 'tis_620'} >>> enc = aliases.aliases.keys() >>> enc ['iso_ir_6', '1140', 'tis620', 'iso8859', 'chinese', 'mskanji', 's_jis', 'iso_celtic', 'ebcdic_cp_wt', 'csibm863', 'ebcdic_cp_he ', 'csHPRoman8', 'cp936', 'iso_8859_5_1988', 'maccyrillic', 'csibm857', ', 'iso_8859_11_2001', 'latin8', 'greek', '8859', 'big5_hkscs', 'iso_ir_144', 'unicodebigunmarked', 'latin3', 'iso_ir_148', 'ebc dic_cp_ca', 'tis_620_0'] >>> Note: this include some encodings like 'quotedprintable', 'zip', 'zlib'... From vatsal.trivedi107 at gmail.com Sat Feb 17 11:08:35 2007 From: vatsal.trivedi107 at gmail.com (vatsal.trivedi107 at gmail.com) Date: 17 Feb 2007 08:08:35 -0800 Subject: download free computer books enjoy Message-ID: <1171728515.923810.73920@a75g2000cwd.googlegroups.com> Free Computer Education Ebooks,Tutorials and much more.... ASP, Business, C++, Careers, CISCO, e-books, Engineering, English, Filmmaking, Finance, Health, Leadership, Management, Marketing, Mathematics, Mobile, Oracle, Perl , Photography, PHP, Programming, VOIP........and much more visit http://ebooks2download.blogspot.com today From bearophileHUGS at lycos.com Tue Feb 6 16:08:23 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Feb 2007 13:08:23 -0800 Subject: Calling J from Python In-Reply-To: <1170749117.582426.151770@p10g2000cwp.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> Message-ID: <1170796103.766866.18320@a34g2000cwb.googlegroups.com> Gosi: > There are a number of graphics examples, utilities and demos you can > use in J and combine it with Python. Some of those graphic examples are very nice, I have seen a big site filled with complex fractals, chaotic attractors, etc. Python Zen seems somewhat opposed to part of the J spirit, that's why it's not easy to advertise J in this newsgroup. Python is open source, and it values readability, it belives that it's better to write more and be more readable/debuggable, than to be able to express many things with few symbols. APL was an interesting language, powerful too, and J looks more keyboard-friendly and it's probably better for other things too. K seems even less readable than J to me. Probably J has to be compared more to scipy than to Python itself, because they share some purposes, the vector/matrix processing. If you need to do lot of array processing the syntax of scipy (with the help of MatPlotLib too, that's partially copied from MatLab) isn't (may be not) high-level enough, the system isn't able to simplify things by itself, etc. So in that situation a more functional language may be fitter (maybe even F#, but probably there are better languages around for that purpose, some modern ones coming from ML family). Bye, bearophile From vito.detullio at gmail.com Sat Feb 10 09:07:19 2007 From: vito.detullio at gmail.com (ZeD) Date: Sat, 10 Feb 2007 14:07:19 GMT Subject: How to find all the same words in a text? References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> <1171116005.380549.73690@l53g2000cwa.googlegroups.com> Message-ID: Johny wrote: >> >Let suppose I want to find a number 324 in the text >> >> >'45 324 45324' >> >> >there is only one occurrence of 324 word but string.find() finds 2 >> >occurrences ( in 45324 too) >> >> >>> '45 324 45324'.split().count('324') >> 1 >> >>> >> >> ciao > Marco, > Thank you for your help. > It works perfectly but I forgot to say that I also need to find the > possition of each word's occurrence.Is it possible that >>> [i for i, e in enumerate('45 324 45324'.split()) if e=='324'] [1] >>> -- Under construction From sickcodemonkey at gmail.com Mon Feb 26 16:06:25 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Mon, 26 Feb 2007 16:06:25 -0500 Subject: getting info on remote files In-Reply-To: <1172523279.352084.92920@t69g2000cwt.googlegroups.com> References: <1172523279.352084.92920@t69g2000cwt.googlegroups.com> Message-ID: <2adc542f0702261306qde56cf9v1807e3fbae754281@mail.gmail.com> You should use os.popen() instead of os.system. os.popen() will return a file-like object that is connected to the stdout of the system command; you can then use that object's read()/readlines() method(s) to assign that output to a Python variable. http://docs.python.org/lib/module-popen2.html On 26 Feb 2007 12:54:39 -0800, gabriel.altay at gmail.com < gabriel.altay at gmail.com> wrote: > > hello everyone, > > Im trying to write some python code that will return information (file > size, last modified ...) about files on a remote computer that I have > 'no password' ssh access to. Ive been able to write code that logs on > to remote computers and I can issue a command using, > > os.system(ssh blah.blah.blah.org "ls -l myfile") > > but how do I store the information returned by the ls command into a > variable. The primary goal of this is to > 1. check file size on remote computer > 2. scp file to local computer > 3. make sure file size of copy and original are the same > > any suggestions would be appreciated > > thanks > gabe > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbmettler at access.unizh.ch Wed Feb 7 05:34:38 2007 From: mbmettler at access.unizh.ch (=?ISO-8859-15?Q?Ma=EBl_Benjamin_Mettler?=) Date: Wed, 07 Feb 2007 11:34:38 +0100 Subject: Built-in datatypes speed Message-ID: <45C9AB3E.9050106@access.unizh.ch> Hello Python-List I hope somebody can help me with this. I spent some time googling for an answer, but due to the nature of the problem lots of unrelevant stuff shows up. Anyway, I reimplemented parts of TigerSearch ( http://www.ims.uni-stuttgart.de/projekte/TIGER/TIGERSearch/ ) in Python. I am currently writing the paper that goes along with this reimplementation. Part of the paper deals with the differences/similarities in the original Java implementation and my reimplementation. In order to superficially evaluate differences in speed, I used this paper ( http://www.ubka.uni-karlsruhe.de/cgi-bin/psview?document=ira/2000/5&format=1 ) as a reference. Now, this is not about speed differences between Java and Python, mind you, but about the speed built-in datatypes (dictionaries, lists etc.) run at. As far as I understood it from the articles and books I read, any method call from these objects run nearly at C-speed (I use this due to lack of a better term), since these parts are implemented in C. Now the question is: a) Is this true? b) Is there a correct term for C-speed and what is it? I would greatly appreciate an answer to that, since this has some impact on the argumentation in the paper. Thanks, Ma?l PS: For people interested in this reimplementation project: my code will be published here ( http://www.ling.su.se/dali/downloads/treealigner/index.htm ) as soon as it is integrated with the GUI and properly tested. The whole thing is GPLed... From exarkun at divmod.com Mon Feb 5 09:18:45 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 Feb 2007 09:18:45 -0500 Subject: when will python 2.5 take in mainstream? In-Reply-To: Message-ID: <20070205141845.25807.1934323812.divmod.quotient.10788@ohm> On Mon, 05 Feb 2007 10:19:26 +0100, Laurent Pointal wrote: >tleeuwenburg at gmail.com a ?crit : >> When they have to ... >> >> One of the big things about Python is that its penetration slows it >> down. There's more legacy code and interdependant systems around now >> that Python is more successful and more mature. >> >> Here's a thought -- perhaps it would be worth having some good ways to >> interact with Python from Python. Suppose you have some 2.4 code >> someplace, interacting with your mysqldb or whatever, and you don't >> want to rewrite it. So long as you have some kind of object broker, >> you could (plausibly) leave your 2.4 apps running with the old >> interpreter, but wrap them for Python 2.5 and use that in your new >> development. > >KISS please. > Requiring change is simpler than not requiring change? Okay, perhaps you could make a case, but it's far from obvious this is always true. >> Ditto 3.0. >> >> Rather than having to re-write every interacting component, maybe it >> could be straightforward to all Python2.4 from Python2.5 to execute >> particular library calls. I'm not an expert, I don't know how you'd >> build such a system, but I do know that re-writing stuff is a real >> pain. > >Most of Python 2.4 source code is compatible with Python 2.5. Problems >come with native compiled modules, you must have those for you 2.X >Python version - some times just a compilation is enough. Do you have any data to actually back this assertion up? I have plenty of evidence to the contrary. > >For Python 3.0, AFAIK its a big rewrite and developers know that it will >be uncompatible in large parts with existing code. > How does knowing that it will not be compatible have any bearing on the arguments made by the original poster? It doesn't change anything, as far as I can tell. From mizipzor at gmail.com Sun Feb 4 11:36:56 2007 From: mizipzor at gmail.com (Mizipzor) Date: Sun, 4 Feb 2007 17:36:56 +0100 Subject: "Subscribing" to topics? Message-ID: Is there a way to "subscribe" to individual topics? im currently getting bombarded with daily digests and i wish to only receive a mail when there is activity in a topic that interests me. Can this be done? Thanks in advance. From roman.yakovenko at gmail.com Mon Feb 12 13:08:16 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 12 Feb 2007 20:08:16 +0200 Subject: Jython / Java / C / C++ interoperability In-Reply-To: <1171303068.745886.49570@h3g2000cwc.googlegroups.com> References: <1171303068.745886.49570@h3g2000cwc.googlegroups.com> Message-ID: <7465b6170702121008p2fc04256n26774754d4c83955@mail.gmail.com> On 12 Feb 2007 09:57:48 -0800, Charity wrote: > Hi all, > > I have a code base primarily written in Java. I would like to use > Jython to "use" this code base. Everything is wonderful because > Jython calls Java easily. > > However, there may be a time when I would like to call C/C++ from > Jython. I can't do this directly, can I? Would I have to wrap the C/ > C++ in Java to access from Jython? Or call Python which will call the > C/C++? > > What method would be the easiest and most elegant solution for gaining > access to C/C++ functionality from Jython? Please keep in mind that I > have very little Jython experience. > May be you should consider JPype( http://jpype.sourceforge.net/ ) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From deets at nospam.web.de Tue Feb 6 06:49:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 Feb 2007 12:49:51 +0100 Subject: How to prevent from race conditions to share data between many process and thread in python References: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> <52r2njF1of0tpU1@mid.uni-berlin.de> <1170762238.532367.269120@l53g2000cwa.googlegroups.com> Message-ID: <52r8avF1oph0dU1@mid.uni-berlin.de> mars wrote: > On 2?6?, ??6?14?, "Diez B. Roggisch" wrote: >> mars wrote: >> > I use TurboGears to do some web service. TurboGears use cherrypy. When >> > web browser access this site, the cherrypy will call my python >> > program. So my program looks like a lib. When web browser access the >> > site, the http server will fock a process or gerenate a thread. I need >> > share some data or operate some files. How can I prevent from race >> > conditions. Is there any way can I lock this. >> > Thank you in advance! >> >> There are the Lock and RLock objects available in the module threading. >> >> Diez > > Can this also lock mutil-process? No. Diez From steve at holdenweb.com Tue Feb 13 03:24:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Feb 2007 08:24:18 +0000 Subject: pygame and python 2.5 In-Reply-To: <1171213686.383076.280390@j27g2000cwj.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> <1171213686.383076.280390@j27g2000cwj.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Feb 11, 4:24 am, Steve Holden wrote: >> mensana... at aol.com wrote: >>> On Feb 11, 1:35?am, Steve Holden wrote: [...] > >>> By the way, on the sci.math newsgroup I promote >>> Python every chance I get. One fellow thanked me >>> profusely for recommending Python & GMPY and asked >>> for some help with a program he was having problems >>> with. We worked it out fine but his problem made me >>> suspect there may be more bugs in GMPY. What's my >>> motivation for tracking them down? >> The satisfaction of a job well done? What's my motivation for acting as >> a director of the Python Software Foundation when I get accusations of >> irresponsibility? > > I apologize. But I hope you see how this appears from > the outside, that the PSF doesn't give a rat's ass about > Windows users with AOL addresses. Sure, that's wrong, > but calling people who bring up these points whiny leeches > doesn't do anything to dispell that notion. > The AOL address is nothing to do with it. Accusations of whiny leeching tend to be made at people whose attitudes aren't constructive and who express their complaints in ways that seem to imply an expectation of some kind of right to dictate to open source developers. >> Anyway, thanks for taking the time to help maintain gmpy. > > Thanks, I try to help as much as I can. I'm a little > sensitive about gmpy because without it, I would have > to abandon Python and I don't want to abandon Python. > >> This thread is starting to make me think that there's a case to be made >> for somehow providing supported build facilities for third-party >> extension modules. > > And the untouchables would greatly appreciate it. > We're all Python users. There are no untouchables. But in the open source world you tend to have to take ownership of the problems that are important to you. Since you say you couldn't get the attention of gmpy's developers you might need to think about trying to join the team ... >> This wouldn't be a simple project, but since there's a Windows buildbot >> for Python there's no reason why the same couldn't be done for >> extensions. I'll raise this with the PSF and see what the response is: >> then your carping will at least have had some positive effect ;-) >> >> Stick with it, and let's try to make things better. > > Ok. > On a point of information, as it happens there's a Board meeting today and I have tabled the topic for discussion. Unfortunately I can't guarantee to attend the meeting (I am moving from the UK to the USA this week) but I will try to do so, and will attempt to report back to c.l.py within a week. regards Steve PS: Couldn't send this yesterday, or attend the meeting, because BT Internet termined my DSL service early, mau God rot their profits and drive them into bankruptcy. I'll report back once I found out how the discussions went. -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From S.Mientki-nospam at mailbox.kun.nl Sun Feb 11 07:35:13 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 11 Feb 2007 13:35:13 +0100 Subject: favourite editor In-Reply-To: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> Message-ID: <51ed8$45cf0d6e$d443bb3a$7257@news.speedlinq.nl> azrael wrote: > Since i'm new on this forum, and first time meeting a python comunity, > i wanted to ask you for your python editors. > > Im looking for some good python editor, with integrated run function, > without having to set it up manualy like komodo. > I found the pyscripter, and it has all i need, but it's unsatble. > bloated. No it is very stable, but some programs should be started differently, read the manual ! it crashes when i close an yplication window run by python > from pyscripter. please. tell me a good one with buil in run (<-very > important) and nice gui. if possible to suport projects, code > highlighting, code completition, class browser, python comand line > (>>>), traceback. You could try SPE, but that's really unstable, and no help manual to read ;-) and for the rest the answer must certainly be in the still running thread "Best Free and Open Source Python IDE" cheers, Stef Mientki From me at mylife.com Tue Feb 27 17:08:28 2007 From: me at mylife.com (Jason B) Date: Tue, 27 Feb 2007 22:08:28 GMT Subject: Pixel Array => Bitmap File References: Message-ID: My mistake, I see the section now about "Writing Your Own File Decoder..." Thanks again for your help! - J "Jason B" wrote in message news:mV1Fh.2439$M65.1505 at newssvr21.news.prodigy.net... > Thanks, Roel... > > The Image.frombuffer() method looks promising, but the "mode" parameter > seems a bit too limited for my needs. I must be able to specify not only > the order of the bits (RGB in any order) but also whether the format is > 565, 555, etc. > > Maybe I need to work outside the bounds of PIL? > > - J > From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 05:35:11 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 16 Feb 2007 21:35:11 +1100 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: On Thu, 15 Feb 2007 19:04:34 -0600, Edward K Ream wrote: >> Isn't the very concept of major releases (1.x, 2.x, 3.x) that they *can* >> be not backwards-compatible with previous releases? > > Not at all. Backwards compatibility means that one can still run old code > provided the code eschews new features. Python releases have generally > been backwards compatible with previous releases, with a few minor > exceptions. That's fine, but Python 3 has been explicitly stated to be where Python will have backwards _in_compatible changes made. That's not to say that all Python 2.x programs will break under Python 3, but some surely will. > For example, my app runs fine on Python 2.2.2 through Python > 2.5, and little work was required to make this happen. In fact, my app > should run find on Python 3.x, but that's because it doesn't use print :-) It's too early to say for sure what will run under Python 3, because it hasn't been decided fully yet, but it is quite probable that it will still compile and/or run and possibly even do what you intended. > In other words, the consequence of pep 3105 will be that *nobody* who wants > their app to be portable will be able to use print until *everybody* has > converted to Python 3.x. I doubt that is what Guido had in mind, but I may > be mistaken :-) I'm pretty sure you're mistaken. Python 3 will be the release that breaks code. Hopefully very little, but there almost certainly will be some. -- Steven. From liuwensui at gmail.com Wed Feb 14 18:20:07 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Wed, 14 Feb 2007 18:20:07 -0500 Subject: anyway to create a table-like object? Message-ID: <1115a2b00702141520o624e2046xfadefef77cc4ed1@mail.gmail.com> Dear all, is there a way to create a 2-dimension-table-like object such that I can reference a whole column directly using something like : mytable.column1 ? by the way, can python be used for database programming to pull large volume data (hundred M or even several Gs) out of large database and do data manipulation and reporting ? if yes, how is the speed and efficiency ? thanks. wensui From sjmachin at lexicon.net Mon Feb 12 08:16:52 2007 From: sjmachin at lexicon.net (John Machin) Date: 12 Feb 2007 05:16:52 -0800 Subject: Formatting milliseconds to certain String In-Reply-To: References: Message-ID: <1171286212.248432.73240@a34g2000cwb.googlegroups.com> On Feb 12, 11:32 pm, Deniz Dogan wrote: > Hello. > I need help with a small problem I'm having. > > I want to make a function which takes an integer representing some time > in milliseconds and returns the same time but formatted as > "hours:minutes:seconds,milliseconds" with leading zeros whenever possible. > > E.g. I input 185804 to the function and it returns 00:03:05,804. | >>> def fmt_millis(millis): | ... """millis is an integer number of milliseconds. | ... Return str hh:mm:ss,ttt | ... """ | ... seconds, millis = divmod(millis, 1000) | ... minutes, seconds = divmod(seconds, 60) | ... hours, minutes = divmod(minutes, 60) | ... return "%02d:%02d:%02d,%03d" % (hours, minutes, seconds, millis) | ... | >>> fmt_millis(0) | '00:00:00,000' | >>> fmt_millis(1) | '00:00:00,001' | >>> fmt_millis(12345678) | '03:25:45,678' | >>> fmt_millis(45678) | '00:00:45,678' | >>> fmt_millis(1230000) | '00:20:30,000' | >>> fmt_millis(3600000) | '01:00:00,000' | >>> fmt_millis(3600000*24) | '24:00:00,000' | >>> fmt_millis(3600000*2400) | '2400:00:00,000' | >>> From tinaweb at bestemselv.com Fri Feb 9 01:01:57 2007 From: tinaweb at bestemselv.com (Tina I) Date: Fri, 09 Feb 2007 07:01:57 +0100 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com><1170731096.976076.173270@h3g2000cwc.googlegroups.com><1170749117.582426.151770@p10g2000cwp.googlegroups.com><1170796103.766866.18320@a34g2000cwb.googlegroups.com><1170861935.779969.52980@v33g2000cwv.googlegroups.com><1170874782.600836.210670@a34g2000cwb.googlegroups.com> <2ZKdnYNMboxxS1fYRVnzvA@telenor.com> Message-ID: <69qdnVgvRJjIk1HYRVnzvA@telenor.com> Hendrik van Rooyen wrote: > > I am under the impression that Loki had a daughter called Hel ... > > - Hendrik > Yes. And Hel was the queen of the underworld which was also called 'Hel' (Which of course is 'hell', in modern Norwegian : "helvete") From bbbart at inGen.be Mon Feb 5 06:11:48 2007 From: bbbart at inGen.be (Bart Van Loon) Date: Mon, 5 Feb 2007 16:11:48 +0500 Subject: in place-ness of list.append References: Message-ID: It was Mon, 5 Feb 2007 05:01:28 -0600, when skip at pobox.com wrote: > > Bart> #-------------------------------------------------- > Bart> def addnumber(alist, num): > Bart> """ work around the inplace-ness of .append """ > Bart> mylist = alist[:] > Bart> mylist.append(num) > Bart> return mylist > Bart> #-------------------------------------------------- > > Bart> and I am wondering if this is good practice or not. > > Bart> any advice on this matter? > > Such an operation will be O(N**2), why is that? > and thus expensive if performed frequently on lists of moderate > length. I've never been tempted to do this. Can you say a little > about why you'd want to do this? Knowing that, perhaps someone here > can point you in a more Pythonic direction. I am building a binary tree where each node is a list. the two children are the parent list + 1 and the parent list + 2. I am using it recursively as such: #----------------------------------------------------------- def makescoretree(scorelist): """ generates the Tree of possible scores """ if waves(scorelist) >= MAXWAVES: return [] return Scoretree(scorelist, makescoretree(addnumber(scorelist, 1)), makescoretree(addnumber(scorelist, 6))) #----------------------------------------------------------- but now I found out that I can do this easily like #----------------------------------------------------------- def makescoretree(scorelist): """ generates the Tree of possible scores """ if waves(scorelist) >= MAXWAVES: return [] return Scoretree(scorelist, makescoretree(scorelist + [1]), makescoretree(scorelist + [6])) #----------------------------------------------------------- -- regards, BBBart "Who can fathom the feminine mind?" -Calvin "I like `em anyway" -Hobbes From sjdevnull at yahoo.com Wed Feb 28 17:09:09 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 28 Feb 2007 14:09:09 -0800 Subject: Python Source Code Beautifier In-Reply-To: <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> References: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> Message-ID: <1172700549.583792.41660@s48g2000cws.googlegroups.com> On Feb 28, 11:24 am, Alan Franzoni wrote: > Il 27 Feb 2007 16:14:20 -0800, sjdevn... at yahoo.com ha scritto: > > > > > Those mean different things: > > >>>> a=[1] > >>>> b=a > >>>> a += [2] > >>>> a > > [1, 2] > >>>> b > > [1, 2] > >>>> a=[1] > >>>> b=a > >>>> a = a + [2] > >>>> a > > [1, 2] > >>>> b > > [1] > > This is a really nasty one! I just answered to Tim above here, and then I > saw your example... I had never realized that kind of list behaviour. > That's probably because i never use + and += on lists (i prefer the more > explicit append() or extend() and i do copy list explictly when I want to) > , BTW I think this behaviour is tricky! Seems obvious and desirable to me. Bare "=" is the way you assign a name to an object; saying "NAME =" will rebind the name, breaking the connection between a and b. Without it, they continue to refer to the same object; extending the list (via += or .extend) mutates the object, but doesn't change which objects a and b are referencing. It would be very counterintuitive to me if "=" didn't change the name's binding, or if other operators did. From http Wed Feb 14 03:07:18 2007 From: http (Paul Rubin) Date: 14 Feb 2007 00:07:18 -0800 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171431443.737052.183960@j27g2000cwj.googlegroups.com> <1171435541.291367.299290@j27g2000cwj.googlegroups.com> <1171437351.206085.236450@q2g2000cwa.googlegroups.com> Message-ID: <7x4ppptb61.fsf@ruckus.brouhaha.com> "John Machin" writes: > What does "pwn" mean? http://en.wikipedia.org/wiki/Pwn From tokauf at web.de Sat Feb 24 06:56:01 2007 From: tokauf at web.de (TK) Date: Sat, 24 Feb 2007 12:56:01 +0100 Subject: Newbie question: Install Tkinter with Python2.5 In-Reply-To: <1172180806.514444.155690@l53g2000cwa.googlegroups.com> References: <45de03c6$0$8891$9b622d9e@news.freenet.de> <1172180806.514444.155690@l53g2000cwa.googlegroups.com> Message-ID: <45e027f4$0$4355$9b622d9e@news.freenet.de> Hi, > I see that Tcl/Tk detection has been moved in the Python source > distribution (since the "good old days" when I last had to deal with > this kind of thing) from the configure machinery to the setup.py > program. However, a few things worth checking include (1) whether you > not only have the Tcl/Tk libraries but also the Tcl/Tk headers/ > includes and (2) whether they're installed in standard places or > somewhere else. > > Look for things like libtcl8.4.so, libtk8.4.so as well as tcl.h and > tk.h. If appropriate, check your distribution's packages and make sure > you have the developer packages (eg. tcl8.4-dev, tk8.4-dev) installed. It's not so simple ... . Thanx fpor help. o-o Thomas From deets at nospam.web.de Mon Feb 5 09:59:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Feb 2007 15:59:12 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> Message-ID: <52ov20F1of7ecU1@mid.uni-berlin.de> Gosi wrote: > It is quite easy to call J from Python > > http://groups.google.com/group/J-Programming/browse_thread/thread/5e84b75667f5f64e What is J, and why should we care? Diez From lincolnr at oar.net Tue Feb 27 14:55:24 2007 From: lincolnr at oar.net (lincoln rutledge) Date: Tue, 27 Feb 2007 14:55:24 -0500 Subject: difference between string and list Message-ID: <45E4465D020000C50000701E@gw.osc.edu> I'm having trouble figuring out the difference between a string and a list. I know that: string = "foo bar" is a list of characters, "foo bar", and string[0] is "f". while: list = ["foo", "bar"] and list[0] is "foo". strings have methods like string.count("f") returns 1. What methods do lists have? Is it a similar class to string? thanks, Lincoln From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 28 06:15:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 28 Feb 2007 12:15:13 +0100 Subject: using telnetlib References: <1172654582.919944.13530@k78g2000cwa.googlegroups.com> Message-ID: <54l6hpF21daqnU1@mid.individual.net> Phoe6 wrote: >>>> import telnetlib >>>> tn = telnetlib.Telnet("172.31.128.244") >>>> tn.read_until("Login: ") > '\r\nLogin: ' >>>> tn.write("root\n:") ^^^ With telnet, use "\r\n" for line breaks at *all* times to be on the safe side. Also, what's the ":" at the end for? Regards, Bj?rn -- BOFH excuse #88: Boss' kid fucked up the machine From duncan.booth at invalid.invalid Tue Feb 27 05:06:29 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Feb 2007 10:06:29 GMT Subject: Lists: Converting Double to Single References: <%6QEh.6362$_73.1862@newsread2.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber wrote: > Something like (pseudo-code): > > > cnt = 0 > for rw in cursor(): > if cnt: > for i,v in enumerate(rw): > sum[i] += v #accumulate next row > else: > sum = rw #initialize to first row > cnt += 1 > avg = [ float(v) / cnt for v in sum] > > Don't know if this is faster than numpy operations, but it > definitely reduces the amount of memory consumed by that list of > lists... A lot of course depends on the input data, and the example given wasn't even syntactically valid so I can't tell if he started with integers or floats, but if the lists are long and the OP is at all worried about accuracy, this code may be a bad idea. Adding up a long list of values and then dividing by the number of values is the classic computer science example of how to get an inaccurate answer from a floating point calculation. I wouldn't have mentioned it, but since the OP said numpy it might just be that he cares about the result. What I really don't understand though is why, if he wants the final result in NumPy, he doesn't just use it for the calculation? >>> from numpy import array >>> lst = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] >>> array(lst).mean(axis=0) array([ 3.5, 4.5, 5.5, 6.5, 7.5]) What I haven't tried to figure out is whether, having said all that, NumPy's mean is any more accurate than the naive sum and divide calculation? So far as I can tell, it isn't any more accurate although it does give different results. From http Tue Feb 6 13:42:53 2007 From: http (Paul Rubin) Date: 06 Feb 2007 10:42:53 -0800 Subject: Help with multiple key sort References: <1170786670.535839.118650@s48g2000cws.googlegroups.com> Message-ID: <7x3b5j86vm.fsf@ruckus.brouhaha.com> ian.brady1 at gmail.com writes: > It moves right while keeping sorted order to the left. This is the > new stable sort in 2.5. >>> b ['1 one 2', '1 one 1', '1 two 1', '1 one 0', '1 xx 0'] >>> sorted(b,key=lambda x: x.split()) ['1 one 0', '1 one 1', '1 one 2', '1 two 1', '1 xx 0'] From kirk at nospam.jobsluder.net Sat Feb 3 23:10:30 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Sat, 03 Feb 2007 23:10:30 -0500 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <1170546032.316062.133050@m58g2000cwm.googlegroups.com> Message-ID: In article <1170546032.316062.133050 at m58g2000cwm.googlegroups.com>, "Paul Boddie" wrote: > Quite. I imagine that most GNU/Linux distributions (and various BSDs) > provide at least some version of MySQLdb as a package. Bingo, I've rarely installed python from python.org, or other libraries from sourceforge, etc., etc.. Usually I've installed BSD-style ports, debian-style packages, or RedHat-style RPMs. > > Paul From steve at REMOVEME.cybersource.com.au Sun Feb 25 20:05:52 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 26 Feb 2007 12:05:52 +1100 Subject: newbie question References: <1172451445.535936.173510@k78g2000cwa.googlegroups.com> Message-ID: On Sun, 25 Feb 2007 16:57:25 -0800, jeff wrote: >>>> print {}.update.__doc__ That's a long way to spell "help({}.update)" :-) -- Steven D'Aprano From uval at rz.uni-karlsruhe.de Thu Feb 15 23:18:40 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Fri, 16 Feb 2007 05:18:40 +0100 Subject: builtin set literal In-Reply-To: <1171612923.145381.220960@p10g2000cwp.googlegroups.com> References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> Message-ID: > {:} for empty dict and {} for empty set don't look too much atrocious > to me. this looks consistent to me From bborcic at gmail.com Fri Feb 2 10:09:23 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 02 Feb 2007 16:09:23 +0100 Subject: Germany issues warrants for 13 American CIA agents In-Reply-To: References: <1170286881.262636.315770@a75g2000cwd.googlegroups.com> Message-ID: Vance P. Frickey wrote: > I understand that Mengele's old boss is still alive and well > in Deutschland What else do you understand ? From emami at knmi.nl Fri Feb 23 09:24:01 2007 From: emami at knmi.nl (Nader Emami) Date: Fri, 23 Feb 2007 15:24:01 +0100 Subject: compile python with sqlite3 Message-ID: L.S., I have to compile (install) locally Python 2.5, because I don't have 'root' permission. Besides I would use 'sqlite3' as a database for TurboGears/Django. I have installed 'sqlite3' somewhere on my Linux (/path/to/sqlite'). What do I have to do if I want to compile 'Python' with 'sqlite3'? I would appreciate if somebody tells me to solve this problem. With regards, Nader From nospam at riddergarn.dk Tue Feb 13 08:09:18 2007 From: nospam at riddergarn.dk (NOSPAM plz) Date: Tue, 13 Feb 2007 14:09:18 +0100 Subject: Download parts not whole file in ones Message-ID: <45D1B87E.5010205@riddergarn.dk> Hey, My problem is, is it possible to download parts of a file while. i think is it is called threading My code thats download the whole webpage, and stunds the app while is is downloading: -----------CODE----------- import urllib # the heavy file to download f = urllib.urlopen("http://da.wikipedia.org/wiki/Wiki") # This was supposed to print the file while it downloads while 1: print f.read(100) -----------/CODE----------- In my example it just download the whole file, and then print it. Any suggestions? Regards Andreas From gagsl-py at yahoo.com.ar Thu Feb 8 01:53:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Feb 2007 03:53:00 -0300 Subject: 'IF' Syntax For Alternative Conditions References: Message-ID: En Thu, 08 Feb 2007 01:01:38 -0300, escribi?: > However, I cannot find, nor create by trial-and-error, the syntax for > alternative conditions that are ORed; e.g., > > if cond1 OR if cond2: > do_something. > > Please pass me a pointer so I can learn how to correctly write this. See the Python tutorial: http://docs.python.org/tut/node7.html#SECTION007700000000000000000 Note that most (if not all) Python keywords are lowercase. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun Feb 25 04:32:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 06:32:50 -0300 Subject: select which lib for iNet? References: <5c62a320702250112u4c4fb047u50144a4124e1d620@mail.gmail.com> Message-ID: En Sun, 25 Feb 2007 06:12:32 -0300, Marco escribi?: > I wanta know why (Py)Qt has its own lib on socket/ sql/ openGL,etc ? > Is the lib better than standard lib? See http://www.commandprompt.com/community/pyqt/x3738 In short, because Qt already had them, and some callbacks or function calls may need to use them instead of the native Python classes. -- Gabriel Genellina From nszabolcs at gmail.com Thu Feb 22 08:07:52 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 22 Feb 2007 05:07:52 -0800 Subject: Regex Speed In-Reply-To: References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172049029.217002.55560@v33g2000cwv.googlegroups.com> Message-ID: <1172149672.365758.256300@l53g2000cwa.googlegroups.com> > Well, just as an idea, there is a portable C library for this at > http://laurikari.net/tre/ released under LGPL. If one is willing to > give up PCRE extensions for speed, it might be worth the work to > wrap this library using SWIG. actually there is a python binding in the tre source with an example python script so it is already done. From aleaxit at gmail.com Mon Feb 26 19:33:17 2007 From: aleaxit at gmail.com (Alex Martelli) Date: Mon, 26 Feb 2007 16:33:17 -0800 Subject: gmpy moving to code.google.com In-Reply-To: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> Message-ID: On 2/26/07, Daniel Nogradi wrote: ... > Svn checkout, compilation and installation went okay but some tests > failed, this is the output of 'python test_gmpy.py': Thanks for the report! That test is trying to check that a previously existing memory leak went away, and unfortunately this requires measuring the memory used by the process which is kind of flaky... in particular: > Failed example: > _memsize()-_siz > Expected: > 0 > Got: > -4 ...this means that (after a loop of the operation that used to leak) your process is consuming 4KB _less_ than it was before the loop (?!). Guess I'll have to make that test more "tolerant" of such small flakiness... [done -- it's now in revision 10 of the SVN repository]. > 1 items had failures: > 2 of 132 in gmpy_test_mpz.__test__.number > ***Test Failed*** 2 failures. That's actually just the one failure (all tests are repeated with and without caching enabled). Thanks again for your report! Alex From B.Ogryczak at gmail.com Wed Feb 28 12:48:59 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 28 Feb 2007 09:48:59 -0800 Subject: finding out the precision of floats In-Reply-To: <1172684085.170332.323490@z35g2000cwz.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172684085.170332.323490@z35g2000cwz.googlegroups.com> Message-ID: <1172684939.736516.83800@v33g2000cwv.googlegroups.com> On Feb 28, 6:34 pm, "Arnaud Delobelle" wrote: > > So as long as you're dealing with something like > > invoices, Decimal does just fine. When you start real calculations, > > not only scientific, but even financial ones[1], it doesn't do any > > better then binary float, and it's bloody slow. > > I'm not doing 'real world' calcultations, I'm making an app to help > teach children maths. Without divisions? > I need numerical values that behave well as > decimals. I also need them to have an arbitrary number of significant > figures. Floats are great but they won't help me with either. Amongst > other things, I need 3.0*0.1==0.3 to be True. How about (1.0/3.0)*3.0 == 1.0? That doesn't need to be True? > Please do not make the assumption that I have chosen to use a decimal > type without some careful consideration. Well, you didn't indicate this before. Anyway, in that case efficiency has no impact at all, so you might as well use Decimal. From peterbe at gmail.com Fri Feb 23 10:09:07 2007 From: peterbe at gmail.com (Peter Bengtsson) Date: 23 Feb 2007 07:09:07 -0800 Subject: With PIL... paste image on top of other with dropshadow Message-ID: <1172243347.246211.317600@8g2000cwh.googlegroups.com> I love the dropshadow effect I managed to make with this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474116 Here's what it can look like: http://www.peterbe.com/test/188-tequilacat.2.jpg It takes a background as a parameter but it's just a colour. What I want is to put the image on top of another but doing so with a dropshadow. I guess the solution would be something like putting the dropshadow on the first image without a background colour but instead a transparant background and then paste this onto another image. I just have no idea to do that? The final result I want is something like programmtically fake that a picture (the foreground) is hanging on a wall (the background) with a dropshadow so that it looks like it's hanging in a inch-deep frame. From lbates at websafe.com Thu Feb 22 09:45:45 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 22 Feb 2007 08:45:45 -0600 Subject: Reading mails from Outlook In-Reply-To: <1172152420.295840.133600@t69g2000cwt.googlegroups.com> References: <1172152420.295840.133600@t69g2000cwt.googlegroups.com> Message-ID: <45DDAC99.7040009@websafe.com> beeswax wrote: > Hi, > > Does anyone knows how to read e-mails from a specific folders in > outlook? > I only found out how to read the mails from the inbox folder and how > to list all available folder. > I just don't found a way to access my mails from the other folders. > > Can anyone help me? > > Regards, > > Sam > I'll bet that some of the best information you can get about interacting with Outlook is going to be by looking at the sourcecode to SpamBayes plug-in. You can get it from here: https://sourceforge.net/project/showfiles.php?group_id=61702&package_id=58141 -Larry From rawehage at insightbb.com Mon Feb 12 18:07:09 2007 From: rawehage at insightbb.com (Roger A. Wehage) Date: Mon, 12 Feb 2007 17:07:09 -0600 Subject: 'File name' is not recognized as an internal or external command, operable program Message-ID: <054e01c74efa$85fdecf0$6601a8c0@roger47220a73e> Here it is-nearly four and a half years since Mike Henley posted 'File name' is not recognized as an internal or external command, operable program-and the problem still persists. Some weeks ago I installed ActiveState 8.3.5.0 on Windows XP and many things stopped working. Like Mike, I struggled to find the cause until I ran across his post: http://mail.python.org/pipermail/python-list/2002-September/165998.html And, as Mike suggested, I moved the ".tcl" extension from User variables to System variables, and everyone seems to be happy. :o) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 19 05:04:19 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 11:04:19 +0100 Subject: (beginners question) howto set self.field4.subfield8='asdf'? References: <1171877794.747825.294890@t69g2000cwt.googlegroups.com> Message-ID: openopt at ukr.net wrote: > I have > class A: > def __init__(self, objFun, x0): > #(I want to have self.primal.f = objFun) > #both > self.primal.f = objFun > #and > self.primal = None > self.primal.f = objFun None is a singleton, so if Python were to allow the above f would always be the objFun of the last created A instance. > yields error > what should I do? Make a dedicated Primal class: >>> class Primal: ... pass ... >>> class A: ... def __init__(self, fun, x0): ... self.primal = Primal() ... self.primal.f = fun ... >>> def square(x): return x*x ... >>> a = A(square, 42) >>> a.primal.f Even better, because it makes no assumptions about the internal layout of Primal: class Primal: def __init__(self, f): self.f = f ... self.primal = Primal(fun) ... Peter From wdraxinger at darkstargames.de Tue Feb 20 14:14:37 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Tue, 20 Feb 2007 20:14:37 +0100 Subject: Sorting directory contents References: <45DB0D28.6060608@websafe.com> Message-ID: Larry Bates wrote: > 3) You didn't handle the possibility that there is s > subdirectory > in the current directory. You need to check to make sure it > is a file you are processing as os.listdir() returns files > AND directories. Well, the directory the files are in is not supposed to have any subdirectories. > 4) If you just put a tuple containing (mtime, filename) in a > list > each time through the loop you can just sort that list at > the end it will be sorted by mtime and then alphabetically. Ah, of course. Hmm, seems I was short of caffeine when I hacked my code :-P > def listdir_chrono(dirpath): > import os > # > # Get a list of full pathnames for all the files in dirpath > # and exclude all the subdirectories. Note: This might be > # able to be replaced by glob.glob() to simplify. I would > # then add a second optional parameter: mask="" that would > # allow me to pass in a mask. > # > # List comprehensions are our friend when we are processing > # lists of things. > # > files=[os.path.join(dirpath, x) for x in > os.listdir(dirpath) > if not os.path.isdir(os.path.join(dirpath, x)] > > # > # Get a list of tuples that contain (mtime, filename) that > # I can sort. > # > flist=[(os.stat(x).st_mtime, x) for x in files] > > # > # Sort them. Sort will sort on mtime, then on filename > # > flist.sort() > # > # Extract a list of the filenames only and return it > # > return [x[1] for x in flist] > # > # or if you only want the basenames of the files > # > #return [os.path.basename(x[1]) for x in flist] Now, THAT is elegant. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From gert.cuykens at gmail.com Thu Feb 8 18:48:32 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Fri, 9 Feb 2007 00:48:32 +0100 Subject: def obj() In-Reply-To: References: <45cb9d24$0$6842$4d3efbfe@news.sover.net> Message-ID: #include function hello(){ struct obj = { char *data = 'hello'} obj.add = obj_add(obj); return obj; } function obj_add(obj){ function add(value){ obj.data += value; return obj; } } main(){ test = hello(); test.add('world'); printf(test.data); } I was thinking something like this maybe ? From sjmachin at lexicon.net Wed Feb 14 00:37:23 2007 From: sjmachin at lexicon.net (John Machin) Date: 13 Feb 2007 21:37:23 -0800 Subject: python not returning true In-Reply-To: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> Message-ID: <1171431443.737052.183960@j27g2000cwj.googlegroups.com> On Feb 14, 4:15 pm, "agent-s" wrote: > I have a function, generally described as so: > > def function(args): > if condition: > if condition2: > function(args+1) return None > elif condition3: > print "text" > return True > else: > return False else: return None There are two cases, indicated above, where you don't explicitly do a "return", so you fall off the end of the function, and Python returns None. Then when the function's caller tests the returned value, None is treated as logically false. > which is used in: > > if function(args): > print "ok" > > so here basically "text" will print out when condition3 is true but it > will not print out "ok" when condition3 is true. When it's true it > should print out borth "text" and "ok" In the second last sentence, it is difficult to determine what you think is expected behaviour and what you say is the actual behaviour. In the last sentence, what does the first "it" refer to? If the knowledge about returning None doesn't help you, try some standard(??) techniques like inserting print statements or debugger break-points. HTH, John From johnjsal at NOSPAMgmail.com Thu Feb 1 16:41:02 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Feb 2007 16:41:02 -0500 Subject: Sorting a list In-Reply-To: <45c254a2$0$674$426a34cc@news.free.fr> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> <45c254a2$0$674$426a34cc@news.free.fr> Message-ID: <45c25d9a$0$27590$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: >> One more thing. What if I want them in reverse chronological order? I >> tried reverse() but that seemed to put them in reverse alphabetical >> order based on the second element of the tuple (not the year). > > Really ? > > >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), > ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')] > >>> lines.sort() > >>> lines > [('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc'), ('1996', 'aaa'), > ('1996', 'ccc'), ('1997', 'aaa'), ('1997', 'bbb')] > >>> lines.reverse() > >>> lines > [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), > ('1995', 'ccc'), ('1995', 'bbb'), ('1995', 'aaa')] > >>> Oh I didn't sort then reverse, I just replaced sort with reverse. Maybe that's why! From lance at augustmail.com Thu Feb 15 12:05:35 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Thu, 15 Feb 2007 17:05:35 GMT Subject: re.search making no match == 0 Message-ID: Hey all, I have a search: VAR = re.search("PROVEN.*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" , pcpT9, re.S ).group(1) #.split()[1] that does not match (sometimes it will and sometimes it will not match) Traceback (most recent call last): File "P:\Burke\TRACKERS\Ortho-McNeil\Automation\Wave3\test.py", line 53, in ? VAR = re.search("PROVEN.*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" , pcpT9, re.S ).group(1) #.split()[1] AttributeError: 'NoneType' object has no attribute 'group' Is there a way in python to make this "non" match equal a value (say, "0")? This one line is actually a series of searches Reasons = ["EFFICACY","EFFECTIVE","WORKS QUICKLY","PROVEN","SAFETY","LITTLE","WELL"," BETTER","SAMPLES"] # Reasons(29) VAR = [re.search(r"%s.*?\n[\sA-Za-z\(\)\/\-]+\d(.*?)\n.*?" % i, pcpT9, re.S ).group(1) for i in Reasons ] #.split()[1] and one of the items in the array may or may not be present. Lance From aleaxit at gmail.com Fri Feb 23 19:24:44 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 23 Feb 2007 16:24:44 -0800 Subject: Rational numbers In-Reply-To: <1172274278.169015.79910@z35g2000cwz.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> <1172274278.169015.79910@z35g2000cwz.googlegroups.com> Message-ID: <1172276684.884139.48630@q2g2000cwa.googlegroups.com> On Feb 23, 3:44 pm, cas... at comcast.net wrote: ... > I can keep building gmpy for Windows. I actually use MINGW since > getting GMP compiled under MSVC is "challanging". I should be able to > build new binaries for Windows this weekend. And I would be happy to > point everyone to a real release. Great! May I add you as a Member to the Google Code gmpy project? After which, you should be able to use svn to get the latest sources, make fixes, etc, etc -- including (if I understand the Google Code mechanics correctly) simply uploading the Windows installer or whatever, if it passes all tests (formal and informal) satisfactorily. Please don't use the "1.02 prerelease" sources zip -- the SVN trunk is more updated, I'll make a "1.02 definitive" sources zip once we have gmpy built and working correctly on all variants of Windows and Mac that we're going to support (I suggest that the binaries be made for Python 2.3, 2.4 and 2.5, for Windows, Mac intel and Mac PPC -- unless we can make Mac Universal work, but I'm finding that quite problematic... a PPC Mac somewhere I shd be able to find:-). Thanks, Alex From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 16:56:24 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 22:56:24 +0100 Subject: Calling J from Python In-Reply-To: <45c791f1$0$5076$ba4acef3@news.orange.fr> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <45c78a46$0$29725$426a74cc@news.free.fr> <45c791f1$0$5076$ba4acef3@news.orange.fr> Message-ID: <45c7a0f1$0$1029$426a34cc@news.free.fr> Laurent Pointal a ?crit : > Bruno Desthuilliers wrote: > > >>Gosi a ?crit : >> >>>On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: >>>J has very many advanced operations. >> >>what's an "advanced operation" ? > > > An operation which dont stay in place. > You meant something like a good camembert ?-) From grante at visi.com Tue Feb 6 17:23:21 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 06 Feb 2007 22:23:21 -0000 Subject: Help reading binary data from files References: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> Message-ID: <12shvup889qu9a3@corp.supernews.com> On 2007-02-06, jeff wrote: > I am stumped trying to read binary data from simple files. Here is a > code snippet, where I am trying to simply print little-endian encoded > data from files in a directory. > > for name in os.listdir(DOWNLOAD_DIR): > filename = s.path.join(DOWNLOAD_DIR, name) > if os.path.isfile(filename): > f = open(filename, 'rb') > while True: > ele = unpack(' print ele > > > When the code runs, 0 is always the data printed, but the data files > are not all zero. > > Any quick tips? What are the f.read(2) calls returning? -- Grant Edwards grante Yow! Hello, GORRY-O!! I'm at a GENIUS from HARVARD!! visi.com From etatoby at gmail.com Sat Feb 24 13:20:22 2007 From: etatoby at gmail.com (Toby) Date: 24 Feb 2007 18:20:22 GMT Subject: Endianness conversion References: <45e05c49$0$20809$5fc30a8@news.tiscali.it> <1172338039.789502.26470@h3g2000cwc.googlegroups.com> Message-ID: <45e081e6$0$20809$5fc30a8@news.tiscali.it> Daniel Harding wrote: > Try the using the array module. array objects provide a byteswap > method which reverses endianness. Thanks! Toby From B.Ogryczak at gmail.com Fri Feb 16 12:01:42 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 16 Feb 2007 09:01:42 -0800 Subject: why I don't like range/xrange In-Reply-To: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: <1171645302.453369.166190@s48g2000cws.googlegroups.com> On Feb 16, 4:30 pm, "stdazi" wrote: > for (i = 0; some_function() /* or other condition */ ; i++) C's "for(pre,cond,post) code" is nothing more, then shorthand form of "pre; while(cond) {code; post;}" Which translated to Python would be: pre while cond: code post From python at rcn.com Thu Feb 15 21:17:45 2007 From: python at rcn.com (Raymond Hettinger) Date: 15 Feb 2007 18:17:45 -0800 Subject: builtin set literal In-Reply-To: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> Message-ID: <1171592265.316602.234820@s48g2000cws.googlegroups.com> >> What about "{,}"? For consistency "(,)" and "[,]" might >> also have to be permissible, and maybe even "{:}" for an >> empty dict. The notion of a set literal was rejected in PEP 218, http://www.python.org/dev/peps/pep-0218/ . One of the reasons for the rejection was that the small benefit of a literal notion was more than offset by the attendant need for syntactical atrocities like those listed above. Raymond From tiedon_jano at hotmail.com Thu Feb 1 12:47:29 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 01 Feb 2007 17:47:29 GMT Subject: data design In-Reply-To: References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> <45bfbcc3$0$30950$426a74cc@news.free.fr> <1170201274.580256.182740@v45g2000cwv.googlegroups.com> Message-ID: James Stroud kirjoitti: > > > > For instance, I have a copy_files section of a configuration. In order > to know what goes with what you have to resort to gymnastics with the > option names > > [copy_files] > files_dir1 = this.file that.file > path_dir1 = /some/path > > files_dir2 = the_other.file yet_another.file > path_dir2 = /some/other/path > > > James You don't have to. With a config file: ### [copy_files] /some/path = this.file that.file C:\a windows\path with spaces= one.1 two.two a_continuation_line_starting_with_a_tab.xyz and_another_starting_with_a_some_spaces.abc /some/other/path = the_other.file yet_another.file ### the following program: ### #!/usr/bin/python import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open(r'ConfigTest.INI')) opts = config.options('copy_files') print opts print 'Files to be copied:' for opt in opts: path = opt optVal = config.get('copy_files', opt) #print opt, optVal fileNames = optVal.split() ### The following lines are only needed for Windows ### because the use of ':' in Windows' file name's ### device part clashes with its use in ConfigParser pathParts = '' for ind in range(len(fileNames)): if fileNames[ind][-1] in ':=': path += ':' + pathParts + fileNames[ind][:-1] del fileNames[:ind+1] break pathParts += fileNames[ind] + ' ' ### Windows dependent section ends print ' Path:', '>' + path + '<' for fn in fileNames: print ' >' + fn + '<' ### produces the following output: ### ['c', '/some/other/path', '/some/path'] Files to be copied: Path: >c:\a windows\path with spaces< >one.1< >two.two< >a_continuation_line_starting_with_a_tab.xyz< >and_another_starting_with_a_some_spaces.abc< Path: >/some/other/path< >the_other.file< >yet_another.file< Path: >/some/path< >this.file< >that.file< ### Cheers, Jussi From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 19:00:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Mar 2007 01:00:46 +0100 Subject: design question: no new attributes In-Reply-To: References: <8BIEh.1349$QI4.489@trnddc01><1172561344.290126.191530@h3g2000cwc.googlegroups.com><3c5Fh.3664$Tg7.2156@trnddc03> Message-ID: <45e60fdc$0$30655$426a34cc@news.free.fr> Alan Isaac a ?crit : > Ben Finney writes: > >>Really, though, adding attributes to an instance is a normal thing to >>do in Python, and you've not yet shown why you want that normal >>functionality to be special-cased here. > > > > I accept your earlier point that if an interface changes > one can just trap use of the old interface. But I remain > interested in preventing dynamic attribute creation in > particular cases. > > I have not tried to argue that dynamic attribute creation > can be dangerous for a couple reasons. > - There is no reason to expect this list to be receptive. Right. Don't you wonder why ? > - I do not have the experience to make a general argument. > - I do not always find it a problem, but only in certain situations. Which ones ? > However I will observe that > - entire languages are structured on the premise that dynamic > attribute creation can be hazardous Entire languages are structured on the premise that developers are dumb and that anything dynamic can be hazardous. Seriously, if you fear dynamic attribute creation, you'd better choose another language. What about dynamically changing the class of an object? Now ain't *that* hazardous ?-) > - debuggers watch out for dynamic attribute creation, Which ones ? > which > tells us it is a common source of bugs s/common/potential/ > - I sincerely doubt that anyone who has written more than > a couple scripts in Python has never accidentally created an > attribute dynamically while intending to assign to an existing > attribute. Of course. But MHE (7+ years of Python programming - more than a couple scripts...) is that this has not proven so far to be a common and annoying enough problem to justify fighting against the language. > I know the response: write good unit tests. OK, but right now > I am writing code where this restriction will serve as a reasonable > error check, I don't share your definition of "reasonable". But you should have guessed by now !-) From python at hope.cz Fri Feb 9 08:19:13 2007 From: python at hope.cz (Johny) Date: 9 Feb 2007 05:19:13 -0800 Subject: Strings in Python In-Reply-To: <1170977957.862904.164100@a75g2000cwd.googlegroups.com> References: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> <1170959568.410295.285410@l53g2000cwa.googlegroups.com> <1170977957.862904.164100@a75g2000cwd.googlegroups.com> Message-ID: <1171027153.025437.277550@q2g2000cwa.googlegroups.com> Thanks ALL for help and ideas L From sulsa at gazeta.pl Sun Feb 4 11:05:40 2007 From: sulsa at gazeta.pl (Sulsa) Date: Sun, 4 Feb 2007 17:05:40 +0100 Subject: Dlaczego ten destruktor nie dziala References: <20070204170503.4dbb1b14.sulsa@gazeta.pl> Message-ID: <20070204170540.09f393e7.sulsa@gazeta.pl> sorry, wrong group. From chris at shenton.org Fri Feb 9 09:07:40 2007 From: chris at shenton.org (Chris Shenton) Date: Fri, 09 Feb 2007 09:07:40 -0500 Subject: TimedRotatingFileHandler() isn't rotating at midnight? In-Reply-To: <1171021836.812953.183150@m58g2000cwm.googlegroups.com> (Vinay Sajip's message of "9 Feb 2007 03:50:36 -0800") References: <1171021836.812953.183150@m58g2000cwm.googlegroups.com> Message-ID: <86tzxvwhjn.fsf@Bacalao.shenton.org> "Vinay Sajip" writes: > It might. I assume you have a long-running process which runs past > midnight - that's the scenario that TimedRotatingFileHandler is meant > for. Can you post a complete minimal example which shows the problem? > Rotating should happen when the logging process creates the handler > before midnight and makes a logging call destined for that handler > after midnight. Ah, then maybe I'm expecting the wrong thing. The python code is invoked from cron every 10 minutes or so, it's not long-running. Each time it opens the same log file. Sounds like this isn't going to do what I want. Thanks for the clarification. From joshua at eeinternet.com Tue Feb 6 22:33:50 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 06 Feb 2007 18:33:50 -0900 Subject: Return images with matplotlib? References: <45c684e2$1@griseus.its.uu.se> Message-ID: <45c93c00$0$16291$88260bb3@free.teranews.com> Jan Danielsson wrote: > Hello all, > > I have written a program which takes some data from a postgresql > database, and via mod_python outputs it as tables on a web site. Now I > would like to present these tables as graphs, which matplotlib can do. > But in order to properly display these graphs on the web page, I need > to return the image data, like so: > > def barchart(req, params): > some_format = matplotlib.generate_fancy_graph(params) > png_buf = make_png_buffer(some_format) > return png_buf > > Is this possible? If so -- how? If you are returning the buffer (and nothing else) directly to a browser you can't print a Content-type header that says it's a png file, and the browser will accept it as a graphic, as long as you call the script from within an IMG tag. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From jstroud at mbi.ucla.edu Fri Feb 2 00:14:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 01 Feb 2007 21:14:12 -0800 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: Peter Otten wrote: > Chris wrote: > > >>I am trying to overload the __invert__ operator (~) such that >>it can take a second argument, other than >>self, so that I can express: >> >>x ~ y >> >>by using: >> >>def __invert__(self, other): >> >>for example. Is this possible? > > > No, you will get a syntax error before python even look up the names: > > >>>>x > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined > >>>>x ~ x > > File "", line 1 > x ~ x > ^ > SyntaxError: invalid syntax > > Peter Seems an arbitrary limitation. Consider - x and x - y Which is inconsistent with limiting ~ to a unary operation. James From tdelaney at avaya.com Thu Feb 15 18:19:58 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 16 Feb 2007 10:19:58 +1100 Subject: Method overloading? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EC9C@au3010avexu1.global.avaya.com> Steven D'Aprano wrote: > This is an example of overloading: > > class Cheese(object): > def flavour(self): > return "tasty and scrumptious" > def colour(self): > return "yellow" > > Now we define a sub-class which overloads some methods: > > class BlueVein(Cheese): > def colour(self): > return "white with blue veins" Nope - while the term "overloading" is definitely overloaded, the above is not an example of any use of "overloading". It is an example of "overriding". The most common use of "overloading" refers to having multiple methods on a class with the same name, but different signatures. Tim Delaney From mmanns at gmx.net Sat Feb 24 01:48:13 2007 From: mmanns at gmx.net (Martin Manns) Date: Sat, 24 Feb 2007 01:48:13 -0500 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <1172297970.069334.193020@a75g2000cwd.googlegroups.com> Message-ID: On 23 Feb 2007 22:19:30 -0800 casevh at gmail.com wrote: > > Looks pretty much the same as mx.Number > > > > Does this warning come up from gmp? Do I have to compile it with > > different flags? > > Or do both wrappers use the same code? > > > > I would like to encourage the python community (i.e. the guys > > maintaining the python docs) to point out a recommended rational > > library. In one of the rational PEPs, it is stated that there are > > multiple robust rational wrappers for python. But it is not stated, > > which ones were thoroughly reviewed. > > > That specific error message is only a warning that occurs the first > time a comparison operation is performed. I've successfully used gmpy > and just ignored the one-time only error. You can use the "warnings" > module to filter out that error. If I remember correctly, it was fixed > in version 1.01. I know it is fixed in the SVN version. > > Which specific version of gmpy are you using? (What is > gmpy.version()?) > $ python Python 2.4.3 (#1, Jan 13 2007, 20:53:15) [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gmpy >>> gmpy.version() '1.01' >>> Martin From Finger.Octopus at gmail.com Sat Feb 3 10:43:40 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 3 Feb 2007 07:43:40 -0800 Subject: How can I access data from MS Access? Message-ID: <1170517420.026596.74880@s48g2000cws.googlegroups.com> How to access data from MS Access? I tried ADOdb for Python but it doesn't seems to work. Even the official examples dont work, like this one: import adodb conn = adodb.NewADOConnection('access') # mxodbc required dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\inetpub\\adodb\ \northwind.mdb;" conn.Connect(dsn) (I have downloaded mxodbc, but still it doesn't works) From gagsl-py at yahoo.com.ar Tue Feb 6 19:08:25 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 21:08:25 -0300 Subject: Coordinate Grid Points References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> <1170727428.120082.47690@a75g2000cwd.googlegroups.com> <1170804943.418026.243480@q2g2000cwa.googlegroups.com> Message-ID: En Tue, 06 Feb 2007 20:35:43 -0300, escribi?: > Anyways heres my error: > ************************************************************************************************************************ > ***File "C:/Documents and Settings/Eric/Desktop/Python/2d guessing > game.py", line 11, in *** > *** randp = Point(random.randint(1, 20), random.randint(1, > 20)) *** > ***TypeError: default __new__ takes no > parameters > *** > class Point(object): > def _init_(self, x, y): > self.x = x > self.y = y > > #generate random coordinate point > randp = Point(random.randint(1, 20), random.randint(1, 20)) _init_ should be __init__ (two leading and trailing underscores) That special method is used to initialize your newly constructed Point instance. See section 9.3.2 on the Python tutorial: http://docs.python.org/tut/node11.html#SECTION0011320000000000000000 -- Gabriel Genellina From rory at campbell-lange.net Thu Feb 22 10:42:39 2007 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Thu, 22 Feb 2007 15:42:39 +0000 Subject: Local class variables? (mod_python problem) In-Reply-To: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> References: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> Message-ID: <20070222154239.GA12709@campbell-lange.net> Apologies to Piet and Diez for the lack of clarity in my previous post (and the broken code). In essence we use class variables as follows: class Part (object): totalgia = 0 def __init__(self, gia): self.gia = gia # gross internal area self.giaratio = 0 Part.totalgia += self.gia def addavgbm(self): self.giaratio = float(self.gia)/float(Part.totalgia) def __repr__(self): return "gia: %0.1f giaratio: %0.2f" % (self.gia, self.giaratio) if __name__ == '__main__': p1 = Part(20) p2 = Part(30) for p in p1, p2: p.addavgbm() print p totalgia keeps incrementing when this code is used under mod_python. We most certainly are in 'murky waters of accidental concurrent access'. A life vest would be gratefully received. Kind regards Rory On 22/02/07, Rory Campbell-Lange (rory at campbell-lange.net) wrote: > We have a set of classes using static methods to retain reference > variables between operations. The problem is that the static variables > are not reset between operations when used through mod_python. > > Although it is possible to reset the class variables between invocations > of the system, this has the potential of 'wiping out' these variables > when another user is using the system. > > Is there a way of getting the equivalent of 'local class variables'? In > other words, a way of making 'print a' and 'print b' below provide the > same output? On 22/02/07, Piet van Oostrum (piet at cs.uu.nl) wrote: > >>>>> Rory Campbell-Lange (RC) wrote: > There are several errors in your python code: quite a number of comma's > have to be replaced by semicolons (or newlines), and there is a spurious > comma. On 22/02/07, Diez B. Roggisch (deets at nospam.web.de) wrote: > Rory Campbell-Lange wrote: > It's very unclear what you mean here, and I'm additionally under the > impression that you are deep in the murky waters of accidential > concurrent access errors here. -- Rory Campbell-Lange From sjmachin at lexicon.net Fri Feb 9 20:19:09 2007 From: sjmachin at lexicon.net (John Machin) Date: 9 Feb 2007 17:19:09 -0800 Subject: Matching Strings In-Reply-To: References: Message-ID: <1171070349.681965.19720@h3g2000cwc.googlegroups.com> On Feb 10, 11:58 am, Larry Bates wrote: > rshepard-at-appl-ecosys.com wrote: > > On 2007-02-10, rshep... at nospam.appl-ecosys.com wrote: > > >> if item == selName: > > > Slicing doesn't seem to do anything -- if I've done it correctly. I > > changed the above to read, > > > if item[2:-2] == selName: > > > but the output's the same. > > > Rich > > Use the interpreter to test things: > > a="(u'ground water',)" > > a[2:-2] > "'ground water'" > > a[3:-3] > 'ground water' > > That is what you are looking for. True. Unfortunately he was looking for the wrong thing. He has: a = (u'ground water', ) a[2:-2] -> () a[3:-3] -> () () == 'ground water' -> False HTH, John From grante at visi.com Sun Feb 25 21:09:50 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 26 Feb 2007 02:09:50 -0000 Subject: getting terminal display size? References: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> <12u4g4ci5gqu46c@corp.supernews.com> Message-ID: <12u4gbepet1ek62@corp.supernews.com> On 2007-02-26, Grant Edwards wrote: > On 2007-02-26, jeff wrote: > >> I looked around a lot on the internet and couldn't find out how to do >> this, how do I get the sizer (in rows and columns) of the view? > > You use the TIOCGWINSZ ioctl() call on the tty device in question. > > import termios, fcntl, struct, sys > > s = struct.pack("HHHH", 0, 0, 0, 0) > fd_stdout = sys.stdout.fileno() > x = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s) > print '(rows, cols, x pixels, y pixels) =', > print struct.unpack("HHHH", x) You may also want to handle the WINCH signal so that you know when the window size has been changed. -- From SoutoJohn at gmail.com Sat Feb 3 11:01:56 2007 From: SoutoJohn at gmail.com (SoutoJohn at gmail.com) Date: 3 Feb 2007 08:01:56 -0800 Subject: CTypes Message-ID: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> I'm trying to install PyWinAuto for Python 2.4. It said that one of the required libraries that I need to install would be CTypes. So I head over to CTypes's SourceForge page and I installed CTypes for Python 2.4. I go to run the PyWinAuto installation file and it throws up this error: C:\WINDOWS\Desktop\pywinauto-0.3.6>C:\Python24\Python setup.py install Traceback (most recent call last): File "setup.py", line 29, in ? import pywinauto File "C:\WINDOWS\Desktop\pywinauto-0.3.6\pywinauto\__init__.py", line 28, in ? import findwindows File "C:\WINDOWS\Desktop\pywinauto-0.3.6\pywinauto\findwindows.py", line 31, i n ? import win32functions File "C:\WINDOWS\Desktop\pywinauto-0.3.6\pywinauto \win32functions.py", line 14 9, in ? GetModuleFileNameEx = ctypes.windll.psapi.GetModuleFileNameExW File "C:\PYTHON24\lib\site-packages\ctypes\__init__.py", line 387, in __getatt r__ dll = self._dlltype(name) File "C:\PYTHON24\lib\site-packages\ctypes\__init__.py", line 312, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Errno 1157] One of the library files needed to run this applicati on cannot be found I have found out that anything that calls CTypes is producing this error. I looked into the CTypes source and I found: def __init__(self, name, mode=DEFAULT_MODE, handle=None): self._name = name if handle is None: self._handle = _dlopen(self._name, mode) References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> <1170683733.434435.171350@j27g2000cwj.googlegroups.com> <1170687265.764375.96560@p10g2000cwp.googlegroups.com> Message-ID: <1170954994.946871.75830@l53g2000cwa.googlegroups.com> Yes, of course. But you can still fine-tune the code for the sources you want to parse. The C++ header files I needed to analyze contained no such strings. I believe there are very few real-life .h files out there containing those. In fact I chose #::OPEN::# and #::CLOSE::# because they're more foreign to C++ like eg. ::OPEN or #OPEN would be. I hope this makes sense. :) Roberto Bonvallet ?rta: > K?roly Kiripolszky wrote: > > I've found a brute-force solution. In the preprocessing phase I simply > > strip out the comments (things inside comments won't appear in the > > result) and replace curly brackets with these symbols: #::OPEN::# and > > #::CLOSE::#. > > This fails when the code already has the strings "#::OPEN::#" and > "#::CLOSE::" in it. > > -- > Roberto Bonvallet From michele.petrazzoDELETE at DELETEunipex.it Sat Feb 24 03:07:47 2007 From: michele.petrazzoDELETE at DELETEunipex.it (Michele Petrazzo) Date: Sat, 24 Feb 2007 08:07:47 GMT Subject: failed to install PIL in fedora core 6 In-Reply-To: <1172300619.894761.243200@z35g2000cwz.googlegroups.com> References: <1172300619.894761.243200@z35g2000cwz.googlegroups.com> Message-ID: Frank Potter wrote: > I use "python setup.py install" to install PIL in fedora with python > 2.4, But I got these errors: <-cut some errors-> > error: Python.h: No such file or directory In file included from > libImaging/Imaging.h:14, from _imaging.c:78: So you don't have the python-dev package. > What should I do if I want to successfully have pil installed? Try to search into the Fedora repos for the PIL (or python-imaging). If not, install the python-dev and compile! Michele From gagsl-py at yahoo.com.ar Sun Feb 11 14:18:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 16:18:17 -0300 Subject: Adding an XML fragment as a child node in a pre-existing Element tree References: <1171217718.232391.291850@v45g2000cwv.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 15:15:21 -0300, Rajarshi escribi?: > Hi, I'm using ElementTree for some RSS processing. The point where I > face a problem is that within an I need to add another > child node (in addition to etc) which is a well-formed XML > document (Chemical Markup Language to be precise). > > So my code looks like: > > import cElementTree as ET > > c = open('x.cml').readlines() > c = string.join(c) > cml = ET.XML(c) All the above thing can be replaced by: cml = ET.parse("x.cml") > > Now I also have the following code: > > def addItem(self, title, link, description, cml = None): > RSSitem = ET.SubElement ( self.RSSchannel, 'item' ) > > ET.SubElement( RSSitem, 'title' ).text = title > ET.SubElement( RSSitem, 'description' ).text = description > > What I'm confused is how I can add the cml Element object that I > generated, to the RSSitem as a child node. SubElement is just a convenience function for creating a new element and appending it to an existing parent element. As you already have the new subelement, just use append: RSSitem.append(cml) See the documentation at http://www.effbot.org/zone/element-index.htm -- Gabriel Genellina From gagsl-py at yahoo.com.ar Tue Feb 6 23:24:54 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Feb 2007 01:24:54 -0300 Subject: need help to kill a process References: <1170813580.163486.219190@l53g2000cwa.googlegroups.com> Message-ID: En Tue, 06 Feb 2007 22:59:40 -0300, escribi?: > this is my code snip. > within my python script I have the following commands.. > > > > import os > ... > os.system ("cd /home; ./TestTool &") > os.system ("cd /usr/; sh run.sh load.xml &") > > > > I need to kill these 2 process after a particular job is done.. is > there any way to get the pids of these process and if so how do i > invoke the kill command through os.system.. > > or else is there anyother way to do this... If you're using Python>=2.4 you could use the subprocess module. import subprocess child1 = subprocess.Popen(["./TestTool"], cwd="/home") child2 = subprocess.Popen(["sh","run.sh","load.xml"], cwd="/usr") Popen objects have a pid attribute. You don't have to use os.system to kill them; use os.kill instead. You'll notice that I leave out the final &, because I don't know how to start a background process without using the shell. But I think you can use: bg [pid], afterwards, to get the same result. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Sun Feb 18 02:49:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 18 Feb 2007 18:49:43 +1100 Subject: Need an identity operator because lambda is too slow References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> Message-ID: On Sat, 17 Feb 2007 21:59:18 -0800, Deron Meranda wrote: > Consider a much-simplified example of such an iteration where > sometimes you need to transform an item by some function, but most of > the time you don't: > > if some_rare_condition: > func = some_transform_function > else: > func = lambda x: x > for item in some_sequence: > item2 = func(item) > ..... # more stuff This does the test once, but does a function look-up every loop. > Now the "lambda x:x" acts suitably like an identity operator. But it > is very slow, when compared to using more complex-looking code: > > do_transform = some_rare_condition > for item in some_sequence: > if do_transform: > item2 = transform_function(item) > else: > item2 = item > ..... # more stuff Despite doing the if..else comparison every loop, this is a little faster for the case where some_rare_condition is false. But I have to question whether this is a worthwhile optimization, especially if some_rare_condition really is rare. Calling the identity function "lambda x: x" one million times takes about half a second; or to put it another way, each call to the identity function costs you about half a microsecond. How much time does the rest of the loop processing take? Are you sure you're optimizing something which needs to be optimized? (E.g. if your main loop takes fifteen minutes to run, and you're trying to shave off half a second, just don't bother.) Compare the following, where I use an arbitrary small function as a placeholder for whatever work you really want to do: setup = """import time identity = lambda x: x do_work = lambda x: time.time() + x x = 1 """ Now use timeit to compare doing the work on its own with doing the work together with an identity function: >>> timeit.Timer("do_work(x)", setup).repeat() [3.1834621429443359, 3.1083459854125977, 3.1382210254669189] >>> timeit.Timer("do_work(identity(x))", setup).repeat() [3.5951459407806396, 3.6067559719085693, 3.5801000595092773] Is your "do_work" function really so fast that one second per two million calls to identity() is a significant load? If some_rare_condition really is rare, then a possible solution might be: if some_rare_condition: some_sequence = [transform(item) for item in some_sequence] # or modify in place if needed... see enumerate for item in some_sequence: do_something_with(item) This should run as fast as possible in the common case, and slow down only in the rare condition. Another solution would be: if some_rare_condition: for item in some_sequence: item = transform(item) do_something_with(item) else: for item in some_sequence: do_something_with(item) This is probably going to be the fastest of all, but has the disadvantage that you are writing the same code twice. -- Steven. From gnewsg at gmail.com Mon Feb 19 04:31:06 2007 From: gnewsg at gmail.com (billie) Date: 19 Feb 2007 01:31:06 -0800 Subject: distutils and paths Message-ID: <1171877466.385801.309900@a75g2000cwd.googlegroups.com> Hi there. I played with distutils for some hours but I didn't figured out how to solve this problem so I would really be thankful if someone could help me out. My package is structured as follows: setup.py | mypkg | | | __init__.py | library.py | test | | | test.py | doc | doc.html doc_files | doc.css By using setup.py script I would like to copy "test" and "doc" directories (and all files contained in them) into Python's site- package directory (on Windows "C:\Python2x\Lib\site-packages\mypkg", on unix "/usr/lib/python2.x/site-packages/mypkg".) Could someone point me in the right direction, please? Thanks in advance. From mail at timgolden.me.uk Mon Feb 12 10:53:51 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 12 Feb 2007 15:53:51 +0000 Subject: WindowsNT user authentication In-Reply-To: <1171294708.261232.18290@p10g2000cwp.googlegroups.com> References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> <1171294708.261232.18290@p10g2000cwp.googlegroups.com> Message-ID: <45D08D8F.6010108@timgolden.me.uk> billie wrote: > Do you got any idea about how getting user's home directory? The answer to that is unfortunately slightly complicated, because Windows has no such thing as a "user's home directory" or, if you prefer, it has several such things. If you want, you can let Python make the decision, by calling os.path.expanduser on "~" which, in my case, correctly gives h:\ which is my domain home directory. Obviously this is not necessarily the same as my Documents and Settings directory, which can also be considered a home directory. That you can get by querying the shell: from win32com.shell import shell, shellcon idlist = shell.SHGetSpecialFolderLocation (0, shellcon.CSIDL_PERSONAL) documents_and_settings = shell.SHGetPathFromIDList (idlist) print documents_and_settings In my case they are the same but that will depend on your setup. I know in the past at least one of these has defaulted to c:\ Alternatives (which in my case amount to the same thing) include using the HOMEDRIVE / HOMEPATH / HOMESHARE environment vars: import os drive = os.environ.get ("HOMEDRIVE", "") path = os.environ.get ("HOMEPATH", "") share = os.environ.get ("HOMESHARE", "") print drive+path print share I haven't bothered to look, but I think this latter is how the expanduser function works things out. YMMV TJG From jeff at kalikstein.com Tue Feb 6 17:01:20 2007 From: jeff at kalikstein.com (jeff) Date: 6 Feb 2007 14:01:20 -0800 Subject: Help reading binary data from files Message-ID: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> I am stumped trying to read binary data from simple files. Here is a code snippet, where I am trying to simply print little-endian encoded data from files in a directory. for name in os.listdir(DOWNLOAD_DIR): filename = s.path.join(DOWNLOAD_DIR, name) if os.path.isfile(filename): f = open(filename, 'rb') while True: ele = unpack(' <1170492758.498303.55730@v33g2000cwv.googlegroups.com> Message-ID: <1147f$45c49c24$54d1d767$20780@news.chello.no> On Saturday 03 February 2007 09:52, Paddy wrote: > On Feb 3, 8:24 am, vis... at veriwave.com wrote: >> I am trying to work out a regular expression in a PyQt environment for >> time in hh:mm:ss format. Any suggestions? > > Yep, > Use Kodos! > http://kodos.sourceforge.net/ > > - It's Fab. There's also a Python port of the Regular Expressions example from Qt in the PyQt source distribution, though it's not as feature complete as Kodos, obviously. :-) Vishal should probably start by trying one of these tools, typing something like (\d\d):(\d\d):(\d\d) into the regular expression (or pattern) field. David From ziga.seilnacht at gmail.com Mon Feb 26 16:56:26 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 26 Feb 2007 13:56:26 -0800 Subject: 2.4->2.5 current directory change? In-Reply-To: References: <1172523655.177915.94840@s48g2000cws.googlegroups.com> Message-ID: <1172526986.736247.313120@h3g2000cwc.googlegroups.com> Chris Mellon wrote: > Considering that it's a backwards incompatible breaking change > (although I understand why it was done), you'd think it deserved > mention in the more prominent "Whats new in Python 2.5" section on the > website, in addition to a one-liner in the NEWS file. Ah well, while > I'm sure I'm not the only one who ran into it, it doesn't seem to be > causing mass calamity and I know now. I guess that most of the scripts that want curdir on path and work on different platforms already have to include current directory manualy. Twisted's preamble in Trial does that too, but it is too cautious to work on Windows (line 15 in the trial script): if hasattr(os, "getuid") and os.getuid() != 0: sys.path.insert(0, os.curdir) Maybe that can be changed to: if not hasattr(os, "getuid") or os.getuid() != 0: sys.path.insert(0, os.curdir) I'm no security expert, and I don't know if there are other operating systems that don't have getuid() function but have a superuser, but this doesn't look that less secure to me. Ziga From jstroud at mbi.ucla.edu Mon Feb 5 21:33:18 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 05 Feb 2007 18:33:18 -0800 Subject: Coordinate Grid Points In-Reply-To: <1170727428.120082.47690@a75g2000cwd.googlegroups.com> References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> <1170727428.120082.47690@a75g2000cwd.googlegroups.com> Message-ID: Eric.Gabrielson at gmail.com wrote: > On Feb 5, 3:29 pm, James Stroud wrote: > >>Eric.Gabriel... at gmail.com wrote: >> >>>Hello, >>> I am very knew to python and am attempting to write a program >>>in python that a friend of mine is having to write in java. I am doing >>>this for fun and would like some help as to how i can generate random >>>coordinate points (x,y) and compare them with user inputted coordinate >>>points. For example how will I be able to access the separate values, >>>the x from the x,y position. I think I understand everything except >>>1)the random coordinate points 2) the getting the users inputted x and >>>y values in one line ("Please guess a coordinate point from (1,1) to >>>(20,20): ") as opposed to ("Please enter an x value:" and "Please >>>enter a y value") and finally 3) acessing the x value from the x,y >>>coordinate function. the assignment description is located here http:// >>>www.cs.washington.edu/education/courses/142/07wi/homework/ >>>homework.html if you would like to see a more in depth discription of >>>the game. >> >>>Many Thanks, >>>Eric >> >>For 1: see the random module (e.g. random.randint) >>For 2: see the "eval" function and "raw input" >>For 2 (without cheating): see the re module. For example: >>***************************************************************************** >> ***map(int, re.compile("\(?(\d+),(\d+)\)?").search(inpt).groups())**** >>***************************************************************************** >>(Giving you the latter because eval will do this for you anyway.) >> >>Also see "raw_input". >> >>James > > > Thank you very much for your response i will play around with the code > when I have some time ( hopefully later tonight) but could you please > breakdown what the part that I surrounded with asterisks, I think I > recognize it but don't understand it. > > Eric > "re" is the regular expression module for python. "re.compile()" compiles the regular expression into a regular expression object with certain attributes, one of which is "search". "search" searches a string, here "inpt", and this produces a "match" (actually a _sre.SRE_Match) object that has, as one of its attributes, a "groups()" method that returns matches to the grouped expressions inside the regular expression, i.e. expressions surrounded by un-escaped parentheses. Inside of the quotes is a regular expression string, (that, in general, should be preceded immediately by a lowercase r--but is not here because it doesn't matter in this case and I forgot to). map() maps a callable (here int) to the list of groups returned by groups(). Each group is a string matching r"\d+" which is an expression for one or more digits. Each group is converted into an integer and map returns a list of integers. I escaped the enclosing parentheses and put question marks (match zero or one) so that the enclosing parentheses would be optional. This makes all of the following evaluate to [20, 20]: "20,20" "(20,20" "20,20)" "(20,20)" Except for typos, the middle two would be quite uncommon for user input, but would match the expression. Note also, that I didn't allow for whitespace anywhere, which might be expected. Arbitrary whitespace is matched by r"\s*". James From jeremit0 at gmail.com Tue Feb 6 16:00:08 2007 From: jeremit0 at gmail.com (jeremito) Date: 6 Feb 2007 13:00:08 -0800 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <45c8d18d$0$418$426a34cc@news.free.fr> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> Message-ID: <1170795607.938431.144340@p10g2000cwp.googlegroups.com> On Feb 6, 2:36 pm, Bruno Desthuilliers wrote: > jeremito a ?crit : > > > > > On Feb 6, 10:59 am, "bruno.desthuilli... at gmail.com" > > wrote: > > >>On 6 f?v, 16:23, "jeremito" wrote: > > (snip) > >>>But I can't even get __setitem__ to run. > > >>of course, since your __new__ method returns a dict instance, not a xs > >>instance... > >>There are very few cases where you really need to override the __new__ > >>method. > > > The reason I create my object with __new__ instead of __init__ is > > because when I use __init__ when a value is set it calls __setitem__. > > This is what I want to happen, but not inside of __init__. Does this > > make sense? > > It would make sens - if you couldn't call dict.__setitem__ directly. > > > > > > > I'm sure there is a better/more pythonic way to do this, > > but I'm unsure of what it is. Can someone show me an example of how > > this should work? > > (snip) > >>>Is this what the __setitem__ method is for? > > >>Yes. But note that you you need to manually call the superclass's > >>overriden method - unless you > >>really want to replace it with your own, which is obviously not the > >>case here... > > >>Note that if someone manually changes the values of xG, xF, or xS, the > >>computed values of xA and/or xT > >>won't reflect this change. Is that what you want ? > > > Eventually (when I figure out how to use __setitem__) I will change > > what happens when xG, xF, or xS are changed so that it also changes xA > > and xT. > > Which is not the best way to go IMHO. Unless the computation is very > intensive (which doesn't seem to be the case here) or it's heavily used > in big loops *and* the perfs are not good enough, it's better to > recompute on the fly at read time. And if one of the above cases arises, > then it will be time to use memoization (ie: cache the result of > computation, invalidating the cache when needed). > > > > >>Finally, and if I may ask, what is your use-case for subclassing > >>dict ? You don't need this to implement a dict-like object, > >>and it might be simpler in your case to write an ordinary class, then > >>add support for the required subset of the dict interface. > > > Eventually I am going to add other features to my class (as I have > > mentioned) so I can't simply use a dict object. > > I already understood this. My question is : why do you want to > *subclass* dict. In Python, inheritence is only about implementation, > it's *not* needed for polymorphism to work. So you don't have to > subclass dict to have an object behaving (more or less, that's up to > you) like a dict. > > Here's an alternative implementation, so you get the idea. Note that it > behaves mostly like a dict (well, not totally, but since we don't know > which subset of the dict interface you need...), but also like a > 'standard' object, so you can use either cs.['xT'] or cs.xT with the > same result. > > class Xs(dict): > """ > Xs is a container object to hold information about cross sections. > """ > _computedkeys = 'xA', 'xT' > > def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): > self.xS = xS > self.xF = xF > self.xG = xG > self.nu = nu > > # xA and xT as properties (AKA computed attributes) > def _get_xA(self): > return self.xG + self.xF > def _set_xA(self, dummy): > raise AttributeError( > "%s.xA is read-only" % self.__class__.__name__ > ) > xA = property(fset=_set_xA, fget=_get_xA) > > def _get_xT(self): > return self.xA + self.xS > def _set_xT(self, dummy): > raise AttributeError( > "%s.xT is read-only" % self.__class__.__name__ > ) > xT = property(fset=_set_xT, fget=_get_xT) > > # dict interface support, to be extended if needed > def __setitem__(self, key, value): > setattr(self, key, value) > > def __getitem__(self, key): > return getattr(self, key) > > def keys(self): > return self.__dict__.keys() + list(self._computedkeys) > > def values(self): > return self.__dict__.values() \ > + [getattr(self, key) for key in self._computedkeys] > > def items(self): > return zip(self.keys(), self.values()) > > def __iter__(self): > for k in self.keys(): > yield k > raise StopIteration > > def __contains__(self, key): > return key in self.keys() > > def __repr__(self): > return repr(dict(self.items())) Thanks a lot for your help. I think what you have written is much better than what I could have come up with on my own. I guess I just need more experience. Thanks, Jeremy From pierre.imbaud at laposte.net Thu Feb 8 05:31:23 2007 From: pierre.imbaud at laposte.net (Imbaud Pierre) Date: Thu, 08 Feb 2007 11:31:23 +0100 Subject: iso 8601, quality criteria In-Reply-To: <45caf119$0$25912$426a74cc@news.free.fr> References: <45caf119$0$25912$426a74cc@news.free.fr> Message-ID: <45cafbf7$0$29486$426a74cc@news.free.fr> Imbaud Pierre a ?crit : cutnpaste error in this posting, here is the complete message: Context: I am writing an application that accesses XMP-coded files. Some fields contain dates, and comply to iso 8601. I installed the iso8601 python module (http://cheeseshop.python.org/pypi/iso8601), it fails on the simplest forms: ipdb> parse_date('2005-01-01') *** TypeError: expected string or buffer (behaves fine with complete strings, but this one is legal!) Choose a module Python interfaces to the world: very few libs or protocols have no python module interfacing them. But they sometimes have many, and it aint easy to pick up the right one. And if there is only one, it aint obvious wether it will fill your quality criteria. My dream: a table with, for each library/module or even application, a note in [0:10] in front of every quality criterium. criteria?: completeness robustness how well tested? simplicity documentation maintenance team responsiveness usage: how many developpers picked it up and still use it? how many picked it up but gave it up? The list is an obvious oversimplification, each criterium could be discussed for hours. robustness, for instance, means: how well does it behave when illegal data is fed? A LOT of actual modules (comprising mine (:-) raise obscure exceptions. the iso8601 module is simple enough, easy to install, but fails on legal data. I guess the fix would be useful, but is it maintained? Is it in use? I used xml.dom.minidom, recently. Works fine, but I found the interface awfully complicated. Right or wrong, when I had to write some xml, I wrote my own code: better be simple, although untested, undocumented, etc, than using a module so complicated U never finished the learning curve... So, my questions would be: - how do You, other developpers, cope with this question? - is there such a base, helping to pick up existing modules? - if no, dont U think such an initiative might be useful? - Those who have to deal with iso8601 dates, how do U proceed? Ill have a look to mxdatetime, but is it the right answer? From george.sakkis at gmail.com Fri Feb 2 01:39:27 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 1 Feb 2007 22:39:27 -0800 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: <1170398367.258727.262840@l53g2000cwa.googlegroups.com> On Feb 2, 12:49 am, James Stroud wrote: > Ben Finney wrote: > > > The Python runtime parser is designed to parse Python, not some > > arbitrary language that someone chooses to implement in Python. > > You haven't addressed why the limitation isn't arbitrary. Indeed, and that's because it is arbitrary. Python has the arbitrary limitation that it's not Perl (or C, or Lisp or what have you). George From grahamd at dscpl.com.au Mon Feb 5 16:39:22 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 5 Feb 2007 13:39:22 -0800 Subject: Python does not play well with others In-Reply-To: <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> References: <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> Message-ID: <1170711562.894756.120270@h3g2000cwc.googlegroups.com> On Feb 6, 4:52 am, John Nagle wrote: > sjdevn... at yahoo.com wrote: > > John Nagle wrote: > > >>Graham Dumpleton wrote: > > >>>On Feb 4, 1:05 pm, Paul Rubin wrote: > > >>>>"Paul Boddie" writes: > >> Realistically, mod_python is a dead end for large servers, > >>because Python isn't really multi-threaded. The Global Python > >>Lock means that a multi-core CPU won't help performance. > > > The GIL doesn't affect seperate processes, and any large server that > > cares about stability is going to be running a pre-forking MPM no > > matter what language they're supporting. > > Pre-forking doesn't reduce load; it just improves responsiveness. > You still pay for loading all the modules on every request. For > many AJAX apps, the loading cost tends to dominate the transaction. > > FastCGI, though, reuses the loaded Python (or whatever) image. > The code has to be written to be able to process transactions > in sequence (i.e. don't rely on variables intitialized at load), > but each process lives for more than one transaction cycle. > However, each process has a copy of the whole Python system, > although maybe some code gets shared. As someone else pointed out, your understanding of how mod_python works within Apache is somewhat wrong. I'll explain some things a bit further to make it clearer for you. When the main Apache process (parent) is started it will load all the various Apache modules including that for mod_python. Each of these modules has the opportunity to hook into various configuration phases to perform actions. In the case of mod_python it will hook into the post config phase and initialise Python which will in turn setup all the builtin Python modules. When Apache forks off child processes each of those child processes will inherit Python already in an initialised state and also the initial Python interpreter instance which was created, This therefore avoids the need to perform initialisation of Python every time that a child process is created. In general this initial Python interpreter instance isn't actually used though, as the default strategy of mod_python is to allocate distinct Python interpreter instances for each VirtualHost, thereby at least keeping applications running in distinct VirtualHost containers to be separate so they don't interfere with each other. Yes, these per VirtualHost interpreter instances will only be created on demand in the child process when a request arrives which necessitates it be created and so there is some first time setup for that specific interpreter instance at that point, but the main Python initialisation has already occurred so this is minor. Most importantly, once that interpreter instance is created for the specific VirtualHost in the child process it is retained in memory and used from one request to the next. If the handler for a request loads in Python modules, those Python modules are retained in memory and do not have to be reloaded on each request as you believe. If you are concerned about the fact that you don't specifically know when an interpreter instance will be first created in the child process, ie., because it would only be created upon the first request arriving that actually required it, you can force interpreter instances to be created as soon as the child process has been created by using the PythonImport directive. What this directive allows you to do is specify a Python module that should be preloaded into a specific interpreter instance as soon as the child process is created. Because the interpreter will need to exist, it will first be created before the module is loaded thereby achieving the effect of precreating the specific named interpreter instance. So as to make sure you don't think that that first interpreter instance created in the parent and inherited by the child processes is completely wasted, it should be pointed out that the first interpreter instance created by Python is sort of special. In general it shouldn't matter, but there is one case where it does. This is where a third party extension module for Python has not been written so as to work properly in a context where there are multiple sub interpreters. Specifically, if a third party extension module used the simplified API for GIL locking one can have problems using that module in anything but the first interpreter instance created by Python. Thus, the first instance is retained and in some cases it may be necessary to force your application to run within the context of that interpreter instance to get it to work where using such a module. If you have to do this for multiple applications running under different VirtualHost containers you loose your separation though, thus this is only provided as a fallback when you don't have a choice. I'll mention one other area in case you have the wrong idea about it as well. In mod_python there is a feature for certain Python modules to be reloaded. This feature is normally on by default but is always recommended to be turned off in a production environment. To make it quite clear, this feature does not mean that the modules which are candidates for reloading will be reloaded on every request. Such modules will only be reloaded if the code file for that module has been changed. Ie., its modification time on disk has been changed. In mod_python 3.3 where this feature is a bit more thorough and robust, it will also reload a candidate module if some child or descendant of the module has been changed. So to summarise. Interpreter instances once created in the child processes for a particular context are retained in memory and used from one request to the next. Further, any modules loaded by code for a request handler is retained in memory and do not have to be reloaded on each request. Even when module reloading is enabled in mod_python, modules are only reloaded where a code file associated with that module has been changed on disk. Does that clarify any misunderstandings you have? So far it looks like the only problem that has been identified is one that I already know about, which is that there isn't any good documentation out there which describes how it all works. As a result there are a lot of people out there who describe wrongly how they think it works and thus give others the wrong impression. I already knew this, as I quite often find myself having to correct statements on various newgroups and in documentation for various Python web frameworks. What is annoying is that even though you point out to some of the Python web frameworks that what they state in their documentation is wrong or misleading they don't correct it. Thus the wrong information persists and keeps spreading the myth that there must be some sort of problem where there isn't really. :-( Graham From sam.schelfhout at gmail.com Fri Feb 23 06:31:17 2007 From: sam.schelfhout at gmail.com (beeswax) Date: 23 Feb 2007 03:31:17 -0800 Subject: Reading mails from Outlook In-Reply-To: <45DDAC99.7040009@websafe.com> References: <1172152420.295840.133600@t69g2000cwt.googlegroups.com> <45DDAC99.7040009@websafe.com> Message-ID: <1172230277.732888.14620@v33g2000cwv.googlegroups.com> On 22 feb, 15:45, Larry Bates wrote: > beeswax wrote: > > Hi, > > > Does anyone knows how to read e-mails from a specific folders in > > outlook? > > I only found out how to read the mails from the inbox folder and how > > to list all available folder. > > I just don't found a way to access my mails from the other folders. > > > Can anyone help me? > > > Regards, > > > Sam > > I'll bet that some of the best information you can get about interacting > with Outlook is going to be by looking at the sourcecode to SpamBayes > plug-in. You can get it from here: > > https://sourceforge.net/project/showfiles.php?group_id=61702&package_... > > -Larry Hi again, I found the solution myself, the next code will iterate all folders, sub folders and their mails. I just needed to understand what I could do with the folders objects. But, this code will trow an error when trying to connect to shared folders (exchange folders etc). Btw does anyone knows a good API for this, or a way to get all the properties from an object? # Create instance of Outlook o = win32com.client.gencache.EnsureDispatch("Outlook.Application") # Dump all folders recursive, starting from root DumpFoldersRecursive(o.GetNamespace("MAPI").Folders,0) o = None def DumpFoldersRecursive(folders,indent): # Note: the com indexes start from 1 for i in range(1,folders.Count+1): folder = folders[i] print '%sFolder %d: "%s"' % ('\t'*indent,i,DecodeUnicodeString(folder.Name)) # if a folder has no subfolders, its Folders.Count will be zero, so this is safe. for i in range(len(folder.Items)): message = folder.Items[i+1] print message.Subject DumpFoldersRecursive(folder.Folders,indent+1) Regards, Sam From FreakCERS at gmail.com Sun Feb 25 03:21:49 2007 From: FreakCERS at gmail.com (Christian Sonne) Date: Sun, 25 Feb 2007 09:21:49 +0100 Subject: RegExp performance? Message-ID: <45e145a0$0$90264$14726298@news.sunsite.dk> Long story short, I'm trying to find all ISBN-10 numbers in a multiline string (approximately 10 pages of a normal book), and as far as I can tell, the *correct* thing to match would be this: ".*\D*(\d{10}|\d{9}X)\D*.*" (it should be noted that I've removed all '-'s in the string, because they have a tendency to be mixed into ISBN's) however, on my 3200+ amd64, running the following: reISBN10 = re.compile(".*\D*(\d{10}|\d{9}X)\D*.*") isbn10s = reISBN10.findall(contents) (where contents is the string) this takes about 14 minutes - and there are only one or two matches... if I change this to match ".*[ ]*(\d{10}|\d{9}X)[ ]*.*" instead, I risk loosing results, but it runs in about 0.3 seconds So what's the deal? - why would it take so long to run the correct one? - especially when a slight modification makes it run as fast as I'd expect from the beginning... I'm sorry I cannot supply test data, in my case, it comes from copyrighted material - however if it proves needed, I can probably construct dummy data to illustrate the problem Any and all guidance would be greatly appreciated, kind regards Christian Sonne PS: be gentle - it's my first post here :-) From mblume at socha.net Mon Feb 19 15:40:22 2007 From: mblume at socha.net (Martin Blume) Date: Mon, 19 Feb 2007 21:40:22 +0100 Subject: How to call a function defined in another py file References: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> <45da0720$0$3822$5402220f@news.sunrise.ch> <1171916841.964600.262530@q2g2000cwa.googlegroups.com> Message-ID: <45da0b36$0$3822$5402220f@news.sunrise.ch> schrieb >> >>> I have a function called 'test' defined in A.py. >>> How can I call that function test in my another file B.py? >> >> In B.py: >> import A >> A.test() >> > > But Do I need to put A.py and B.py in the same directory? No, but then you have to take certain precautions. (*) > if not, where does python look for A.py ? In the path defined by the (IIRC) PYTHONPATH (*) > And do I need to compile A.py before I can import it to B.py? No. (*) you might want to read the fine documentation at http://docs.python.org/tut/node8.html which tells it much better than I do, and might give you some more ideas for googling. I haven't had yet the necessity for cross-directory imports. HTH Martin From alan.franzoni_invalid at geemail.invalid Wed Feb 28 11:24:05 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 28 Feb 2007 17:24:05 +0100 Subject: Python Source Code Beautifier References: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> Message-ID: <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> Il 27 Feb 2007 16:14:20 -0800, sjdevnull at yahoo.com ha scritto: > Those mean different things: > >>>> a=[1] >>>> b=a >>>> a += [2] >>>> a > [1, 2] >>>> b > [1, 2] >>>> a=[1] >>>> b=a >>>> a = a + [2] >>>> a > [1, 2] >>>> b > [1] This is a really nasty one! I just answered to Tim above here, and then I saw your example... I had never realized that kind of list behaviour. That's probably because i never use + and += on lists (i prefer the more explicit append() or extend() and i do copy list explictly when I want to) , BTW I think this behaviour is tricky! -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From paul at boddie.org.uk Wed Feb 7 11:35:26 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Feb 2007 08:35:26 -0800 Subject: multithreading concept In-Reply-To: References: Message-ID: <1170866126.933766.66430@h3g2000cwc.googlegroups.com> On 7 Feb, 02:53, "S.Mohideen" wrote: > > Python is praised about - me too. But at one instance it fails. It fails to > behave as a true multi-threaded application. That means utilizing all the > CPUs parallely in the SMP efficiently stays as a dream for a Python > Programmer. Take a look at the Python Wiki for information on parallel processing with Python: http://wiki.python.org/moin/ParallelProcessing Pure CPython code may not be able to use more than one CPU merely through the use of threads (Jython and IronPython are different, though), but using all the CPUs or cores in an SMP system is not exactly a mere dream, as many of the projects listed on the above page demonstrate. Paul From bignose+hates-spam at benfinney.id.au Tue Feb 13 16:32:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Feb 2007 08:32:42 +1100 Subject: Undo os.remove References: <1171398956.060378.215530@q2g2000cwa.googlegroups.com> Message-ID: <87fy999211.fsf@benfinney.id.au> chris.peressotti at gmail.com writes: > Hi. I just used os.remove to get rid of some files -- > unfortunately, I realized afterward that I didn't really want to get > rid of them. It isn't life-or-death, here, but is there any way for > me to get these files back? Since 'os.remove' delegates the actual removal to your operating system, it's a matter of whether your operating system has a way to get those files back. Most operating systems don't have a simple "bring this file back" system call (the way they have a "remove this file" system call), so Python can't provide such an interface. But your operating system might provide a way. -- \ "Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force." -- Carol Reichel | _o__) | Ben Finney From grante at visi.com Fri Feb 9 14:58:31 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 09 Feb 2007 19:58:31 -0000 Subject: Thanks to all References: Message-ID: <12spkj7kb245k07@corp.supernews.com> On 2007-02-09, jiddu wrote: > Thanks for all the input guys, I know it is difficult, but the > calculators and statistic sites/books are missing some things > which I need for my play so I guess I have no choice but to > study up and work. You're most welcome. Though I really have no idea whom you're thanking or for what you're thanking them [a situation remedied by posting your thank-you as a follow-up to the relevent thread], it would be rude for nobody to acknowledge your thanks. ;) -- Grant Edwards grante Yow! ... this must be what at it's like to be a COLLEGE visi.com GRADUATE!! From gigs at hi.t-com.hr Fri Feb 2 08:27:59 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 02 Feb 2007 14:27:59 +0100 Subject: coping directories In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ escribi?: > >> class CVisitor(FileVisitor): >> def __init__(self, fromdir, todir): >> self.fromdirLen = len(fromdir) + 1 # here is my problem >> self.todir = todir >> FileVisitor.__init__(self, fromdir) >> def visitdir(self, dirpath): >> topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) >> os.mkdir(topath) >> def visitfile(self, filepath): >> topath = os.path.join(self.todir, filepath[self.fromdirLen:]) >> cpfile(filepath, topath) #copy contents from filepath to >> topath[/code] >> >> >> When I copy contents from C:\IronPython to C:\temp >> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this >> self.fromdirLen = len(fromdir) + 1 >> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen >> = len(fromdir) i get contents copied to C:\ (actually to parent dir) > > Instead of actually doing os.mkdir and cpfile, use a print statement to > output the involved variables, and try with and without +1. You'll see > yourself what happens. > > --Gabriel Genellina > well I have tried with print but can't figure out I got this when I have removed + 1 >>> C = CpallVisitor('C:\\New', 'c:\\temp') >>> C.run(startdir='C:\\New') c:\temp\ filepath: C:\New\AUTOEXEC.BAT Topath: \AUTOEXEC.BAT filepath: C:\New\boot.ini Topath: \boot.ini filepath: C:\New\CONFIG.SYS Topath: \CONFIG.SYS but needs to be this >>> C = CpallVisitor('C:\\New', 'c:\\temp') >>> C.run(startdir='C:\\New') c:\temp\ filepath: C:\New\AUTOEXEC.BAT Topath: c:\temp\AUTOEXEC.BAT filepath: C:\New\boot.ini Topath: c:\temp\boot.ini filepath: C:\New\CONFIG.SYS Topath: c:\temp\CONFIG.SYS In python shell I got same thing, no matter fromdirLen is len(fromdir) + 1 or len(fromdir) >>> fromdir = 'C:\\New' >>> fromdirLen = len(fromdir) >>> todir = 'C:\\temp' >>> topath = os.path.join(todir, fromdir[fromdirLen:]) >>> topath 'C:\\temp\\' >>> fromdirLen = len(fromdir)+1 >>> topath = os.path.join(todir, fromdir[fromdirLen:]) >>> topath 'C:\\temp\\' >>> fromdir[fromdirLen:] '' >>> fromdirLen = len(fromdir) >>> fromdir[fromdirLen:] '' >>> fromdir 'C:\\New' Please help From gregpinero at gmail.com Thu Feb 1 17:33:50 2007 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 1 Feb 2007 17:33:50 -0500 Subject: Odd import behavior Message-ID: <312cfe2b0702011433t17e7e3e0nbcd0a210980dd022@mail.gmail.com> I didn't realize Python behaved like this. Is there an FAQ I can read on this? FILE module1.py: VAR1='HI' FILE MAIN.py: from module1 import * import module1 print VAR1 print module1.VAR1 VAR1='bye' print VAR1 print module1.VAR1 And the results are: >>> HI HI bye HI It seems to use module1.VAR1 for VAR1 until I assign something to VAR1 in which case they become seperate. -Greg From sturlamolden at yahoo.no Thu Feb 8 14:11:09 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 8 Feb 2007 11:11:09 -0800 Subject: Does the world need another v0.1 python compiler? In-Reply-To: <1170957733.673152.119430@j27g2000cwj.googlegroups.com> References: <1170918215.074099.262930@p10g2000cwp.googlegroups.com> <1170954814.417840.64810@l53g2000cwa.googlegroups.com> <1170957733.673152.119430@j27g2000cwj.googlegroups.com> Message-ID: <1170961869.741989.76960@p10g2000cwp.googlegroups.com> On Feb 8, 7:02 pm, bearophileH... at lycos.com wrote: > At the moment I think this approach can't improve much the speed of > Python programs compared to what Psyco is already able to do. Pyrex generates code that competes with hand-written C. It is as close to statically typed Python as it gets. http://www.scipy.org/PerformancePython From skpeterson at nospam.please.ucdavis.edu Fri Feb 16 21:08:04 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 16 Feb 2007 18:08:04 -0800 Subject: why I don't like range/xrange References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <45d61e34$0$29759$426a74cc@news.free.fr> Message-ID: Roel Schroeven on Sat, 17 Feb 2007 01:31:13 GMT didst step forth and proclaim thus: ... > So, the point is that in C you can influence the loop's behavior by > modifying the loop variable, while you cannot do that in Python (at > least not in a for-loop). What's wrong with... for i in range(10): if condition: break ...? -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From timr at probo.com Wed Feb 28 02:40:37 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 28 Feb 2007 07:40:37 GMT Subject: [OT] python notation in new NVIDIA architecture References: Message-ID: "Daniel Nogradi" wrote: >Something funny: > >The new programming model of NVIDIA GPU's is called CUDA and I've >noticed that they use the same __special__ notation for certain things >as does python. For instance their modified C language has identifiers >such as __device__, __global__, __shared__, etc. Is it a coincidence? >Probably it is. :) Well, identifiers starting with an underline are reserved for implementation use in ISO standard C++, so the chicken and egg question is an interesting one.. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From S.Mientki-nospam at mailbox.kun.nl Sun Feb 4 15:32:29 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 04 Feb 2007 21:32:29 +0100 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> <87tzy2utjl.fsf@smsnet.pl> <6eb8$45c5b41a$d443bb3a$2475@news.speedlinq.nl> Message-ID: <4457f$45c642c8$d443bb3a$1456@news.speedlinq.nl> > Just a note, If you run the module from different location, it may not > always work. > > The '..' is relative to the location you are running the module from, > the current directory, and not relative to the location of the module is > at. thanks for the tip Ron, I didn't realized ".." was literal ;-) so I've changed my application, so it inserts the absolute path. cheers, Stef > From Robert.Katic at gmail.com Wed Feb 14 19:10:59 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 14 Feb 2007 16:10:59 -0800 Subject: output to console and to multiple files In-Reply-To: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> Message-ID: <1171498259.757320.127100@q2g2000cwa.googlegroups.com> like this? class Writers (object): def __init__(self, *writers): self.writers = writers def write(self, string): for w in self.writers: w.write(string) def flush(self): for w in self.writers: w.flush(): import sys logfile = open('log.txt', 'w') sys.stdout = Writers(aya.stdout, file('log.out', 'w'), logfile) sys.stderr = Writers(aya.stdout, file('log.err', 'w'), logfile) From gigs at hi.t-com.hr Wed Feb 21 09:50:57 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 21 Feb 2007 15:50:57 +0100 Subject: Tkinter checkbuttons and variables Message-ID: from Tkinter import * states = [] def onpress(i): states[i] = not states[i] root = Tk() for i in range(10): chk = Checkbutton(root, text= str(i), command=lambda i=i: onpress(i)) chk.pack(side=LEFT) states.append(0) root.mainloop() print states after exiting i get everything like it suppose to but when i put command like this: command=lambda: onpress(i) i got only last checkbutton check. Why i have to pass this default argument? btw i have python 2.5 thx From rschroev_nospam_ml at fastmail.fm Wed Feb 7 05:52:39 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 07 Feb 2007 10:52:39 GMT Subject: division by 7 efficiently ??? In-Reply-To: <1170806724.447542.206120@m58g2000cwm.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> <1170775779.707583.131420@k78g2000cwa.googlegroups.com> <1170806044.201254.289080@l53g2000cwa.googlegroups.com> <1170806724.447542.206120@m58g2000cwm.googlegroups.com> Message-ID: garrickp at gmail.com schreef: > On Feb 6, 4:54 pm, "John Machin" wrote: >> Recursive? Bzzzt! >> Might it not be better to halve the interval at each iteration instead >> of calling a random number function? mid = (lo + hi) >> 1 looks >> permitted and cheap to me. Also you don't run the risk of it taking a >> very high number of iterations to get a result. > > I had considered this, but to halve, you need to divide by 2. Using > random, while potentially increasing the number of iterations, removes > the dependency of language tricks and division. It's possible to use Fibonacci numbers instead of halving each time; that requires only addition and subtraction. Unfortunately I forgot exactly how that works, and I don't have the time to look it up or to try to reproduce it now. Maybe later. AFAIK that method is not commonly used since binary computers are very good at dividing numbers by two, but it would be a good method on ternary or decimal computers. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From michele.simionato at gmail.com Tue Feb 27 09:30:43 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Feb 2007 06:30:43 -0800 Subject: Is there a technic to avoid this bug In-Reply-To: <54inn6F2115doU1@mid.uni-berlin.de> References: <54inn6F2115doU1@mid.uni-berlin.de> Message-ID: <1172586643.865731.78020@m58g2000cwm.googlegroups.com> On Feb 27, 1:49 pm, "Diez B. Roggisch" wrote: > However, it might be that either pychecker or pylint will give you a warning > for such statements. Yep, pychecker gives a warning "Statement appears to have no effect" Michele Simionato From rdm at rcblue.com Sat Feb 3 17:48:06 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 03 Feb 2007 14:48:06 -0800 Subject: Definitions of editor and IDE? Message-ID: <20070203224824.0CC7C1E400A@bag.python.org> An HTML attachment was scrubbed... URL: From ask at me Tue Feb 20 22:31:32 2007 From: ask at me (alf) Date: Tue, 20 Feb 2007 21:31:32 -0600 Subject: converting u'11\xa022' to '11\xa022' In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > u'11\xa022'.encode('charmap') thx a lot. one more question, once a unicode object is created e.g. u=unicode('hello', 'iso-8859-1') is there any way to find: 1-original encoding of u 2-list of supported encodings? A. From S.Mientki-nospam at mailbox.kun.nl Mon Feb 12 14:44:31 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 12 Feb 2007 20:44:31 +0100 Subject: Newbie Question In-Reply-To: <53bqoaF1rlgkqU1@mid.individual.net> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> <53bqoaF1rlgkqU1@mid.individual.net> Message-ID: <342d7$45d0c389$d443bb3a$9252@news.speedlinq.nl> Bjoern Schliessmann wrote: > Stef Mientki wrote: > >> - in Delphi the GUI design itself is done in a graphical >> environment, making it much easier and faster > > RAD possible with Python, too. > >> - auto-scaling of components on a form is very easy (so if the >> user changes form size ..) > > Just to name one library, wxPython can do this easily. > >> - even making everything on a form movable by the >> end-user is just 1 mouse-click >> - using the designers style, or the user style is just 1 click >> - very good feedback, so creating interactive graphs is very easy, >> cross-hair, slopes, region of interest etc. > > Those look like parts of the first point. Designtime and runtime feedback are not the same thing. > >> - a very huge collection of controls is standard available > > Just to name one, wxPython ... > >> [...] >> but to be honest ... >> ... I never even tried to write a GUI in Python, ... > > You should. There are several widely used libraries available > (Tkinter, wxPython, pyQt, pyGTK, ...), chances are that you like at > least one of them if you try. Oh I forgot that, ... ... in Delphi you don't have to choose ;-) But as I said before, I'll take a look in the future, thanks, cheers, Stef Mientki From arkanes at gmail.com Thu Feb 1 10:12:22 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 1 Feb 2007 09:12:22 -0600 Subject: SWIG overhead In-Reply-To: <52ednjF1npm6bU1@mid.uni-berlin.de> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> <1170328902.611668.271550@k78g2000cwa.googlegroups.com> <52e2bsF1nlgutU1@mid.uni-berlin.de> <1170340876.890010.184840@a75g2000cwd.googlegroups.com> <52ednjF1npm6bU1@mid.uni-berlin.de> Message-ID: <4866bea60702010712p431be5b5g1c87ce595d301536@mail.gmail.com> On 2/1/07, Diez B. Roggisch wrote: > Bart Ogryczak wrote: > > > On Feb 1, 12:48 pm, "Diez B. Roggisch" wrote: > >> > Yeah, found that one googling around. But I haven?t fund anything more > >> > up to date. I imagine, that the performance of all of these wrappers > >> > has been improved since then. But the performance of Python/C API > >> > would too? > >> > Anyways, it?s not about exact number, it?s more about taking decision > >> > if doing rewrite is worth it?s time. > >> > >> The wrappers essentially create the boilerplate-code that invokes the > >> Python C-API. So whatever improvements the latter has been developed, the > >> wrappers will benefit from it. > > > > Without doubt it?s true in case of SWIG, but if I understand > > Python.Boost documentation correctly, it does *not* use Python/C API. > > It has to. In the end, marshalling data between e.g. python datastructures > and C++ is done that way. > As I understand it, part of the Boost.Python internals is a C++ wrapper over the Python C api, and there's no separate code generation phase because it uses template magic to generate the wrappers. So while obviously the C API is used at some level, it's not visible to the wrapper author. > >> I doubt that there are major performance penalties associated with any of > >> them. > > > > Take a look at pages 23 and 24 of http://people.web.psi.ch/geus/talks/ > > europython2004_geus.pdf > > Ok, I see. I really wonder what SWIG does. > SWIG generates a low-level C module, and then a Python one on top of it. It allows for quite some versatility in wrapping (because you can have (almost) arbitrary Python code generated). Most of the other tools generate a .pyd which you import directly. > > Well, SWIG is easy to use. But I?ve gotta make hundreds of millions of > > calls, which do tasks as simple, as getting one int from an array and > > returning it. With functions that simple SWIG?s overhead seems to be a > > problem. > > Still I think you should first use wrappers for ease of use. Then when you > hit a performance bottleneck, it might be worth wrapping that class > manually. However, it _might_ of course be that this isn't integrating too > seamless with the wrapped classes, but I can't say anything about that > really. > Personally, I'd favor *correctness* first, then ease of use, and then speed. > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From gregturn at mindspring.com Tue Feb 20 15:38:00 2007 From: gregturn at mindspring.com (Goldfish) Date: 20 Feb 2007 12:38:00 -0800 Subject: How to do a Decorator Here? In-Reply-To: References: Message-ID: <1172003880.480416.252460@v45g2000cwv.googlegroups.com> On Feb 20, 8:20 pm, "Gregory Pi?ero" wrote: > Need some decorator help. > > I have a class. And I want to add behavior to one of this class's > methods to be run before the class runs the actual method. Is this > what decorators are for? > > So the class I want to work with is string.Template > > Let's say I have this: > from string import Template > a=Template("$var1 is a test") > > def preprocess(var1): > #Real code here will be more complicated, just an example > var1=var1.upper() > > a.substitute(var1="greg") > > So how can I have preprocess run before substitute is run? I want the > user to be able to call a.substitute and have preprocess run > automatically. > > Or is this not what decorators do? I'm trying to avoid subclassing if I can. > > Thanks in advance for the help. > > -Greg That sounds like aspect oriented programming. Spring Python (http:// springpython.python-hosting.com) offers a way to wrap objects with method interceptors. Method interceptors give you full control before and after method calls. Sometimes decorators can be used to do that as well, but they have constraints in where they can be used. I found them too inflexible for my needs, so I built an AOP solution. Greg From d.lidell at gmail.com Sat Feb 10 16:32:35 2007 From: d.lidell at gmail.com (d.lidell at gmail.com) Date: 10 Feb 2007 13:32:35 -0800 Subject: wxPython libraries never detected In-Reply-To: References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> Message-ID: <1171143155.537545.9530@j27g2000cwj.googlegroups.com> On Feb 10, 1:07 pm, hg wrote: > By default, you need to have wx installed in the python site-package path / > under Mandriva, I have wx 2.8 installed > here: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-ansi/ > > hg Ah, now I see. But I have a new problem: "ls /usr/lib/python2.4/site-packages | grep wx-2.8" returns "wx-2.8- gtk2-unicode" I copied wx-2.8-gtk2-unicode to /usr/lib/python2.5/site-packages/, which I assume the programs I am attempting to compile and run are using by default, but they still do not find the libraries. How can I tell where the programs are searching for the libraries? Thanks. From paddy3118 at netscape.net Sat Feb 3 00:37:11 2007 From: paddy3118 at netscape.net (Paddy) Date: 2 Feb 2007 21:37:11 -0800 Subject: main In-Reply-To: References: Message-ID: <1170481031.861396.248680@j27g2000cwj.googlegroups.com> On Feb 3, 4:45 am, fatwallet... at yahoo.com wrote: > is the main function in python is exact compare to Java main method? > > all execution start in main which may takes arguments? > Hi Fatwallet, May I have some of your money? Oh, sorry, the main function... The main function is *not* like that of Java, if Java is ike C in that execution starts in main(). In Python, you can create a function called main and it behaves just like any other function. Stick that function in a file and the python interpreter will create a function object out of it, assigned to the name main. Now, while directly interpreting a python file, the interpreter sets the global name __name__ to the value '__main__' If the file is being interpreted due to it being referenced via an import statement, then __name__ is set to the name of the module being imported. You can therefore use the value of the __name__ variable to get a file to do different things when imported versus when directly run. Some people arrange for a function called main to be called when directly interpreted; other don't. Its a convention only. Others use the trick to call test functions when directly executed, when the file is normally imported as a module. > and what is > __name__ > __main__ > > use for in terms of Java? > With respect, (hehe), maybe you need to indicate that you've searched the Python documentation on __name__ and __main__? (Hah! I did that without saying RTFM. - Oh pooh! Fiddlesticks). - Paddy. From adamgarstang at googlemail.com Mon Feb 26 17:43:19 2007 From: adamgarstang at googlemail.com (Adam) Date: 26 Feb 2007 14:43:19 -0800 Subject: Walk thru each subdirectory from a top directory In-Reply-To: <1172525300.450438.57080@8g2000cwh.googlegroups.com> References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> Message-ID: <1172529799.827628.321760@p10g2000cwp.googlegroups.com> On Feb 26, 9:28 pm, silverburgh.me... at gmail.com wrote: > i am trying to use python to walk thru each subdirectory from a top > directory. Here is my script: > > savedPagesDirectory = "/home/meryl/saved_pages/data" > > dir=open(savedPagesDirectory, 'r') > > for file in dir: > if (isdir(file)): > # get the full path of the file > fileName = savedPagesDirectory + file + 'index.html' > print fileName > > $ ./scripts/regressionTest.py > Traceback (most recent call last): > File "./scripts/regressionTest.py", line 12, in ? > dir=open(savedPagesDirectory, 'r') > IOError: [Errno 21] Is a directory > > But I get the above error: > > Can you please tell me what did I do wrong? > > Thank you. >From Alan Gaulds Tut. >>> for t in os.walk('Root'): ... print t ... ('Root', ['D1', 'D2', 'D3'], ['FA.txt', 'FB.txt']) ('Root/D1', ['D1-1'], ['FC.txt']) ('Root/D1/D1-1', [], ['FF.txt']) ('Root/D2', [], ['FD.txt']) ('Root/D3', ['D3-1'], ['FE.txt']) ('Root/D3/D3-1', [], ['target.txt']) >>> This bit below is from one of my first programs as I'm currently learning. It is designed to go form the root down and return the full paths of everything it finds into a list. (I then check the reults for files paths that exceed a certain length - but you don't need to know that.) def findallfiles(self, base): self.results = [] for root,dirs,files in os.walk(base): os.chdir(root) self.scan = glob.glob("*") for r in self.scan: if root[-1] == "\\": self.results.append(root + r) else: self.results.append(root + "\\" + r) return self.results From thinker at branda.to Mon Feb 26 13:48:47 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 02:48:47 +0800 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: <45E32B8F.9000700@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 zefciu wrote: > Thinker wrote: > >> Since PyArg_ParseTuple() is supposed to parse arguments, I >> recommand you to use PyTuple_GetItem() or PyTuple_GET_ITEM(). > > Ok. Now I do it this way: > > c_real = PyFloat_AsDouble(PyTuple_GetItem(coord,0)); c_imag = > PyFloat_AsDouble(PyTuple_GetItem(coord,1)); > > And it worked... once. The problem is really funny - in the > interactive the function fails every second time. > >>>> mandelpixel((1.5, 1.5), 9, 2.2) > args parsed coord parsed ii3 >>>> mandelpixel((1.5, 1.5), 9, 2.2) > TypeError: bad argument type for built-in operation I guess it is caused by ill handling reference count of coord. You should call Py_INCREF() to get a reference since it is borrowed from PyArg_ParseTuple(). You can find more information at http://docs.python.org/ext/refcounts.html - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4yuP1LDUVnWfY8gRAqOmAJ0SaIwpnRk/GZYm2Z5nnC7xH7EYKwCgjz8o 0Z/S7i5PULQMeAFI7U/Cy5I= =4C3l -----END PGP SIGNATURE----- From deets at nospam.web.de Fri Feb 2 17:52:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 02 Feb 2007 23:52:25 +0100 Subject: Python does not play well with others In-Reply-To: <7xirek9pdt.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> Message-ID: <52htlaF1mrd9iU1@mid.uni-berlin.de> > I do think the core should have more stuff than it does, so that its > functionality can be on a par with competing language distros like > J2SE and PHP. Both of those distros include database connectvity > modules and web frameworks. This is simply not true. J2SE doesn't include a web-framework. J2EE does, but it's a separate multi-megabyte-download. PHP _is_ a web centered language, so to say it "includes" a webframework sounds odd to me. And _both_ of them don't contain DB connectivity modules! J2SE has JDBC - which is just a bunch of interfaces. You need to download each and every driver. Python has DB API, and because it isn't statically typed, you just download a compliant driver/implementation. And PHP - well, it hasn't even modules at all. Yes, there are DB connectors for the important DBs. But for example on debian, you don't get ORACLE, as they can't ship the needed libs. So you end up compiling it yourself. To conclude: given that easy_install stands up to it's promise IMHO, I'm pretty happy with the batteries included. Diez From duncanm255 at hotmail.com Thu Feb 1 14:26:08 2007 From: duncanm255 at hotmail.com (D) Date: 1 Feb 2007 11:26:08 -0800 Subject: Tkinter Scrolling In-Reply-To: <2007020112161316807-bob@passcalnmtedu> References: <1170333328.141317.275130@q2g2000cwa.googlegroups.com> <2007020112161316807-bob@passcalnmtedu> Message-ID: <1170357968.405171.14410@h3g2000cwc.googlegroups.com> Bob Greschke wrote: > On 2007-02-01 05:35:30 -0700, "D" said: > > > I'm sure this is a simple question to the Tkinter experts - I have a > > very basic Tkinter application that consists of 1 master window and > > buttons within that window. My problem is that, I need to be able to > > scroll (up and down) when I get to the point that the buttons go off > > the screen. What's the easiest way to do this? Thanks in advance. > > The super-easiest way is to make the "background" a Text() widget, add > its scrollbars, then add the buttons and whatever else to it. Of > course you are then limited to the 'typewriter layout' of widget > placement. The typical way to do it is to make a scrolling canvas and > pack the buttons and other stuff into an empty Frame() and then pack > the frame on to the canvas, which I haven't had to do yet. > > Bob Thanks, Bob - have you seen any examples of the latter approach (using a canvas and frame)? Sounds rather confusing, but it definitely seems like the approach I need to take. Thanks again. From openopt at ukr.net Mon Feb 19 02:56:15 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 18 Feb 2007 23:56:15 -0800 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? In-Reply-To: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> References: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> Message-ID: <1171871775.848808.102080@q2g2000cwa.googlegroups.com> Ok, thx But can I somehow determing how many outputs does caller func require? for example: MATLAB: function [objFunVal firstDerive secondDerive] = simpleObjFun(x) objFunVal = x^3; if nargout>1 firstDerive = 3*x^2; end if nargout>2 secondDerive = 6*x; end So if caller wants only [objFunVal firstDerive] = simpleObjFun(15) than 2nd derivatives don't must to be calculated with wasting cputime. Is something like that in Python? From gheorghe.postelnicu at gmail.com Wed Feb 21 10:55:50 2007 From: gheorghe.postelnicu at gmail.com (Gheorghe Postelnicu) Date: Wed, 21 Feb 2007 10:55:50 -0500 Subject: Question about updating in a GUI Message-ID: <8094b1b60702210755o2deec241w7c724a06947e9882@mail.gmail.com> Hi, I have a GUI which does some visualization based on VTK and Tkinter. The problem I have is kinda complicated to describe, but here is a sketch of it: I have a basic Observer pattern in place for events (such as the change current 2D slice visualized) and it generally works well. However, I just tried inserting a new mode in my GUI, which triggers an update in the above interface. In general, modes react to these event changes by refreshing the data, so the code is really straightforward. However, for this specific mode, I need some persistent data. So I need to tell my Callback to keep the data and not refresh it, as is usually the case. I tried to set a flag that would be set during this operation (my application is not multi-threaded and I took a chance), but the updates in the renderer in VTK are not synchronous, so the flag gets cleared before all the updates occured, so my data still gets flushed away. Any suggestions on how I should be approaching this? Thanks, -- Gheorghe Postelnicu, PhD MGH, Harvard Medical School From kristnjov at nospam.com Fri Feb 9 02:49:17 2007 From: kristnjov at nospam.com (Deniz Dogan) Date: Fri, 09 Feb 2007 08:49:17 +0100 Subject: UNIX shell in Python? Message-ID: Hello. I was thinking about writing a UNIX shell program using Python. Has anyone got any experience on this? Is it even possible? I have programmed a simple shell in C before and I came to think about how perfect Python would be for parsing user input. Regards, Deniz Dogan From adamgarstang at googlemail.com Wed Feb 28 15:53:52 2007 From: adamgarstang at googlemail.com (Adam) Date: 28 Feb 2007 12:53:52 -0800 Subject: convert many excel files to pdf in batch In-Reply-To: References: Message-ID: <1172696032.167875.154800@s48g2000cws.googlegroups.com> 1. Get PDFCreator 2. Install 3. Set as default printer 4. Have all excel files in same folder 5. Select all excel files 6. Right click 7. Select Print 8. Save Each PDF to a location 9. ??? 10. Profit!!!! Never done it with Adobe Writer. I'm a cheapskate. Regards, Adam From http Thu Feb 8 03:51:19 2007 From: http (Paul Rubin) Date: 08 Feb 2007 00:51:19 -0800 Subject: Referencing vars, methods and classes by name References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> <7xbqk52gt8.fsf@ruckus.brouhaha.com> Message-ID: <7xveid6ni0.fsf@ruckus.brouhaha.com> "Gabriel Genellina" writes: > > obj.getattr(a)() > > but even that is a bit ugly, depending. > Surely you meant to say getattr(obj, a)() Yeah, darn. Counterintuitive. I keep making that error in my own code too. Maybe I should put in an RFE. From arnodel at googlemail.com Sun Feb 25 11:14:31 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 25 Feb 2007 08:14:31 -0800 Subject: finding out the precision of floats In-Reply-To: References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> Message-ID: <1172420071.645851.259270@a75g2000cwd.googlegroups.com> On Feb 25, 3:59 pm, "Jerry Hill" wrote: > On 25 Feb 2007 06:11:02 -0800, Arnaud Delobelle wrote: > > > Moreover the reason I got interested in this is because I am creating > > a Dec class (decimal numbers) > > Are you familiar with Python's Decimal library?http://docs.python.org/lib/module-decimal.html > Read on my post for a few more lines and you'll know that the answer is yes :) -- Arnaud From luv.urs at gmail.com Wed Feb 28 12:38:01 2007 From: luv.urs at gmail.com (luvsat) Date: 28 Feb 2007 09:38:01 -0800 Subject: Writing an interpreter for language similar to python!! Message-ID: <1172684281.057538.224370@h3g2000cwc.googlegroups.com> Hello all, I am new to python and working on a project that involves designing a new language. The grammar of the language is very much inspired from python as in is supports nearly all the statements and expressions that are supported by python. Since my project is in initial stage, so I think it would be appropriate if I clarify the following questions: 1. Would it make sense if I parse the whole program from scratch and then construct the valid python strings back so that they can be executed using ''exec'' and ''eval'' commands? 2. Recently, I came across PLY (Python-Lex-Yacc) module that can be used to implement interpreters. It seems quite friendly to work with. Is there any implementation of python interpreter using ply? Any such reference would be extermely helpful for me to continue. Any kind of suggestions/ comments would be highly appreciated. Thanks, Luvish Satija From bruno.desthuilliers at gmail.com Mon Feb 12 07:15:41 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 12 Feb 2007 04:15:41 -0800 Subject: Newbie Question In-Reply-To: <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> Message-ID: <1171282541.900959.261020@a34g2000cwb.googlegroups.com> On 9 f?v, 14:06, Stef Mientki wrote: > >> will explain the rest > > > Delphi is a (dying) proprietary, MS-Windows-only[1] software relying > > on a low-level language. > > Well it may be dying, > but for the moment it beats Python with a factor of 10, > when it comes to user (the majority of PC users) friendly GUI ;-) Would you mind explaining yourself and backing your above assertion ? Like, ie, on which points does Delphi "beats" Python wrt/ GUIs, what special magic would make so that GUIs designed with Delphi would be more "user-friendly", and where does this "factor 10" comes from ? Good luck... From sjmachin at lexicon.net Fri Feb 2 10:49:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 Feb 2007 07:49:33 -0800 Subject: division by 7 efficiently ??? In-Reply-To: References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> Message-ID: <1170431373.045156.156100@v33g2000cwv.googlegroups.com> On Feb 3, 2:31 am, "Jesse Chounard" wrote: > On 31 Jan 2007 19:13:14 -0800, krypto.wiz... at gmail.com > > wrote: > > Its not an homework. I appeared for EA sports interview last month. I > > was asked this question and I got it wrong. I have already fidlled > > around with the answer but I don't know the correct reasoning behind > > it. > > I think this works: You think wrongly. Inspection reveals that it is obviously incorrect for N == 0. Trivial testing reveals that it is wrong for about 6 out of every 7 cases. > > >>> def div7 (N): > > ... return ((N * 9362) >> 16) + 1 > ...>>> div7(7) > 1 > >>> div7(14) > 2 > >>> div7(700) > 100 > >>> div7(70000) > > 10000 > > The coolest part about that (whether it works or not) is that it's my > first Python program. I wrote it in C first and had to figure out how > to convert it. :) Try testing algorithms with a pencil on the back of an envelope first. The uncoolest part about that is that your test data is horribly deficient: >>> for N in xrange(0, 23): ... a = ((N * 9362) >> 16) + 1 ... e = N // 7 ... print N, a, e, a == e ... 0 1 0 False 1 1 0 False 2 1 0 False 3 1 0 False 4 1 0 False 5 1 0 False 6 1 0 False 7 1 1 True 8 2 1 False 9 2 1 False 10 2 1 False 11 2 1 False 12 2 1 False 13 2 1 False 14 2 2 True 15 3 2 False 16 3 2 False 17 3 2 False 18 3 2 False 19 3 2 False 20 3 2 False 21 3 3 True 22 4 3 False HTH, John From eurleif at ecritters.biz Thu Feb 8 16:59:02 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 08 Feb 2007 16:59:02 -0500 Subject: def obj() In-Reply-To: References: Message-ID: <45cb9d24$0$6842$4d3efbfe@news.sover.net> Gert Cuykens wrote: > def obj(): > return {'data':'hello', > 'add':add(v)} > > def add(v): > data=data+v > > if __name__ == '__main__': > test=obj() > test.add('world') > print test.data > > I don't know why but i have one of does none class c programing style > moods again. I was wondering if the following was possible without > using a class ? def obj(): result = {'data': 'hello'} result['add'] = adder(result) return result def adder(obj): def add(value): obj['data'] += value return add if __name__ == '__main__': test = obj() test['add']('world') print test['data'] From gagsl-py2 at yahoo.com.ar Wed Feb 28 22:04:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Mar 2007 00:04:50 -0300 Subject: pyscripter References: Message-ID: En Wed, 28 Feb 2007 11:28:49 -0300, Gigs_ escribi?: > im using pyscripter ide > > it is all alright till the next def > > class Checkbar(Frame): > def __init__(self, parent=None, picks=[], side=LEFT, anchor=W): > Frame.__init__(self, parent) > self.vars = [] > for pick in picks: > var = IntVar() > chk = Checkbutton(self, text=pick, variable=var) > chk.pack(side=side, anchor=anchor, expand=YES) > self.vars.append(var) > # it is all alright till here, but if im going to write next > # class method it wont go with tab for 4 fields > # it goes here all the time (8 fields) > if i remove for statement it all work fine I don't use pyscripter myself, but how could it know that you aren't going to write more code for the __init__ method? Reading the manual might be helpful... Try backspace, shift-tab, an empty line... -- Gabriel Genellina From steveo at syslang.net Thu Feb 1 11:52:37 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 1 Feb 2007 11:52:37 -0500 (EST) Subject: Question about a single underscore. Message-ID: I saw this and tried to use it: ------------------><8------------------- const.py------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__[name]=value import sys sys.modules[__name__]=_const() ------------------><8------------------- const.py------------- Then when I go to try to use it I'm supposed to say: const.pi = 3.14159 const.e = 2.7178 Two questions: 1. Why do I not have to say _const.pi = 3.14159 _const.e = 2.7178 and is this in the tutorial? 2. Can I make this behave in such a way that I can create my constants with a classname that is different for different uses? e.g., irrational_const.pi = 3.14159 irrational_const.e = 2.7178 even_const.first = 2 even_const.firstPlus = 4 TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From http Tue Feb 27 15:22:13 2007 From: http (Paul Rubin) Date: 27 Feb 2007 12:22:13 -0800 Subject: difference between string and list References: Message-ID: <7x4pp773m2.fsf@ruckus.brouhaha.com> "lincoln rutledge" writes: > strings have methods like string.count("f") returns 1. What methods do > lists have? Is it a similar class to string? Strings and lists are similar but not the same. dir(string) will show you the methods available for strings. dir(list) will show you the methods available for lists. See also the "built-in types" section of the Python Library Reference Manual, the section on sequence types. From usenet1 at ingfamily.net Mon Feb 12 13:44:36 2007 From: usenet1 at ingfamily.net (usenet1 at ingfamily.net) Date: 12 Feb 2007 10:44:36 -0800 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded Message-ID: <1171305876.030471.59470@s48g2000cws.googlegroups.com> I'm a newbie with hopefully an easy question. I'm trying to write some "C" code that will run a python script that can in turn call some "C" functions. However I'm having a problem getting started because although I can run a script from the python ide that imports ctypes, when I execute that 'import ctypes' code from the "C" code I get the following error: 'import site' failed; use -v for traceback Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\ctypes\__init__.py", line 6, in import os as _os, sys as _sys File "C:\Python25\lib\os.py", line 690, in import copy_reg as _copy_reg File "C:\Python25\lib\copy_reg.py", line 7, in from types import ClassType as _ClassType File "C:\Python25\lib\types.py", line 93, in import _types SystemError: _PyImport_FixupExtension: module _types not loaded [6569 refs] For reference here is my code: // pytest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "python.h" int _tmain(int argc, _TCHAR* argv[]) { Py_Initialize(); PyRun_SimpleString("import ctypes"); Py_Finalize(); return 0; } Steve From libintr at gmail.com Tue Feb 6 13:38:54 2007 From: libintr at gmail.com (lee) Date: 6 Feb 2007 10:38:54 -0800 Subject: electronics and python Message-ID: <1170787134.923982.197760@v33g2000cwv.googlegroups.com> Hi guys.....Is there any software written using python for electronics.....i mean any simulation software or something?? From broek at cc.umanitoba.ca Thu Feb 8 17:31:23 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 08 Feb 2007 16:31:23 -0600 Subject: doctests for interactive functions In-Reply-To: References: Message-ID: <45CBA4BB.50604@cc.umanitoba.ca> Neil Cerutti said unto the world upon 02/08/2007 02:25 PM: > On 2007-02-08, Brian van den Broek wrote: >> All classes take an optional argument input_function that >> determines how the class instance gets its input. If this is >> not provided, it defaults to raw_input. doctest tests reassign >> it so that they can be run automatically. > > What I've done in these cases is create a file containing my test > input, and before running the doctests I remap sys.stdin to my > file of test data. Then you don't need test code cluttering up > your functions. > Hi Neil and all, Thanks for the suggestion, Neil. I will look into it. I am not worried about the test code cluttering up my module's source, as I am using doctest.testfile to run doctests defined in a separate file anyway. I am looking to produce illustrative examples for the user manual which also can serve as tests. I'll play around and see if remapping sys.stdin reduces the gap between the appearance of the doctest examples and of actual use cases as compared to my current approach. Thanks again, Brian vdB From frodo at theshire.org Tue Feb 13 08:15:07 2007 From: frodo at theshire.org (Cristiano Paris) Date: Tue, 13 Feb 2007 14:15:07 +0100 Subject: Lazy container Message-ID: <45D1B9DB.9090105@theshire.org> Hi everyone, I'm trying to write a Container which should mimic a list. Basically, the container pulls items on the fly from an unspecified source through a function and returns an instance of a given class over the pulled item. That is: class lazy(object): def __getitem__(self,index): return Foo(f(index)) lc = lazy() Here I see a problem: two consecutive accesses to lc for the same index would retrieve two different instances of Foo. In some scenarios this is not desirable since one wants to have all the accessors to share the same instance for the same index so as to reduce memory consumption. So, I thought to use an internal dictionary of all the Foo instances given away so far. Something like: class lazy(object): def __init__(self): self.cache = {} def __getitem__(self,index): if not self.cache.has_key(index): value = Foo(f(index)) # MISS self.cache[index] = value else: # HIT value = self.cache[index] return value This is acceptable as it reduces the number of instances living in the system at any given time. The problem with this implementation is that the cache never decreases in length as Foo instances are no longer referenced by the lc accessor since they're all referenced by the internal cache. There are scenarios in which f() retrieves items from a very huge source (i.e. a database) and threads sharing the lazing container and consuming Foo instances to use them for a very short time and then discardi them: after a while you'll eventually end up having a whole copy of the source in memory, which is unacceptable. One solution may be to use gc.get_referrers() to search the cache for unused instances every time we have a cache miss so as to see if we could discard some instance before inserting the new one in the cache. But this comes at a cost. May be someone has faced this problem before and came up with some obscure language feature to solve this elegantly :D Thanks for your replies. Cristiano From S.Mientki-nospam at mailbox.kun.nl Mon Feb 12 14:40:43 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 12 Feb 2007 20:40:43 +0100 Subject: favourite editor In-Reply-To: <1171307483.481407.167480@a75g2000cwd.googlegroups.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> <45D08DAB.6080908@websafe.com> <1171307483.481407.167480@a75g2000cwd.googlegroups.com> Message-ID: azrael wrote: > I expirienced some big craches. tra running some aplication vith using > Vpython. when you close the vpython window, pyscripter also crashes. > sometimes im writing some code and suddenly get about 300 error > messages without running anything. I like pyscripter, but sometimes it > drives me crazy did you read the help file: if you use a GUI platform (e.g. tknter, wxpython etc.). As the help file says under the topic "known issues" you should not run or debug such scripts internally. Instead use the Run, External Run command. and form the author of PyScripter jan-2007: I hope that such problems will be resolved when I release the remote debugging facility, which should happen quite soon. cheers, Stef Mientki From aisaac at american.edu Tue Feb 20 13:29:54 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 20 Feb 2007 18:29:54 GMT Subject: PLY for standard library Message-ID: Is PLY destined for the standard library? If not, what module providing substantially similar functionality is? Thank you, Alan Isaac From usable.thought at gmail.com Fri Feb 16 11:44:18 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 08:44:18 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> <1171642551.277929.233540@l53g2000cwa.googlegroups.com> Message-ID: <1171644258.015501.313630@l53g2000cwa.googlegroups.com> On Feb 16, 11:34 am, Steve Holden wrote: > Endless Story wrote: > > On Feb 16, 10:29 am, Tim Golden wrote: > >> I would ask if you had *any* other Python installation > >> -- say a cygwin one -- which might just be getting in the way? > > > It's a cygwin problem, guddammit. I was wondering if this might be the > > case - I should have mentioned in my initial post that I've got a > > whole Cygwin setup, including Python. > > > I know the conflict is the problem because just now I opened up a > > command shell in XP (not the Cywgin bash window), and instead of > > typing "python" and getting nothing, I tried "which python" - which > > when you think about it, shouldn't even work in a XP shell. But > > somehow Cygwin is mingling some of its capabilities with the XP shell, > > because "which python" actually gets an answer - "/usr/bin/python," > > which is Cygwin. > > > Now the question is how to fix this - I don't want to uninstall the > > Cygwin version. Instead I need some way of unknotting Cygwin's > > intrusion into what should be an XP-only shell, or else a way of > > giving priority when in that shell (and not the bash shell, which I > > also use) to the Python executable residing at C:\Python25. > > It sounds like you may have mistakenly added Cygwin binary directories > to your Windows path. This isn't normally necessary, since the Cygwin > shell makes all necessary path adjustments as it starts. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007 From usenet200702 at tobyinkster.co.uk Sat Feb 24 03:25:55 2007 From: usenet200702 at tobyinkster.co.uk (Toby A Inkster) Date: Sat, 24 Feb 2007 08:25:55 +0000 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> Message-ID: aleaxit wrote: > If anybody who has easy access to Microsoft's MSVC++.NET (and is willing > to try building GMP 4.2 with/for it), or a PPC Mac with XCode installed > (possibly with MacOSX 10.3...) I'm writing this message on a MacOS 10.3.9 box with Xcode 1.5 (gcc 3.3) installed. If you tell me how, I'd be happy to compile it for you. Contact me through the feedback form on the site below. -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From toffoli at uni.net Fri Feb 16 12:14:11 2007 From: toffoli at uni.net (Giovanni Toffoli) Date: Fri, 16 Feb 2007 18:14:11 +0100 Subject: sorting list of tuples by second (third...) tuple item Message-ID: <004501c751ed$e024de00$1710b7c2@DELLGIOVANNI> Hi, I'm not in the mailing list. By Googling, I stepped into this an old post: (Thu Feb 14 20:40:08 CET 2002) of Jeff Shannon: http://mail.python.org/pipermail/python-list/2002-February/128438.html <<< def SortOnItem(mylist, index): templist = [ (line[index], line) for line in mylist ] templist.sort() return [ line[1:] for line in templist ] What this does is build a separate list containing a tuple of the element that you want to sort on, and the entire line, sorts that list (by the first element, of course), and then strips that first element off .. >>> It seems to me that the tuples aren't sorted only by the first element but, I suppose, other elements are also used if needed to discriminate. In some cases I got some exceptions when an element of the tuple, other than the first, didn't admit comparison. In these cases I had to use an ad hoc comparison function. Regards, Giovanni Toffoli From bear at sonic.net Wed Feb 28 12:59:50 2007 From: bear at sonic.net (Ray Dillinger) Date: Wed, 28 Feb 2007 09:59:50 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> <45e33052$0$27235$742ec2ed@news.sonic.net> Message-ID: <45e5c246$0$27215$742ec2ed@news.sonic.net> > Actually, it just occurred to me that the company location was also in > the subject line of this thread ;-) D'oh! Should have looked at the verbose header before responding. I've got my newsreader set to display one title per line, and then didn't give it enough horizontal room to see your full title. Well, I'm not moving to LA, so I won't waste your time (and mine) applying. Best of luck! Bear From ophionman at gmail.com Mon Feb 26 14:12:14 2007 From: ophionman at gmail.com (raf) Date: 26 Feb 2007 11:12:14 -0800 Subject: Python object to xml biding Message-ID: <1172517133.999532.180400@m58g2000cwm.googlegroups.com> Hi there, I'm looking for a python to XSD/xml biding library to easy handling this very large protocol spec I need to tackle. I've searched google quite extensibly and I haven't found anything that properly fits the bill... I'm mostly interested at the xml -> python and python->xml marshalling/unmarshalling much like jaxb for java. Any ideas? From silovana.vjeverica at com.gmail Thu Feb 8 13:26:51 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Thu, 8 Feb 2007 19:26:51 +0100 Subject: Functions, parameters Message-ID: Hi, I'am still learning Python and while reading Django tutorial couldn't understand this part: class Poll(models.Model): question = models.CharField(maxlength=200) pub_date = models.DateTimeField('date published') # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Poll.objects.filter(question__startswith='What') This 'question__startswith' is the problem. What is the common idiom for this type od arguments, so I can Google it? I understand what this filter is suppose to do, but don't know how it is done (this separation of Poll atribute and startwith function). -- http://www.nacional.hr/articles/view/23894/23 From daftspaniel at gmail.com Mon Feb 5 07:51:30 2007 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 5 Feb 2007 04:51:30 -0800 Subject: comp.lang.python Podcast - URL Change Message-ID: <1170679890.213520.25600@l53g2000cwa.googlegroups.com> Unfortunately I have had to change domains. The feeds for the podcast are updated and available at: http://www.latedecember.co.uk/sites/pythonpod/ Thanks, Davy Mitchell http://www.latedecember.co.uk/sites/personal/davy/ From aisaac at american.edu Sun Feb 11 19:57:35 2007 From: aisaac at american.edu (Alan Isaac) Date: Mon, 12 Feb 2007 00:57:35 GMT Subject: randomly generate n of each of two types References: Message-ID: <3YOzh.1133$yg7.205@trnddc08> "Stargaming" wrote in message news:eqo184$2u7e$1 at ulysses.news.tiscali.de... > ... types *= n > ... shuffle(types) This again has the "costs" I referred to: creating a potentially large sequence, and shuffling it. (Additionally, shuffle cannot achieve many of the possible shuffles of a large list, but I doubt this is easily evaded.) So as far as I can tell, this is the same approach as the original (first) solution. Cheers, Alan Isaac From Eric.Gabrielson at gmail.com Mon Feb 5 17:55:21 2007 From: Eric.Gabrielson at gmail.com (Eric.Gabrielson at gmail.com) Date: 5 Feb 2007 14:55:21 -0800 Subject: Coordinate Grid Points Message-ID: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> Hello, I am very knew to python and am attempting to write a program in python that a friend of mine is having to write in java. I am doing this for fun and would like some help as to how i can generate random coordinate points (x,y) and compare them with user inputted coordinate points. For example how will I be able to access the separate values, the x from the x,y position. I think I understand everything except 1)the random coordinate points 2) the getting the users inputted x and y values in one line ("Please guess a coordinate point from (1,1) to (20,20): ") as opposed to ("Please enter an x value:" and "Please enter a y value") and finally 3) acessing the x value from the x,y coordinate function. the assignment description is located here http:// www.cs.washington.edu/education/courses/142/07wi/homework/ homework.html if you would like to see a more in depth discription of the game. Many Thanks, Eric From garrickp at gmail.com Wed Feb 21 18:01:07 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 21 Feb 2007 15:01:07 -0800 Subject: Creating a daemon process in Python In-Reply-To: References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> <1172095596.050555.225750@j27g2000cwj.googlegroups.com> Message-ID: <1172098867.342275.270140@t69g2000cwt.googlegroups.com> On Feb 21, 3:34 pm, Benjamin Niemann wrote: > That's not a daemon process (which are used to execute 'background services' > in UNIX environments). I had not tested this by running the script directly, and in writing a response, I found out that the entire interpreter closed when the main thread exited (killing the daemonic thread in the process). This is different behavior from running the script interactively, and thus my confusion. Thanks! ~Garrick From kousue at gmail.com Wed Feb 28 10:41:37 2007 From: kousue at gmail.com (Nick !) Date: Wed, 28 Feb 2007 10:41:37 -0500 Subject: Curses and resizing windows Message-ID: <98f5a8830702280741l1ab2d712l5816f908cc4fbf58@mail.gmail.com> > Chris Share wrote: > > I've been writing an application using curses, and have been trying to > > handle resizing the terminal, if running in xterm or similar. Increasing > > the window size is working perfectly, however shrinking it is not > > working at all. No matter how much I shrink the window, the size > > returned by getmaxyx() does not change. However as soon as I increase it > > again, it works fine. > > > I've tracked the problem down to the fact I have created a window > > derived from stdscr. A small script showing the effect is at the end of > > this post. > > odd (thanks for the example - I don't know if this is a problem in > ncurses or in the python interface to it, but will check/see). > > > Can anyone suggest how to solve this problem, that doesn't involve not > > making a derwin of stdscr? > > > I've been googling for hours, but found nothing to help. > > > Python version is 2.3.4 on debian testing. > > probably should report it as a bug (so it's not overlooked). > > -- > Thomas E. Dickey > http://invisible-island.net > ftp://invisible-island.net http://web.cs.mun.ca/~rod/ncurses/ncurses.html#xterm says "The ncurses library does not catch [the SIGWINCH aka resizing] signal, because it cannot in general know how you want the screen re-painted". First, is this really true? When I make my xterms smaller they clip what is displayed--is that a function of curses or the xterm? Second, if true, it explains /what/ is going on--stdscr, only--, but isn't really satisfactory; it doesn't solve the original poster's bug. #!/usr/bin/env python """ curses_resize.py -> run the program without hooking SIGWINCH curses_resize.py 1 -> run the program with hooking SIGWINCH """ import sys, curses, signal, time def sigwinch_handler(n, frame): curses.endwin() curses.initscr() def main(stdscr): """just repeatedly redraw a long string to reveal the window boundaries""" while 1: stdscr.insstr(0,0,"abcd"*40) time.sleep(1) if __name__=='__main__': if len(sys.argv)==2 and sys.argv[1]=="1": signal.signal(signal.SIGWINCH, sigwinch_handler) curses.wrapper(main) If you run this without sigwinch then the line never gets resized, but if you do then it works fine. What we can glean from this is that stdscr only reads off it's size upon initialization. This behaviour may seem a bit strange, but 1) it's legacy and 2) avoids breaking the semantics of windows (which don't change size on their own). The "curses.initscr()" part is kind of unhappy though. It modifies the stdscr variable without us explicitly assigning anything (but I can't think of any other way to do it, beyond making stdscr a global, and that feels worse) and will break if initscr() ever returns a new Window structure instead of just updating and returning the old one. Does anyone have any tips for how to structure this so that the screen can actually be assigned to? In conclusion, it's not a bug, it's a feature. Joy! The workaround is to write a sigwinch_handler that at least does `endwin(); initscr()`. Sorry for reviving an old thread, but it doesn't seem the issue was ever resolved (the thread doesn't go anywhere and there's no warning about this in the docs that I noticed). (please CC: me if anyone cares, I'm not on the list) -Nick Guenther From ayaz at dev.slash.null Sun Feb 11 02:05:45 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Sun, 11 Feb 2007 12:05:45 +0500 Subject: HTML Parsing References: <1171148863.807386.310960@h3g2000cwc.googlegroups.com> Message-ID: "mtuller" typed: > I have also tried Beautiful Soup, but had trouble understanding the > documentation As Gabriel has suggested, spend a little more time going through the documentation of BeautifulSoup. It is pretty easy to grasp. I'll give you an example: I want to extract the text between the following span tags in a large HTML source file. Linux Kernel Bluetooth CAPI Packet Remote Buffer Overflow Vulnerability >>> import re >>> from BeautifulSoup import BeautifulSoup >>> from urllib2 import urlopen >>> soup = BeautifulSoup(urlopen('http://www.someurl.tld/')) >>> title = soup.find(name='span', attrs={'class':'title'}, text=re.compile(r'^Linux \w+')) >>> title u'Linux Kernel Bluetooth CAPI Packet Remote Buffer Overflow Vulnerability' -- Ayaz Ahmed Khan A witty saying proves nothing, but saying something pointless gets people's attention. From bj_666 at gmx.net Sat Feb 17 01:57:52 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 17 Feb 2007 07:57:52 +0100 Subject: WHAT IS THIS? References: Message-ID: In , Captain wrote: > Just bought a new PC with Windows XP Media Edition. [?] I gather > Python is a programming language, but I am wondering why it was > installed on my PC, and is it safe to remove it? I have no intention of > learning the program. Thanks in advance If it came with the computer it's most probably not safe to remove it because chances are that it's used by some program or script that is pre-installed by the vendor of the machine. At least HP, Compaq and IBM/Lenovo are known to do this on some computers: http://www.python.org/doc/faq/installed/ http://effbot.org/pyfaq/installed-why-is-python-installed-on-my-machine.htm Ciao, Marc 'BlackJack' Rintsch From sturlamolden at yahoo.no Mon Feb 19 06:43:37 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 19 Feb 2007 03:43:37 -0800 Subject: Choices: scipy, matplot ... In-Reply-To: <1171881249.661739.269400@v45g2000cwv.googlegroups.com> References: <1171881249.661739.269400@v45g2000cwv.googlegroups.com> Message-ID: <1171885417.761205.191060@l53g2000cwa.googlegroups.com> On Feb 19, 11:34 am, "dug" wrote: > I would like to do some real time signal processing with a graphical > display and I would like your advice as to what I should use. I would > like to be able to view the results and to change parameters of some > signal processing in 'real time'. Data is coming quite slowly in every > 1-5 seconds and will consist of (x,y,t). > > I have been thinking about SciPy or matplot, but am not restricting > myself to these (or even Python). You will need: - Python 25 - NumPy - SciPy (possibly) - Matplotlib (for graphing) - PyGTK or wxPython (for the rest of the GUI) Finally you need something to make Python talk to your hardware. Pick one of the following, dependent on your need and skills: - ctypes - pyrex - inlined C with scipy.weave - autogenerated wrappers with swig - hand-written Python extension in C - hand-written Python extension in C++ (CXX or Boost.Python) From gatti at dsdata.it Thu Feb 8 03:49:38 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: 8 Feb 2007 00:49:38 -0800 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: <1170924578.362210.242280@a34g2000cwb.googlegroups.com> On Feb 8, 7:02 am, Dave Benjamin wrote: > Neil Cerutti wrote: > > There's been only one (or two?) languages in history that > > attempted to provide programmers with the ability to implement > > new infix operators, including defining precedence level and > > associativity (I can't think of the name right now). > > You're probably thinking of SML or Haskell. OCaml also allows you to > define new infix operators, but the associativities are fixed (and > determined by what punctuation you use). Also some flavours of Prolog, as descrived in the classic book by Clocksin & Mellish. Regarding the OP, I hope his need for an infix tilde operator is overestimated; there are plenty of infix operators that can be abused, and at least one of them should be unused and available for redefinition. Lorenzo Gatti From sickcodemonkey at gmail.com Tue Feb 27 20:56:15 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 27 Feb 2007 20:56:15 -0500 Subject: Special Characters In-Reply-To: <2adc542f0702271723m4e813d0ckf907227f76992a93@mail.gmail.com> References: <2adc542f0702271723m4e813d0ckf907227f76992a93@mail.gmail.com> Message-ID: <2adc542f0702271756u51907534x5bdbef7614eab08a@mail.gmail.com> Sorry guys. It has been a long day today. There is no issues when dealing with "#" in variables. I found out that when I was reading the file, there were additional blank spaces being appended to the value. To correct the issue, I just had to dp varName = msInfo[0].strip() finName = varName.strip() On 2/27/07, Sick Monkey wrote: > > I have a quick question about handling values with special characters. > > Lets say I have a file which contains: > ================================== > blah#blah > ================================== > Here is what I have for my code: > f6 = open(fileAttached) > msInfo = f6.readlines(); f6.close() > varName = msInfo[0] > .... > smtp.login(uname,varName) > ... > ================================== > I am trying to connect to a mailserver, and it keeps failing. My guess is > that the "#" sign messing up. Is there anyway to encode that character? > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Bulkan at gmail.com Sat Feb 17 08:44:07 2007 From: Bulkan at gmail.com (placid) Date: 17 Feb 2007 05:44:07 -0800 Subject: cmd all commands method? In-Reply-To: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> Message-ID: <1171719847.413759.167230@q2g2000cwa.googlegroups.com> placid wrote: > Hi all, > > if i want to treat every cmdloop prompt entry as a potential command > then i need to overwrite the default() method ? > > What i want to achieve is to be able to support global variable > creation for example; > > res = sum 1 2 > > this would create a variable res with the result of the method > do_sum() ? > > then would i be able to run; > > sum a 5 this should have been, sum res 5 > > this would return 8 or an error saying that res is not defined > > > Cheers From mail at microcorp.co.za Sat Feb 17 04:41:13 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 17 Feb 2007 11:41:13 +0200 Subject: Pep 3105: the end of print? References: <20070216144903.25807.996277675.divmod.quotient.23913@ohm> Message-ID: <026a01c7527c$bf1e3a00$03000080@hendrik> "Steve Holden" wrote: > Jean-Paul Calderone wrote: > > > > I think some people are confused that the language "Python 3.x" has "Python" > > in its name, since there is already a language with "Python" in its name, > > with which it is not compatible. > > > Right. Let's call Python 3.0 something different but related. How about > "snake oil"? ;-) I kind of like this idea - it means that the initiates can go on caravan tours of America, selling it as a panacea for all ills, IT related or not... A whole new industry. - Hendrik From vatsal.trivedi107 at gmail.com Sat Feb 17 11:09:12 2007 From: vatsal.trivedi107 at gmail.com (vatsal.trivedi107 at gmail.com) Date: 17 Feb 2007 08:09:12 -0800 Subject: download free computer books enjoy Message-ID: <1171728552.504456.270400@v45g2000cwv.googlegroups.com> Free Computer Education Ebooks,Tutorials and much more.... ASP, Business, C++, Careers, CISCO, e-books, Engineering, English, Filmmaking, Finance, Health, Leadership, Management, Marketing, Mathematics, Mobile, Oracle, Perl , Photography, PHP, Programming, VOIP........and much more visit http://ebooks2download.blogspot.com today From peter.mctaggart at gmail.com Tue Feb 13 05:45:40 2007 From: peter.mctaggart at gmail.com (peter) Date: 13 Feb 2007 02:45:40 -0800 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: <12t17gsjh6vgh94@corp.supernews.com> <12t1ch1n8hj9n69@corp.supernews.com> <12t2cgssrrbmf1a@corp.supernews.com> Message-ID: <1171363540.435556.312430@v33g2000cwv.googlegroups.com> On Feb 13, 7:44 pm, Jussi Salmela wrote: > Grant Edwards kirjoitti: > > > On 2007-02-12, Larry Bates wrote: > >> Grant Edwards wrote: > >>> On 2007-02-12, Larry Bates wrote: > >>>> On 2007-02-12, Larry Bates wrote: > >>>>>>> I at least need the code for useing some library for > >>>>>>> connecting to acrobat reader and giving the print command on > >>>>>>> windows and some thing similar on ubuntu linux. > >>>>>> Just let the registered .PDF viewer do it for you. > > >>>>>> os.start('myfile.pdf') > >>>>> Eh? I don't see os.start() it either 2.5 or 2.44 > >>>>> documentation, and it's sure not there in 2.4.3: > >>>> My bad. os.system() > >>> That doesn't work either: > > >>> $ ls -l user.pdf > >>> -rw------- 1 grante users 35640 2005-11-21 14:33 user.pdf > > >>> $ python > >>> Python 2.4.3 (#1, Dec 10 2006, 22:09:09) > >>> [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > >>> Type "help", "copyright", "credits" or "license" for more > >>> information. > >>> >>> import os > >>> >>> os.system('user.pdf') > >>> sh: user.pdf: command not found > >>> 32512 > > >> Works fine on my system. You linux guys just have it hard. > >> The op said "windows". > > > The posting to which you replied specified Linux. > > >> I can't answer for ubuntu linux but maybe you can help there? > > > I don't see how. Pdf files just aren't executable. > > On Windows, this (where fileName is xyz.PDF, for example): > webbrowser.open(r'file://' + fileName) > starts Acrobat Reader with the document read in. I have no idea why, > because Acrobat Reader sure ain't my browser;) > > Maybe someone could try this out on Linux. > > Cheers, > Jussi Works on Ubuntu -- this opens a tab in my browser and then launches Document Viewer to view the PDF. peter at astro:~$ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import webbrowser >>> webbrowser.open(r'file:///home/peter/appa.pdf') >>> From eopadoan at altavix.com Fri Feb 16 14:04:19 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 16 Feb 2007 17:04:19 -0200 Subject: why I don't like range/xrange In-Reply-To: <53m8p8F1sf1i1U1@mid.individual.net> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <53m8p8F1sf1i1U1@mid.individual.net> Message-ID: > But this long int => int issue should not exist in a future python > version any more, IIRC int and long int is scheduled to be merged > somehow. (Or isn't it?) It is done. http://mail.python.org/pipermail/python-3000-checkins/2007-January/000251.html -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From B.Ogryczak at gmail.com Mon Feb 26 12:16:44 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 26 Feb 2007 09:16:44 -0800 Subject: python notation in new NVIDIA architecture In-Reply-To: References: Message-ID: <1172510204.056500.4410@8g2000cwh.googlegroups.com> On Feb 26, 2:03 pm, "Daniel Nogradi" wrote: > Something funny: > > The new programming model of NVIDIA GPU's is called CUDA and I've > noticed that they use the same __special__ notation for certain things > as does python. For instance their modified C language has identifiers > such as __device__, __global__, __shared__, etc. Is it a coincidence? > Probably it is. :) It's no coincidence. __* and __*__ have been used in C long before Python. And Python (as almost any modern language) takes a lot of syntax from C/C++. From karoly.kiripolszky at gmail.com Mon Feb 5 08:11:07 2007 From: karoly.kiripolszky at gmail.com (=?iso-8859-1?q?K=E1roly_Kiripolszky?=) Date: 5 Feb 2007 05:11:07 -0800 Subject: C parsing fun In-Reply-To: <1170680435.129554.133030@a34g2000cwb.googlegroups.com> References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170680435.129554.133030@a34g2000cwb.googlegroups.com> Message-ID: <1170681066.967476.155240@q2g2000cwa.googlegroups.com> Thx for responding, Szabolcs! I've already tried that, but couldn't manage to get it to work. The source I tried to parse is a huge MSVC 7.1 solution containing about 38 projects, and I believe the code is so complex that it has too many different dependencies and GCC just can't handle them. Btw I'm not deeply familiar with C++ compilers, so maybe it was because of compiler misconfiguration, but I really don't know... Szabolcs Nagy ?rta: > > based on concepts my boss had. To do this I needed to represent C++ > > code structure in Python somehow. I read the docs for Yapps, pyparsing > > and other stuff like those, then I came up with a very simple idea. I > > realized that bracketed code is almost like a Python list, except I > > have to replace curly brackets with squared ones and surround the > > remaining stuff with quotes. This process invokes no recursion or node > > yes that's a nice solution > sometimes it's not enough though (won't work on code obfuscated with > macros) > > anyway if you need something more sophisticated then i'd recommend > gccxml or it's python binding: > > http://www.language-binding.net/pygccxml/pygccxml.html From duncan-news at grisby.org Fri Feb 16 07:33:29 2007 From: duncan-news at grisby.org (Duncan Grisby) Date: 16 Feb 2007 12:33:29 GMT Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <45d5a499$0$5995$b9f67a60@news.newsdemon.com> In article <1171620696.577982.283740 at m58g2000cwm.googlegroups.com>, exhuma.twn wrote: >Supposing you have two separate processes running on the same box, >what approach would you suggest to communicate between those two >processes. [...] >* Webservices > Advantage: Relatively easy to use, can work across different >languages > Disadvantage: Even more overhead on the TCP/IP side that simple >sockets, as really bulky SOAP messages need to be passed around. > >* CORBA -- similar to webservices but more complicated to code. Lots of people say that, but I don't think it's true. Obviously as the maintainer of a CORBA implementation I'm biased, but take a look at some examples of code that implement SOAP clients and servers and compare it to similar CORBA code. Especially in Python, the SOAP code tends to be incredibly verbose and complex, and the CORBA code really small and simple. My recommendation would be that for simple communications where performance isn't important use XML-RPC; for more complex cases where performance is a bit more important but you don't need anything except Python, use Pyro; for cases where performance is particularly important and/or you need cross-language communications, use CORBA. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- -- Posted via NewsDemon.com - Premium Uncensored Newsgroup Service ------->>>>>>http://www.NewsDem From sjdevnull at yahoo.com Wed Feb 21 17:23:19 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 21 Feb 2007 14:23:19 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> <1172043626.705209.14870@v45g2000cwv.googlegroups.com> Message-ID: <1172096599.208376.271280@j27g2000cwj.googlegroups.com> On Feb 21, 1:44 pm, a... at pythoncraft.com (Aahz) wrote: > > Note that I believe it will be many years, perhaps even a decade, before > "python" on a Unix system starts up Python 3.0. That's a pretty safe bet considering that the factory-installed "python" on my Linux system is still 1.x and you run "python2" to get 2.x (I haven't done a new OS install in a couple of years, but 2.x had been out for years when I did the install). And 2.x is much less likely to break 1.x code than 3.x will be to break 2.x code. From DierkErdmann at mail.com Thu Feb 22 15:55:54 2007 From: DierkErdmann at mail.com (DierkErdmann at mail.com) Date: 22 Feb 2007 12:55:54 -0800 Subject: pyinstaller fails to create exe-File Message-ID: <1172177754.619194.30090@k78g2000cwa.googlegroups.com> Hi ! I am trying to create an exe file using pyinstaller. Running the created exe-File gives the error message "" Traceback (most recent call last): File "", line 8, in File "E:\Documents\mich\job\abs\backup_skript\buildbackup\out1.pyz/ email", lin e 79, in __getattr__ File "D:\Programme\pyinstaller\iu.py", line 334, in importHook raise ImportError, "No module named %s" % fqname ImportError: No module named email.mime.multipart "" My python-Skript uses the following imports: import ConfigParser import glob import os import smtplib import time import win32api import zipfile from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders Can someone help? Running python script.py works without any problems. I have also tried to use py2exe, but python setup.py py2exe gives the following error message: copying d:\programme\python25\lib\site-packages\py2exe\run.exe -> E: \Documents\m ich\job\abs\backup_skript\dist\backup.exe Traceback (most recent call last): File "setup.py", line 4, in setup(console=["backup.py"]) File "d:\programme\python25\lib\distutils\core.py", line 151, in setup dist.run_commands() File "d:\programme\python25\lib\distutils\dist.py", line 974, in run_commands self.run_command(cmd) File "d:\programme\python25\lib\distutils\dist.py", line 994, in run_command cmd_obj.run() File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", line 223, in run self._run() File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", line 290, in _run self.create_binaries(py_files, extensions, dlls) File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", line 548, in create_binaries arcname, target.script) File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", line 788, in build_executable add_resource(unicode(exe_path), script_bytes, u"PYTHONSCRIPT", 1, True) RuntimeError: EndUpdateResource: Das System kann das angegebene Ger?t oder die a ngegebene Datei nicht ?ffnen. (=System cannot find the specified device or the file) Thanks in advance. Dierk From a.schmolck at gmail.com Tue Feb 27 15:42:58 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 27 Feb 2007 20:42:58 +0000 Subject: [ANN] mlabrap-1.0b: a high level python to matlab bridge Message-ID: URL --- Description ----------- Mlabwrap-1.0 is a high-level python to matlab(tm) bridge that makes calling matlab functions from python almost as convenient as using a normal python library. It is available under a very liberal license (BSD/MIT) and should work on all major platforms and (non-ancient) python and matlab versions and either numpy or Numeric (Numeric support will be dropped in the future). News ---- version 1.0b brings python 2.5 compatibility and various small fixes (improved error handling for 7.3, improvements to setup.py etc.). Provided I don't get any bug reports within the next two weeks or so the only difference between this version and 1.0 final will be cheeseshop support. Since mlabwrap 1.0 will be the last version that offers Numeric support anyone who wants to put off the switch to numpy a bit longer and is interested in using mlabwrap is strongly encouraged to download, test and possibly submit a bug report now. Examples -------- Creating a simple line plot: >>> from mlabwrap import mlab; mlab.plot([1,2,3],'-o') Creating a surface plot: >>> from mlabwrap import mlab; from numpy import * >>> xx = arange(-2*pi, 2*pi, 0.2) >>> mlab.surf(subtract.outer(sin(xx),cos(xx))) Creating a neural network and training it on the xor problem (requires netlab) >>> net = mlab.mlp(2,3,1,'logistic') >>> net = mlab.mlptrain(net, [[1,1], [0,0], [1,0], [0,1]], [0,0,1,1], 1000) Thanks go to Taylor Berg and many others who tested and provided feedback for the upcoming 1.0 release; more acknowledgements can be found on the website. cheers, 'as From jstroud at mbi.ucla.edu Fri Feb 23 17:31:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 23 Feb 2007 14:31:08 -0800 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: Troy Melhase wrote: >> Why do people sometimes use one leading underscore? > > > Many folks like to use the single leading underscore to emphasize that > the attribute isn't part of the normal way to use the class or > instance. > > It's bad style in my opinion, but I'm probably in the minority. I've increasingly found that leading underscores are unnecessary as well if not using a "magic" attribute with the bounding double underscores. From NikitaTheSpider at gmail.com Fri Feb 16 15:48:17 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 16 Feb 2007 15:48:17 -0500 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: In article <1171620696.577982.283740 at m58g2000cwm.googlegroups.com>, "exhuma.twn" wrote: > Hi all, > > Supposing you have two separate processes running on the same box, > what approach would you suggest to communicate between those two > processes. Hi exhuma, That would depend on what data I was exchanging between the processes. For instance, if process A spawns work process B and wants to be able monitor B's progress, a message-based protocol might be kind of chatty. In this situation shared memory is probably a better fit because B can write it's progress to a chunk of shared memory and A can read that at its leisure. OTOH if the conversation is more event-driven, then a messaging protocol makes good sense. FYI there's a Python module (with sample code) for using shared memory on most *nix systems here: http://NikitaTheSpider.com/python/shm/ HTH -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From ptmcg at austin.rr.com Fri Feb 16 11:09:09 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Feb 2007 08:09:09 -0800 Subject: why I don't like range/xrange In-Reply-To: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: <1171642148.972583.67430@h3g2000cwc.googlegroups.com> On Feb 16, 9:30 am, "stdazi" wrote: > Hello! > > Many times I was suggested to use xrange and range instead of the > while constructs, and indeed, they are quite more elegant - but, after > calculating the overhead (and losen flexibility) when working with > range/xrange, and while loops, you get to the conclusion that it isn't > really worth using range/xrange loops. > > I'd like to show some examples and I'll be glad if someone can suggest > some other fixes than while a loop :-) > > a) range overfllow : > > for i in range(0, 1 << len(S)) : > ..... > OverflowError: range() result has too many items > > ok, so we fix this one with xrange ! > > b) xrange long int overflow : > > for i in xrange(0, 1 << len(S)) : > ........ > OverflowError: long int too large to convert to int > > Next thing I miss is the flexibility as in C for loops : > > for (i = 0; some_function() /* or other condition */ ; i++) > > or, > > for (i = 0 ; i < 10 ; i++) > i = 10; > > I don't think range/xrange sucks, but I really think there should be > some other constructs to improve the looping flexibility. Other thing > may be, that I just miss an equally elegant alternative that's why I'd > like to hear some suggestions on how to fix the above issues.. (btw, > I've already browsed the archives related to my issue,but i don't see > any good solution) > > Thanks > > Jernej. Very little of my own code uses range or xrange, most of my for loops iterate over a sequence or generator, as in "for item in blahList: do something with item". I think range/xrange are common beginner's constructs, since they reflect a more C-like looping method ("for i in range(len(blahList)): do something with blahList[i]"). I really would *not* encourage use of range/xrange, but feel that iteration over sequences and generators is the more elegant/Pythonic way to go - who is suggesting you use range/xrange? For that matter, just what is it you plan to do 2**len(S) times? If S is of any significant length, the sun may be a lump of coal before you are finished, regardless of what loop mechanism you use (although it would make sense to avoid range's implementation of creating a list of 2**len(S) items - fortunately the implementation already resolves this problem by raising a "that's too many items" exception, and thankfully so). Maybe instead of working around range/xrange, you should think whether a 2**len(S) approach to your problem is feasible in the first place. -- Paul From pink at odahoda.de Wed Feb 7 13:43:57 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 07 Feb 2007 19:43:57 +0100 Subject: distutils: renaming setup.py ok? References: Message-ID: Hello, Anastasios Hatzis wrote: > I want to distribute Python site-packages. Is it okay to use other setup > file names than setup.py, which is mentioned in any place I read in the > doc? > > E.g., setupMySDK.py, setupMyLib.py > > It seems that it works with distutils at least - but probably doing so > has side-effects with other tools which may expect exactly "setup.py" as > file name. I'd say, it's mostly the user who is expecting "setup.py" as the filename. Perhaps 'setup.py --install-sdk' and 'setup.py --install-lib' would be more approriate (which can be done with distutils). HTH -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From gherron at islandtraining.com Thu Feb 8 11:39:36 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 08 Feb 2007 08:39:36 -0800 Subject: Strings in Python In-Reply-To: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> References: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> Message-ID: <45CB5248.5060902@islandtraining.com> Johny wrote: > Playing a little more with strings, I found out that string.find > function provides the position of > the first occurance of the substring in the string. > Is there a way how to find out all substring's position ? > To explain more, > let's suppose > > mystring='12341' > import string > > >>>> string.find(mystring ,'1') >>>> > 0 > > But I need to find the possition the other '1' in mystring too. > Is it possible? > Or must I use regex? > Thanks for help > L > > You could use a regular expression. The re module has s function "findall" that does what you want. Also, if you read the documentation for strings find method, you'll find: 1 S.find(sub [,start [,end]]) -> int 2 3 Return the lowest index in S where substring sub is found, 4 such that sub is contained within s[start,end]. Optional 5 arguments start and end are interpreted as in slice notation. 6 7 Return -1 on failure. So put your find in a loop, starting the search one past the previously found occurrence. i = string.find(mystring, i+1) Gary Herron From dlenski at gmail.com Thu Feb 22 15:38:37 2007 From: dlenski at gmail.com (Dan Lenski) Date: 22 Feb 2007 12:38:37 -0800 Subject: HTTP proxy server for Motorola E815 phone in Python Message-ID: <1172176716.985985.101360@v33g2000cwv.googlegroups.com> Hi all, I've recently written an HTTP proxy server for the Motorola E815 cell phone, based on Suzuki Hisao's "Tiny HTTP Proxy" (http:// www.okisoft.co.jp/esc/python/proxy/). This cell phone allows free Internet access if you change the default proxy server, but it has a severely buggy HTTP client implementation which will freeze if there's no Content-Length header. Basically, it's impossible to read normal web pages without some massaging of the headers. So my proxy adds the correct Content-Length header and tweaks the response in a couple of other ways. It works great now, you can get the code from: http://tonquil.homeip.net/~dlenski/cellphoneproxy/ I've MIT licensed it. It works fine as a proxy for a "normal" web browser too! One of the things I had trouble with was getting decent speed out of this proxy. The original "Tiny HTTP Proxy" didn't support persistent connections... which seriously slows down web browsing with a proxy, since it essentially DOUBLES the number of TCP connections that need to be made for each page access. So my proxy *does* support persistent connections, using the standard Connection or non-standard Proxy-Connection headers to determine whether to keep the connection alive or not. It's still not perfect though... apparently sometimes a web browser will SAY that it wants to keep a connection alive, and then just drop it. The proxy normally runs in a multi-threaded mode, and it counts the number of times that each connection is reused, printing this when the RequestHandler.finish() method is eventually called. If I force the proxy to run in a single thread, and use it as a proxy for Firefox, it will freeze up after a few page requests... the proxy will wait around for a new request on the same socket that never comes. So, my question is... is there any way to improve on this? Is there a way to make BaseHTTPRequestHandler detect when its connection has been closed by the peer without waiting for a long timeout? Is there a way to get the browser to always reuse a connection when it says it's going to? Any advice on improving the code is appreciated! Thanks, Dan Lenski From skip at pobox.com Thu Feb 15 15:54:54 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 15 Feb 2007 14:54:54 -0600 Subject: f---ing typechecking In-Reply-To: <003401c75140$761f0650$5138d953@notebook> References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> Message-ID: <17876.51358.879374.972856@montanaro.dyndns.org> Sergey> posix.stat_result is CLASS, not regular tuple. >> I believe it morphed from being a tuple though. I wasn't suggesting >> that Sergey> It it morphed, the tuple nature of it is just history now. No, it is still full of tuple-fu: >>> import os >>> s = os.stat("/etc/hosts") >>> s (33188, 92111L, 26738688L, 1, 0, 1, 355L, 1171570459, 1164401316, 1171087243) >>> type(s) >>> s.st_mtime 1164401316 >>> s[0:3] (33188, 92111L, 26738688L) >>> s[4:] + s[0:3] (0, 1, 355L, 1171570459, 1164401316, 1171087243, 33188, 92111L, 26738688L) >>> type(s[4:] + s[0:3]) >> The notion of tuples as records in Python is not new: >> http://mail.python.org/pipermail/python-list/1999-December/thread.html >> Search for "super tuples". Sergey> Did it go beyond just talking? Raymond Hettinger just proposed adding a pure Python implementation to Python 2.6. The version he's been using for about a year is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261 Sergey> We can think about tuples anything, but are they something other Sergey> than freezed lists? We can index them, slice, iterate, Sergey> map/redice/filter, can cast (fuckin C!) to lists and back - Sergey> what the difference?? "Tuples is similar to records" - I think Sergey> this is just topological artefact, generated when python was Sergey> compared with some other languague :) The fact that tuples and lists share so many implementation details makes people think of tuples as immutable lists. That view has its uses (allowing you to pretend that you can use lists as dictionary keys or take advantage of the compile-time allocation of tuples of constants, for example), but I don't think that makes the view of tuples as records a "topological artifact". I'm not sure where you believe Python was compared to some other language. My original comment was that tuples could be thought of more like C structs or Pascal records. That was an analogy, not a language comparison. Sergey> classes have sintactically and functionally overcame Sergey> records/structs - why to drag to the same role tuples, that have Sergey> not initially any feature of record? They have a number of record-like features. They are relatively compact (unlike class instances), once instantiated they can't be extended (unlike lists or class instances in the common case). They just don't yet have named attributes. Skip From Michel.Al1 at gmail.com Thu Feb 8 13:20:56 2007 From: Michel.Al1 at gmail.com (k0mp) Date: 8 Feb 2007 10:20:56 -0800 Subject: begin to parse a web page not entirely downloaded In-Reply-To: <45cb63d4$0$6842$4d3efbfe@news.sover.net> References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> <45cb63d4$0$6842$4d3efbfe@news.sover.net> Message-ID: <1170958856.700750.3080@a75g2000cwd.googlegroups.com> On Feb 8, 6:54 pm, Leif K-Brooks wrote: > k0mp wrote: > > Is there a way to retrieve a web page and before it is entirely > > downloaded, begin to test if a specific string is present and if yes > > stop the download ? > > I believe that urllib.openurl(url) will retrieve the whole page before > > the program goes to the next statement. > > Use urllib.urlopen(), but call .read() with a smallish argument, e.g.: > > >>> foo = urllib.urlopen('http://google.com') > >>> foo.read(512) > ' ... > > foo.read(512) will return as soon as 512 bytes have been received. You > can keep caling it until it returns an empty string, indicating that > there's no more data to be read. Thanks for your answer :) I'm not sure that read() works as you say. Here is a test I've done : import urllib2 import re import time CHUNKSIZE = 1024 print 'f.read(CHUNK)' print time.clock() for i in range(30) : f = urllib2.urlopen('http://google.com') while True: # read the page using a loop chunk = f.read(CHUNKSIZE) if not chunk: break m = re.search('', chunk ) if m != None : break print time.clock() print print 'f.read()' print time.clock() for i in range(30) : f = urllib2.urlopen('http://google.com') m = re.search('', f.read() ) if m != None : break print time.clock() It prints that : f.read(CHUNK) 0.1 0.31 f.read() 0.31 0.32 It seems to take more time when I use read(size) than just read. I think in both case urllib.openurl retrieve the whole page. From rkmr.em at gmail.com Wed Feb 21 20:28:51 2007 From: rkmr.em at gmail.com (mark) Date: Wed, 21 Feb 2007 17:28:51 -0800 Subject: guess file type in python Message-ID: Is there any way to guess the file type using python? thanks mark For example in unix: file code.py code.py: a python script text executable file Eccentric.gif Eccentric.gif: GIF image data, version 89a, 237 x 277 From bearophileHUGS at lycos.com Fri Feb 23 13:31:08 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Feb 2007 10:31:08 -0800 Subject: Rational numbers In-Reply-To: <20070223113911.05dcc555@localhost> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> Message-ID: <1172255468.167305.144430@q2g2000cwa.googlegroups.com> Martin Manns: > + gmpy is looking pretty unmaintained (dead) to me (newest update of > cvs 10 months ago). I have used it on Py2.5, so it seems to work anyway, and it's fast enough for my purposes. And probably soon some alex-shaped life will show up elsewhere. Bye, bearophile From JStoneGT at aol.com Tue Feb 6 00:10:14 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Tue, 6 Feb 2007 00:10:14 EST Subject: python for web programming Message-ID: hello, Can you show me some reference datas for python web programming?Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Fri Feb 16 00:07:04 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 15 Feb 2007 22:07:04 -0700 Subject: Pep 3105: the end of print? In-Reply-To: References: Message-ID: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> Edward K Ream wrote: >> You could offer up a patch for Python 2.6 so that you can do:: >> from __future__ import print_function > > This would only work for Python 2.6. Developers might want to support Python > 2.3 through 2.5 for awhile longer :-) Python 3.0 is determined not to be hampered by backwards incompatibility concerns. It's not even clear yet that your average 2.6 code will work on 3.0 -- though there's a pretty large contingent trying to make this true. In short, if you need to support 2.3, you're not ready to be looking at 3.0. STeVe From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 18:20:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 00:20:01 +0100 Subject: Broken Library Code, suggested course of action In-Reply-To: <1170713237.448425.187760@a75g2000cwd.googlegroups.com> References: <1170713237.448425.187760@a75g2000cwd.googlegroups.com> Message-ID: <45c7b48b$0$2196$426a74cc@news.free.fr> Melih Onvural a ?crit : > I've been trying to use the URLParse library, and I thought I had all > of the kinks worked out when I ran into this: > > Traceback (most recent call last): > File "./run.py", line 130, in ? > main() > File "./run.py", line 126, in main > r = crawl.crawl(p, x) > File "/home/monvural/src/crawl.py", line 74, in crawl > root = parser.legiturl(url) > File "/home/monvural/src/crawl.py", line 22, in legiturl insert this line here: print "url : ", url, type(url) > t = urlparse.urlparse(url) > File "/usr/lib/python2.4/urlparse.py", line 50, in urlparse > tuple = urlsplit(url, scheme, allow_fragments) > File "/usr/lib/python2.4/urlparse.py", line 89, in urlsplit > i = url.find(':') > AttributeError: 'tuple' object has no attribute 'find' I guess you'll find that you pass a tuple instead of a string. From stj911 at rock.com Fri Feb 9 11:19:21 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 9 Feb 2007 08:19:21 -0800 Subject: MOSSAD AND 911 - Zack was the anthrax mailer ? Message-ID: <1171037961.326060.278990@a75g2000cwd.googlegroups.com> WHAT DID ISRAEL KNOW IN ADVANCE OF THE SEPTEMBER 11 ATTACKS? * Those Celebrating "Movers" and Art Student Spies * Who were the Israelis living next to Mohammed Atta? * What was in that Moving Van on the New Jersey shore? * How did two hijackers end up on the Watch List weeks before 9/11? At last, the answers. Read Christopher Ketcham's exclusive expose in CounterPunch special double-issue February newsletter. Plus, Cockburn and St. Clair on how this story was suppressed and ultimately found its home in CounterPunch. ====== There are more questions that Alex Cockburn does not ask: 1) Who is the anthrax mailer ? Was the anthrax produced in US or Israeli Labs ? So much for the Israeli love for America. 2) Why did the FBI release the five dancing israelis and not send them to Guantanamo Bay for Interrogation ? 3) What about the pager message to Israelis in WTC not to come to work on 9/11 ? 4) Who rigged Larry Silverstein's towers, WTC1,2,7 and how much larry silverstein, a likudnik jew himself involved in 911 demolitions ? ====== But Bush was merely an ego front for the neocons ... He spoke their speeches, signed their recommendations, and ordered their wars, go and listen to Benjamin Friedman's excellent video in his very passionate voice ... http://video.google.com/videoplay?docid=3552214685532803163&q 911blogger.com <--- the best 911 site, the master site to all other sites From mbm at mediamonger.ch Sun Feb 11 07:21:44 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Sun, 11 Feb 2007 13:21:44 +0100 Subject: How to access an absolute address through Python? In-Reply-To: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> Message-ID: <45CF0A58.2080003@mediamonger.ch> volcano schrieb: > Can it be done, and if yes - how? > Define address. Are you talking about URLs? File paths? Postal addresses? Memory addresses? Whatever addresses? I'm afraid the people on this list can't read your thoughts... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 2 08:19:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 02 Feb 2007 14:19:16 +0100 Subject: LDAP/LDIF Parsing In-Reply-To: References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> <45c26772$0$4272$426a74cc@news.free.fr> Message-ID: <45c339f3$0$432$426a74cc@news.free.fr> Hallvard B Furuseth a ?crit : > Bruno Desthuilliers writes: >> class LdapObject(object): >> (...) >> def __getattr__(self, name): >> try: >> data = self._record[name] >> except KeyError: >> raise AttributeError( >> "object %s has no attribute %s" % (self, name) >> ) > > Note that LDAP attribute descriptions may be invalid Python > attribute names. E.g. > {... > 'title;lang-en': ['The Boss'] > 'title;lang-no': ['Sjefen']} > So you'd have to call getattr() explicitly to get at all the attributes > this way. Yeps, true. Another solution would be to add a __getitem__ method pointing to the same implementation, ie: __getitem__ = __getattr__ >> else: >> # all LDAP attribs are multivalued by default, >> # even when the schema says they are monovalued >> if len(data) == 1: >> return data[0] >> else: >> return data[:] > > IMHO, this just complicates the client code since the client needs to > inserts checks of isinstance(return value, list) all over the place. > Better to have a separate method which extracts just the first value of > an attribute, if you want that. Most of the times, in a situation such as the one described by the OP, one knows by advance if a given LDAP attribute will be used as monovalued or multivalued. Well, this is at least my own experience... From steve at REMOVEME.cybersource.com.au Wed Feb 28 01:16:06 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Feb 2007 17:16:06 +1100 Subject: Walk thru each subdirectory from a top directory References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <1172529799.827628.321760@p10g2000cwp.googlegroups.com> <%6QEh.6363$_73.680@newsread2.news.pas.earthlink.net> Message-ID: On Tue, 27 Feb 2007 06:22:51 +0000, Dennis Lee Bieber wrote: [snip 350-odd file names] > Just a sample of the start of a very long listing... Thanks for sharing. What's with the nude ferret? -- Steven D'Aprano From micheleworldwide at yahoo.com Sun Feb 18 11:44:42 2007 From: micheleworldwide at yahoo.com (Michele Smith) Date: Sun, 18 Feb 2007 08:44:42 -0800 (PST) Subject: FAQ maintenance with Python ... Message-ID: <99554.97899.qm@web60915.mail.yahoo.com> Hello. I am trying to find Scott Witherell who graduated from WSHS and UVA. Do you know how I can get in touch with him? Michele Smith --------------------------------- Everyone is raving about the all-new Yahoo! Mail beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rattan at cps.cmich.edu Wed Feb 7 22:14:13 2007 From: rattan at cps.cmich.edu (rattan at cps.cmich.edu) Date: 7 Feb 2007 19:14:13 -0800 Subject: help on packet format for tcp/ip programming In-Reply-To: <52vdh6F1qp2n6U1@mid.individual.net> References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> Message-ID: <1170904453.625206.54970@l53g2000cwa.googlegroups.com> On Feb 8, 1:43 am, Bjoern Schliessmann wrote: > rat... at cps.cmich.edu wrote: > > I want a specific packet format for packet exchange between a > > client server across the network. For example frame format > > as a python class could be: > > class Frame: > > def __init__(self, buffer=None, count=0, offset=0): > > self.buffer = buffer > > self.count = count > > self.offset = offset > > the question is how to convert it to a byte stream so that format > > of count and offset also becomes a sequence of bytes. > > Try struct. > > Regards, > > Bj?rn > > -- > BOFH excuse #208: > > Your mail is being routed through Germany ... and they're censoring > us. struct module pack and unpack will only work for fixed size buffer : pack('>1024sIL', buffer, count. offset) but the buffer size can vary from one packet to the next :-( -ishwar From sickcodemonkey at gmail.com Mon Feb 19 10:29:33 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Mon, 19 Feb 2007 10:29:33 -0500 Subject: Python Threads In-Reply-To: References: <2adc542f0702181516g7bbfb08ga721b568cb528404@mail.gmail.com> <2adc542f0702181837g3c433742ha0fedd775d8cc0fa@mail.gmail.com> Message-ID: <2adc542f0702190729h7d193706j76fad6437358d71c@mail.gmail.com> Great, thanks for the tip Gabriel! On 2/18/07, Gabriel Genellina wrote: > > En Sun, 18 Feb 2007 23:37:02 -0300, Sick Monkey > escribi?: > > > Well if this cannot be done, can a thread call a function in the main > > method? > > I have been trying and have not been successive. Perhaps I am using > > thread > > incorrectly. > > The safe way to pass information between threads is to use Queue. From > inside the working thread, you put() an item with enough state > information. On the main (GUI) thread, you use after() to check for any > data in the queue, and then update the interfase accordingly. > I think there is a recipe in the Python Cookbook > http://aspn.activestate.com/ASPN/Cookbook/Python > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Fri Feb 9 08:11:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Feb 2007 00:11:47 +1100 Subject: Object type check References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> <1170932439.393593.200090@h3g2000cwc.googlegroups.com> Message-ID: On Thu, 08 Feb 2007 03:00:39 -0800, king kikapu wrote: >> def modify(list_of_x): >> for x in list_of_x: >> try: >> x.change_in_place # don't call the method, just check it exists > > XXmmmm...what exactly is going on here ? I mean, what is actually > happens if you omit the parenethesis as you just did ? I understand > that it does not call the method, but what is really doing ?? The same as for any attribute: x.name gives the object referred to by the attribute name, and x.name() calls that object. He's a simple example: >>> def foo(): ... return "foo" ... >>> type(foo) # the name alone >>> type(foo()) # call the function -- Steven. From grflanagan at yahoo.co.uk Tue Feb 13 04:30:24 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 13 Feb 2007 01:30:24 -0800 Subject: how to compare... In-Reply-To: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> References: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> Message-ID: <1171359024.422165.70250@j27g2000cwj.googlegroups.com> On Feb 13, 5:03 am, "jairodsl" wrote: > Hello everybody ! > > I have two list, they are, S1=['A','B','C','D','E'], and > S2=['F','G','H','I','J'], but i have to compare both in this way: > > A vs J > A vs I, B vs J > A vs H, B vs I, C vs J > A vs G, B vs H, C vs I, D vs J > A vs F, B vs G, C vs H, D vs I, E vs J > B vs F, C vs G, D vs H, E vs I > C vs F, D vs G, E vs H > D vs F, E vs G > E vs F > Could someone give me any idea how to compare(or print) both list in > this way ??? Thanks a lot !!! > > jDSL def interleave( X, Y ): for i in range(1, len(Y)+1): yield zip(X, Y[-i:]) for j in range(1, len(X)): yield zip(X[j:], Y) x = ['A', 'B', 'C', 'D', 'E'] y = ['F', 'G', 'H', 'I', 'J'] for seq in interleave(x, y): print seq [('A', 'J')] [('A', 'I'), ('B', 'J')] [('A', 'H'), ('B', 'I'), ('C', 'J')] [('A', 'G'), ('B', 'H'), ('C', 'I'), ('D', 'J')] [('A', 'F'), ('B', 'G'), ('C', 'H'), ('D', 'I'), ('E', 'J')] [('B', 'F'), ('C', 'G'), ('D', 'H'), ('E', 'I')] [('C', 'F'), ('D', 'G'), ('E', 'H')] [('D', 'F'), ('E', 'G')] [('E', 'F')] Regards Gerard From mona_jamil2000 at yahoo.com Mon Feb 19 07:42:46 2007 From: mona_jamil2000 at yahoo.com (mona_jamil2000 at yahoo.com) Date: 19 Feb 2007 04:42:46 -0800 Subject: Free Url submission, Forum, Free Ebooks, Articles etc Message-ID: <1171888966.674193.22140@h3g2000cwc.googlegroups.com> Free Url submission, Forum, Free Ebooks, Articles etc.. http://www.aonearticles.com From garrickp at gmail.com Wed Feb 21 12:34:45 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 21 Feb 2007 09:34:45 -0800 Subject: Regex Speed In-Reply-To: References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> Message-ID: <1172079285.197453.131490@h3g2000cwc.googlegroups.com> On Feb 20, 6:14 pm, Pop User wrote: > Its very hard to beat grep depending on the nature of the regex you are > searching using. The regex engines in python/perl/php/ruby have traded > the speed of grep/awk for the ability to do more complex searches. > > http://swtch.com/~rsc/regexp/regexp1.html Some darned good reading. And it explains what happened fairly well. Thanks! > > And python 2.5.2. > > 2.5.2? Who needs crystal balls when you've got a time machine? Or did > you mean 2.5? Or 1.5.2 -- say it ain't so, Joe! 2.5. I'm not entirely sure where I got that extra 2. I blame Monday. In short... avoid using re as a sledgehammer against every problem. I had a feeling that would be the case. From kungfoobar at gmail.com Mon Feb 5 05:48:08 2007 From: kungfoobar at gmail.com (kungfoobar at gmail.com) Date: 5 Feb 2007 02:48:08 -0800 Subject: Inheriting str object Message-ID: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> I want to have a str with custom methods, but I have this problem: class myStr(str): def hello(self): return 'hello '+self s=myStr('world') print s.hello() # prints 'hello world' s=s.upper() print s.hello() # expected to print 'hello WORLD', but s is no longer myStr, it's a regular str! What can I do? From hg at nospam.org Tue Feb 13 03:50:11 2007 From: hg at nospam.org (hg) Date: Tue, 13 Feb 2007 09:50:11 +0100 Subject: float print formatting References: <12t3n06pi0diobf@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-02-13, hg wrote: >> Hi, >> >> Considering the float 0.0, I would like to print 00.00. >> >> I tried '%02.02f' % 0.0 ... but I get 0.00 > ^^ > That's the specifierfor how many total columns you want to use > (including the decimal point and all digits to either side). > >> Any clue ? > >>>> "%05.02f" % 0.0 > '00.00' > > -- > Grant Edwards grante Yow! Yow!! "Janitor > at trapped in sewer uses > ESP > visi.com to find decayed > burger"!! Thanks From grflanagan at yahoo.co.uk Tue Feb 6 04:57:49 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 6 Feb 2007 01:57:49 -0800 Subject: Calling J from Python In-Reply-To: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> Message-ID: <1170755869.622823.104220@v45g2000cwv.googlegroups.com> On Feb 5, 3:48 pm, "Gosi" wrote: > It is quite easy to call J from Python > > http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... As I understand it, the k language, which is similar to J, is used to interact with streamed realtime financial data, where I imagine the terseness of the language may make sense. I messed about with J for a day or two, and found it interesting and in a way natural (given some Higher Math background once upon a time). Here's a link to a company who it looks like could value some knowledge of J/K/APL type languages: http://www.kx.com/news/in-the- news.php All the best Gerard From frodo at theshire.org Wed Feb 14 08:59:47 2007 From: frodo at theshire.org (Cristiano Paris) Date: Wed, 14 Feb 2007 14:59:47 +0100 Subject: How to print the variable? In-Reply-To: <345345.69488.qm@web39715.mail.mud.yahoo.com> References: <345345.69488.qm@web39715.mail.mud.yahoo.com> Message-ID: <45D315D3.3030402@theshire.org> Hans Schwaebli wrote: > Hi, > > am am a Python beginner with Java knowledge background. Infact I need to > use Jython. > > My first beginner question is how to determine of what type a variable is? Let v be the var, 'print type(v)' should* work. [* I've never used Jython before]. You can print any variable using the 'print' statement. If you want to be pedantic, surround the variable name with the str() built-in. Cristiano From steve at holdenweb.com Wed Feb 21 05:11:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Feb 2007 05:11:58 -0500 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: References: Message-ID: joanne matthews (RRes-Roth) wrote: > I'm getting different results when I add up a list of floats depending > on the order that I list the floats. For example, the following returns > False: > def check(): > totalProp=0 > inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1] > for each in inputs: > > totalProp+=each > print "totalProp=",totalProp > if totalProp != 1: > print "Your proportions must add up to 1" > > return False > return True > > However, if I swap, the 4th and 5th list items like this: > > totalProp=0 > inputs=[0.2,0.2,0.2,0.2,0.1,0,0.1] > for each in inputs: > > totalProp+=each > print "totalProp=",totalProp > if totalProp != 1: > print "Your proportions must add up to 1" > > return False > return True > > I get True returned. Can anyone tell me whats going on and how I can > avoid the problem. Thanks > > Joanne Matthews I take it by now you understand that you need to test that the sum of your numbers is with some small delta of the value you actually require? I seem to remember this question has been asked on a number of threads, just don't know whether this is the same question as the others. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From sjmachin at lexicon.net Mon Feb 5 21:42:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Feb 2007 18:42:22 -0800 Subject: Decimating Excel files In-Reply-To: References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> <1170725241.634632.100830@v45g2000cwv.googlegroups.com> <1170727172.316685.49980@h3g2000cwc.googlegroups.com> Message-ID: <1170729742.709892.200270@q2g2000cwa.googlegroups.com> On Feb 6, 1:19 pm, gonzlobo wrote: > I tried to open the file with Kate, trust me, it's an Excel file. Who or what is Kate? In what sense is trying to open it any evidence that it's an Excel file? Did you *succeed* in opening the file "with Kate"? What is the problem that the "average user" is having? > > I'm using xlrd, it works beautifully That's nice to know, and not altogether unexpected :-) but doing what exactly? > (although come to think of it, I > haven't tried writing to an .xls file yet... hmmm) Errrrmmm, the "rd" in "xlrd" means *read* -- it doesn't write files. For that, you need a version of pyExcelerator (or variant thereof) with a bug or two fixed. And that won't write "to" files in the sense of updating an existing file. Ermmm #2, sense of deja vu here, did you or did you not receive the detailed e-mail message I sent you 2+ days ago when you first posted?? -- mentioned xlrd, writer, bridge between reader and writer, ... Cheers, John From jstroud at mbi.ucla.edu Tue Feb 20 05:47:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 20 Feb 2007 10:47:57 GMT Subject: WHAT IS THIS? In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > In , James Stroud wrote: > >> Better would be to remove windows xp and get another operating system. > > Yeah XP is sooo ooold, the OP should install Vista. Or did you mean a > real OS instead of just another one? ;-) > > SCNR, > Marc 'BlackJack' Rintsch I meant a real OS. From jeffrey.aylesworth at gmail.com Sun Feb 25 19:53:17 2007 From: jeffrey.aylesworth at gmail.com (jeff) Date: 25 Feb 2007 16:53:17 -0800 Subject: getting terminal display size? Message-ID: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> I looked around a lot on the internet and couldn't find out how to do this, how do I get the sizer (in rows and columns) of the view? From sjmachin at lexicon.net Mon Feb 19 08:55:41 2007 From: sjmachin at lexicon.net (John Machin) Date: 19 Feb 2007 05:55:41 -0800 Subject: How do I create an array of functions? In-Reply-To: References: <1171872999.751809.256880@p10g2000cwp.googlegroups.com> Message-ID: <1171893341.926129.189780@h3g2000cwc.googlegroups.com> On Feb 19, 11:47 pm, Steven D'Aprano wrote: > On Mon, 19 Feb 2007 00:16:39 -0800, Rob Wolfe wrote: > > > Steven W. Orr wrote: > >> I have a table of integers and each time I look up a value from the table > >> I want to call a function using the table entry as an index into an array > >> whose values are the different functions. I haven't seen anything on how > >> to do this in python. > > > Do you mean something like that? > > > # test.py > > > def fun1(): return "fun1" > > def fun2(): return "fun2" > > def fun3(): return "fun3" > > > # list of functions > > dsp = [f for fname, f in sorted(globals().items()) if callable(f)] > > Hmmm... when I try that, I get dozens of other functions, not just fun1, > fun2 and fun3. And not just functions either; I also get classes. > > Does Python have a function that will read my mind and only return the > objects I'm thinking of? Yup. Stevens_mind = r"fun[1-3]$" After "if callable(f)", put and re.match(Stevens_mind, fname) and not isinstance(f, type) From max at alcyone.com Tue Feb 6 14:47:18 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 06 Feb 2007 11:47:18 -0800 Subject: Running long script in the background In-Reply-To: <1170791092.333254.279680@q2g2000cwa.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170769014.352466.135280@h3g2000cwc.googlegroups.com> <1170776253.027044.253050@q2g2000cwa.googlegroups.com> <1170791092.333254.279680@q2g2000cwa.googlegroups.com> Message-ID: wattersmt at gmail.com wrote: > Web pages can show output as it's sent. For testing I created a > script on the server that untars a 600 meg volume, I can see each file > name show up in my browser instantly, just like it should. The other > script I'm trying to run won't show anything until the entire process > is complete and it's just a bunch of echo statements in a for loop, > I'm not sure why they behave differently. In a word: buffering. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis You could have another fate / You could be in another place -- Anggun From http Tue Feb 27 19:59:41 2007 From: http (Paul Rubin) Date: 27 Feb 2007 16:59:41 -0800 Subject: Tuples from List References: Message-ID: <7xhct7jdvm.fsf@ruckus.brouhaha.com> rshepard at nospam.appl-ecosys.com writes: > [ 6.24249034e-01+0.j 5.11335982e-01+0.j 3.67333773e-01+0.j > 3.01189122e-01+0.j 2.43449050e-01+0.j 1.82948476e-01+0.j > 1.43655139e-01+0.j 9.91225725e-02+0.j] > > and I want a list of floats of only the first 6 digits for each value. If I > write: > for i in listname: > print i If you mean the first six digits of the real part and they're all < 1, for z in listname: print '%.5f' % z.real From skip at pobox.com Mon Feb 5 12:03:24 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 5 Feb 2007 11:03:24 -0600 Subject: Calling J from Python In-Reply-To: <1170692852.549730.81030@v33g2000cwv.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: <17863.25436.299354.336711@montanaro.dyndns.org> Gosi> J is in many ways similar to Python. Gosi> J has very many advanced operations. Gosi> http://www.jsoftware.com/ Doesn't look like open source of any variety. If a person uses Python with various add-ons (RPy, numpy, matplotlib, etc) why would they want to switch to a closed source product? Skip From bj_666 at gmx.net Fri Feb 23 13:33:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 23 Feb 2007 19:33:42 +0100 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> Message-ID: In <20070223113911.05dcc555 at localhost>, Martin Manns wrote: > + gmpy is looking pretty unmaintained (dead) to me (newest update of > cvs 10 months ago). What CSV activities do you expect? This package seems to be pretty stable. As long as there is no bug or incompatible changes in the underlying library I would not expect changes to that package. Ciao, Marc 'BlackJack' Rintsch From melih.onvural at gmail.com Mon Feb 5 17:07:17 2007 From: melih.onvural at gmail.com (Melih Onvural) Date: 5 Feb 2007 14:07:17 -0800 Subject: Broken Library Code, suggested course of action Message-ID: <1170713237.448425.187760@a75g2000cwd.googlegroups.com> I've been trying to use the URLParse library, and I thought I had all of the kinks worked out when I ran into this: Traceback (most recent call last): File "./run.py", line 130, in ? main() File "./run.py", line 126, in main r = crawl.crawl(p, x) File "/home/monvural/src/crawl.py", line 74, in crawl root = parser.legiturl(url) File "/home/monvural/src/crawl.py", line 22, in legiturl t = urlparse.urlparse(url) File "/usr/lib/python2.4/urlparse.py", line 50, in urlparse tuple = urlsplit(url, scheme, allow_fragments) File "/usr/lib/python2.4/urlparse.py", line 89, in urlsplit i = url.find(':') AttributeError: 'tuple' object has no attribute 'find' I have just recently upgraded my system to FC6, and I wasn't sure if this was an issue of version change. Why does the urlsplit() function work on my old station, but here I'm getting a tuple cannot find error. I understand from looking at the docs that tuples cannot have operations done onto them as they are immutable and sans index, but there has to be a way to dive into the http address and parse what's there. Thanks for any suggestions, --Melih Onvural From larry.bates at websafe.com Wed Feb 14 12:02:38 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 14 Feb 2007 11:02:38 -0600 Subject: Urllib2 and timeouts In-Reply-To: <1171471921.142012.247450@p10g2000cwp.googlegroups.com> References: <1171471921.142012.247450@p10g2000cwp.googlegroups.com> Message-ID: Johny wrote: > In my script I started using urllib2 to connect to a list of > servers.It works well but only until a server from the list is not > available.Then if it is down , there is a timeout and my script ends > with the error. > So, if I have a list of 10 servers, and the second from the list is > not available , no others are used. > Is there a way how to solve that problem, so that servers after the > server that is not available will be used too? > Thanks for help > L. > Wrap your connection inside a try: block. That way you can catch the exception and continue your loop. -Larry From horpner at yahoo.com Sun Feb 11 08:38:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sun, 11 Feb 2007 13:38:54 GMT Subject: How to find all the same words in a text? References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: On 2007-02-10, Johny wrote: > I need to find all the same words in a text . > What would be the best idea to do that? > I used string.find but it does not work properly for the words. > Let suppose I want to find a number 324 in the text > > '45 324 45324' > > there is only one occurrence of 324 word but string.find() finds 2 > occurrences ( in 45324 too) > > Must I use regex? > Thanks for help The first thing to do is to answer the question: What is a word? The second thing to do is to design some code that can find words in strings. The last thing to do is to search those actual words for the word you're looking for. -- Neil Cerutti From gherron at digipen.edu Mon Feb 19 12:58:51 2007 From: gherron at digipen.edu (Gary Herron) Date: Mon, 19 Feb 2007 09:58:51 -0800 Subject: Declare a variable global In-Reply-To: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> Message-ID: <45D9E55B.3000309@digipen.edu> yinglcs at gmail.com wrote: > Hi, > > I have the following code: > > colorIndex = 0; > > def test(): > print colorIndex; > > This won't work. But it works if i do this: > Yes, it does work. Can you be more explicit about why you think it doesn't? (Also, this is Python not C/C++. Get *RID* of the semi-colons after your statements!) > colorIndex = 0; > > def test(): > global colorIndex; > print colorIndex; > If you wish to change the value of colorIndex inside test, then this won't work colorIndex = 0 def test(): colorIndex=123 # creates a new variable within test In the above case you'll end up with two variables of that name, one in the global context, and the other within test's context. However, this code might be more what you want: colorIndex = 0 def test(): global colorIndex colorIndex=123 # changes the value of the global Better yet, restructure your code to not rely on the global statement. Do something like this if you can: def test(): return 123 colorIndex = test() Gary Herron > My question is why do I have to explicit declaring 'global' for > 'colorIndex'? Can't python automatically looks in the global scope > when i access 'colorIndex' in my function 'test()'? > > Thank you. > > From brochu121 at gmail.com Tue Feb 27 22:44:31 2007 From: brochu121 at gmail.com (David Brochu) Date: Tue, 27 Feb 2007 22:44:31 -0500 Subject: PyFit documentation Message-ID: <9583ed900702271944y5b9c464axe70c96e37c58a5f8@mail.gmail.com> I am trying to run some testing using Fitnesse with the PyFit python module. For some reason I am not able to import the fit.ColumnFixture module from PyFit. I use the following command: from fit.ColumnFixture import ColumnFixture I can't find any documentation on the web for PyFit syntax. Anyone know where I might find documentation so I can see if this is, or ever was, a valid module? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Feb 9 09:14:13 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 09 Feb 2007 14:14:13 +0000 Subject: excel find last column In-Reply-To: References: <1170981163.874220.27660@h3g2000cwc.googlegroups.com> Message-ID: <45CC81B5.9060008@timgolden.me.uk> Lance Hoffmeyer wrote: > I ran makepy.py and loaded Microsoft Excel Object Library 11.0 > I have imported: > > import win32com.client > from win32com.client import constants > import re > import codecs,win32com.client > import time > import datetime > import win32com.client.dynamic > > > using this expression > > lastcol = sh.UsedRange.Find("*", "A1", win32com.client.constant.SearchOrder=xlByColumns, win32com.client.constants.SearchDirection=xlPrevious).Column > > I get error: > > , line 245 > lastcol = sh.UsedRange.Find("*", "A1", win32com.client.constant.SearchOrder=xlByColumns, win32com.client.constants.SearchDirection=xlPrevious).Column > SyntaxError: keyword can't be an expression I suspect you're getting unnecessarily (but understandably) confused by the wrapping which the win32com does for you. Basically, when you run the makepy stuff, a module is generated (which you can go and look at if you feel so inclined) which defines the operations this COM object allows. To handle the constants, a sort of pseudo module is available to you called win32com.client.constants which you use just like any other Python module. In the interpreter dump below, I import the win32com.client stuff and force the module to be generated programatically (essentially the same as calling makepy against the Excel.Application COM library). Then the constants "module" contains, among other things, the xlByColumns constant. Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client >>> xl = win32com.client.gencache.EnsureDispatch ("Excel.Application") >>> win32com.client.constants.xlByColumns 2 >>> If you want to you can use the usual shortcuts: const = win32com.client.constants print const.xlByColumns # or even xlByColumns = const.xlByColumns and use that anywhere you need, so in your example: sh.UsedRange.Find ( "*", "A1", SearchOrder=const.xlByColumns, SearchDirectory=const.xlPrevious ).Column NB I haven't bothered to see whether what your code is doing is correct, merely illustrating the use of constants. HTH a bit TJG From jeff.templon at gmail.com Tue Feb 20 16:10:11 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 13:10:11 -0800 Subject: How to test if one dict is subset of another? In-Reply-To: <7xfy90sizk.fsf@ruckus.brouhaha.com> References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> <1171990539.710698.276050@v45g2000cwv.googlegroups.com> <1171992831.871231.86450@h3g2000cwc.googlegroups.com> <7x3b50d8ri.fsf@ruckus.brouhaha.com> <1171999619.755238.294080@m58g2000cwm.googlegroups.com> <7xfy90sizk.fsf@ruckus.brouhaha.com> Message-ID: <1172005809.086246.63000@p10g2000cwp.googlegroups.com> Hi, thanks! the code lift from 2.3 to 2.2 worked (thank Guido et al for BACKWARDS COMPATIBILITY ;-)) ... unfortunately I was in a hurry to get the release out since a colleague's cluster was croaking under the load of the old, non-indexed version. Your solution is nicer looking than mine, and leads to a less complex implementation. Rolling it into the next release is going to have to wait a few weeks, I hope I can remember it that long. Thanks!! JT On Feb 20, 8:54 pm, Paul Rubin wrote: > "Jay Tee" writes: > > Python 2.2.3 (#1, Oct 26 2003, 11:49:53) > > ImportError: No module named sets > > Hmm, well I think the sets module in 2.3 is written in Python, so you > could drop it into your application for use in 2.2. Better would be > to use the C version from 2.4 if you can. Or you could fake it with > dicts. Sets are really just dicts under the skin. Instead of > set([1,2,3]) you'd use {1:True, 2:True, 3:True}. To intersect > two of them (untested): > > def intersection(d1,d2): > if len(d2) < len(d1): > # swap them so d1 is the smaller one > d1,d2 = d2,d1 > r = {} > for k in d1.iterkeys(): > if k in d2: > r[k] = True > return r > > The d1,d2 swap is just an optimization, since access is constant-time > you want to scan the smaller dictionary to minimize the number of > lookups. From python at hope.cz Sat Feb 3 07:24:49 2007 From: python at hope.cz (Johny) Date: 3 Feb 2007 04:24:49 -0800 Subject: Mod_python and encoding problem Message-ID: <1170505489.296912.308450@a75g2000cwd.googlegroups.com> I use a mod_python request handler and need the output( HTML pages) to be in utf-8 encoding) So, I added to my handler req.content_type = 'text/html ;charset=utf-8' req.write(''' .... ... (""".decode('utf8').encode('utf8')) The problem now is that when I try to call the handler , it is not run properly but instead a download dialog is open I am asked where I want to download that handler. If I ,however,remove charset=utf-8 from req.content_type = 'text/html ;charset=utf-8' handler works well but the utf-8 coding is not set properly Can anyone help/explain? Thanks LL From pink at odahoda.de Mon Feb 5 06:21:09 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 05 Feb 2007 12:21:09 +0100 Subject: Inheriting str object References: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <1170672488.530515.181340 at k78g2000cwa.googlegroups.com>, > kungfoobar at gmail.com wrote: > >> I want to have a str with custom methods, but I have this problem: >> >> class myStr(str): >> def hello(self): >> return 'hello '+self >> >> s=myStr('world') >> print s.hello() # prints 'hello world' >> s=s.upper() >> print s.hello() # expected to print 'hello WORLD', but s is no longer >> myStr, it's a regular str! >> >> What can I do? > > Return a `myStr` instance instead of a regular `str`: > > def hello(self): > return myStr('hello ' + self) yes, but the 'upper' method is the problem here. So you'd have to override all string methods, like class myStr(str): ... def upper(self): return myStr(str.upper(self)) And I'm not sure, if it then works in the intended way... What you are probably looking for, is to extend the 'str' class itself, so every str instance has your added functionality. Don't know, if this is possible at all, but usually it's not a good idea to mess with the bowels of Python unless you have some greater surgical skills. HTH -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From http Mon Feb 12 01:03:06 2007 From: http (Paul Rubin) Date: 11 Feb 2007 22:03:06 -0800 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: <7xbqjzud45.fsf@ruckus.brouhaha.com> "agent-s" writes: > Basically I'm programming a board game and I have to use a list of > lists to represent the board (a list of 8 lists with 8 elements each). > I have to search the adjacent cells for existing pieces and I was > wondering how I would go about doing this efficiently. Thanks You're getting a bunch of Pythonic suggestions which are easy to understand though not so efficient. If you're after efficiency you might look at a book like Welsh and Baczynskyj "Computer Chess II" for some techniques (warning, this is a rather old book though) and program in a closer-to-the-metal language. One common approach these days is "bit boards". Basically you represent the board state as a bunch of 64-bit words, one bit per square. So for checking occupancy, you'd have a word having the bits set for occupied squares. If you only want to check adjacent squares (king moves), you could have a bunch of bit masks (one for each square) with bits set only for the adjacent squares (similarly for bishop moves, rook moves, etc.) Then to check adjacency you'd mask off the appropriate bits for that square, then AND it against the occupancy word. Normally you'd have separate occupancy words for your own pieces and your opponent's. From jgrzebyta at NO.gazeta.pl.SPAM Sat Feb 3 15:54:10 2007 From: jgrzebyta at NO.gazeta.pl.SPAM (Jacol) Date: Sat, 03 Feb 2007 20:54:10 +0000 Subject: raise or not to raise [Newbie] Message-ID: Hello everybody! I found this: http://mail.python.org/pipermail/python-list/1999-July/006344.html My question concernings "callerFunc" and is more general what is difference between: try: raise "xyz" except "xyz": print "This is smthing" and simpler: print "This is smthing" Both give the same result. I don't understand manuals in this point. Thanks a lot, Jacek From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Feb 10 07:22:56 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 10 Feb 2007 13:22:56 +0100 Subject: Newbie Question References: Message-ID: <535rp0F1qoh5lU1@mid.individual.net> John wrote: > Visual Basic is also good. For what -- headache? 8) Regards, Bj?rn -- BOFH excuse #62: need to wrap system in aluminum foil to fix problem From george.sakkis at gmail.com Tue Feb 20 09:09:15 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 20 Feb 2007 06:09:15 -0800 Subject: Bypassing __setattr__ for changing special attributes In-Reply-To: <1171961673.334761.147300@q2g2000cwa.googlegroups.com> References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> <1171961673.334761.147300@q2g2000cwa.googlegroups.com> Message-ID: <1171980555.148297.196810@q2g2000cwa.googlegroups.com> On Feb 20, 3:54 am, "bruno.desthuilli... at gmail.com" wrote: > On 20 f?v, 05:39, "George Sakkis" wrote: > > > I was kinda surprised that setting __class__ or __dict__ goes through > > the __setattr__ mechanism, like a normal attribute: > > But __class__ and __dict___ *are* 'normal' attributes... Well, let alone for the fact that two leading and trailing underscores means 'special' in python, these attributes are not exactly what they seem to be, i.e. a 'normal' type or dict: >>> type(object.__dict__['__class__']) >>> type(type.__dict__['__dict__']) George From olsongt at verizon.net Wed Feb 21 14:06:05 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 21 Feb 2007 11:06:05 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> Message-ID: <1172084764.953839.238660@s48g2000cws.googlegroups.com> On Feb 20, 9:04 pm, "Jeff Templon" wrote: > yo, > > Bjorn, I am not sure I see why my post is bull crap. I think all you > are doing is agreeing with me. My post was entitled "Python 3.0 unfit > for serious work", you just indicated that the Linux distros will > agree with me, in order to be taken seriously, the distros will have > to include 2.x python for a very long time. If 3.0 and 2.x have any > serious degree of incompatibility, python will be a favorite subject > for religious rants and heated arguments for many people. And if we > don't manage to restrain our d evelopers from using features that force > us prematurely to move to 3.0 ... and don't underestimate what this > means, because this means other things will have to move as well, > which may have dependencies on yet other things like C++ library > versions ... then I would have to, for reasons of maintainability, > argue against continuing to allow python code development in the > project. I love python, but not enough to make 20+ people's lives > difficult. > > There are already people making this sort of argument in our project. > > JT I don't know the specifics of your app, but why does everyone insist that they need to use the 'system' python? At least one commercial python app I work with installs it's own completely independant version of python. For many apps where predictible behaviour is required you can install 'your' python, under /opt/myapp or /usr/local/myapp or whatever instead of python, python2.2, python3, etc. The downside is that you'll waste another 15Mb harddrive space, and you'll need to update your internal source tree 4 or 5 times when maintenance releases come out. Apologies if this sounds like a rant, I really mean it in a constructive way. -Grant From tjreedy at udel.edu Fri Feb 9 14:43:26 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Feb 2007 14:43:26 -0500 Subject: Referencing vars, methods and classes by name References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com><7xbqk52gt8.fsf@ruckus.brouhaha.com> <1171008606.012968.106680@p10g2000cwp.googlegroups.com> Message-ID: "Sagari" wrote in message news:1171008606.012968.106680 at p10g2000cwp.googlegroups.com... | Thanks to everyone for all the comments. I am migrating from PHP to | Python and I am looking for the means to port a controller code that | would, roughly speaking, call a certain method of a certain class | (both class and method names taken from user input). Putting aside | input verification (by the moment I perform the call input must have | been verified), what would be the recommended way of doing the trick? Use getattr(ob, name). Suppose mod = cname = mname = Then classobj = getattr(mod, cname) methobj = getattr(classobj, mname) However: Python generally uses methods for instance methods. Would you be creating an instance of the class (easily done -- inst = classobj(args)) before calling the method? If so, call methodobj(inst, args). If not, I wonder I you should really be using (Python) classes. Terry Jan Reedy From Ron at FascinatingElectronics.com Wed Feb 7 14:14:39 2007 From: Ron at FascinatingElectronics.com (Ron Jackson) Date: Wed, 07 Feb 2007 11:14:39 -0800 Subject: Pyserial example program error: win32file.SetupComm reports 'Incorrect function.' Message-ID: I am using Python 2.5 on Windows XP. I have installed Pyserial and win32all extensions. When I try to run the example program scan.py (included below), or any other program using pyserial, as soon as it hits the statement: s = serial.Serial(i) I get the error: Traceback (most recent call last): File "C:\Python25\Doc\PySerial Examples\scan.py", line 26, in for n,s in scan(): File "C:\Python25\Doc\PySerial Examples\scan.py", line 17, in scan s = serial.Serial(i) File "C:\Python25\Lib\site-packages\serial\serialutil.py", line 156, in __init__ self.open() File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 57, in open win32file.SetupComm(self.hComPort, 4096, 4096) error: (1, 'SetupComm', 'Incorrect function.') What do I need to do to fix this? Thanks for the help! -- Ron The example program scan.py (from the pyserial examples folder): ----------------------------------------------- #!/usr/bin/env python """Scan for serial ports. Part of pySerial (http://pyserial.sf.net) (C)2002-2003 The scan function of this module tries to open each port number from 0 to 255 and it builds a list of those ports where this was successful. """ import serial def scan(): """scan for available ports. return a list of tuples (num, name)""" available = [] for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() #explicit close 'cause of delayed GC in java except serial.SerialException: pass return available if __name__=='__main__': print "Found ports:" for n,s in scan(): print "(%d) %s" % (n,s) From thn at mail.utexas.edu Thu Feb 22 10:43:14 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 22 Feb 2007 07:43:14 -0800 Subject: list/get methods/attributes of a class? In-Reply-To: <1172158035.977029.188980@q2g2000cwa.googlegroups.com> References: <1172158035.977029.188980@q2g2000cwa.googlegroups.com> Message-ID: <1172158994.221743.254780@j27g2000cwj.googlegroups.com> Check out the dir() function. It does what you want, I think. Tom On Feb 22, 9:27 am, bkamr... at gmail.com wrote: > Hello, > Sorry guys for this newbie questions. But I wonder if there is a > standard or build-in method to know the methods of a class? > > I'm not originally a progrommer and I have worked with python/qt in a > basic level. Now I work a package which has many predefined classes > which I'm going to resue by importing them. I would like to know more > about each imported class, what methods exists and so on. Printing the > object or type(object) doesn't say so much. > > Any hint or helps is really appreciated! > /Ben From hg at nospam.org Tue Feb 13 03:16:02 2007 From: hg at nospam.org (hg) Date: Tue, 13 Feb 2007 09:16:02 +0100 Subject: float print formatting References: Message-ID: Neil Cerutti wrote: > The eighth-graders will be presenting Shakespeare's Hamlet in the church > basement on Friday at 7 p.m. The congregation is invited to attend this > tragedy. --Church Bulletin Blooper ;-) I like that ! hg From paul at subsignal.org Fri Feb 2 16:19:28 2007 From: paul at subsignal.org (paul) Date: Fri, 02 Feb 2007 22:19:28 +0100 Subject: asyncore DoS vulnerability In-Reply-To: <20070202165230.25807.916181291.divmod.quotient.7521@ohm> References: <17859.26973.898595.251480@montanaro.dyndns.org> <20070202165230.25807.916181291.divmod.quotient.7521@ohm> Message-ID: Jean-Paul Calderone schrieb: > It could ask the application. On the other hand, maybe asyncore remains in > a perfectly consistent state even after it raises this exception, and it is > already "asking" by letting this exception propagate up: if the application > is free to start the loop again after this happens, then it seems everything > is just fine; if some state becomes inconsistent, though, then asyncore should > probably do something more (assuming asyncore applications are supposed to be > able to be resistent to this kind of DoS). I second that, especially given the rather unspecific nature of "ValueError". Something like "EnvironmentError" or "OSError" would be more appropriate. Problem is: such a change would break lots of code... thanks Paul From aboudouvas at panafonet.gr Wed Feb 7 11:17:55 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 7 Feb 2007 08:17:55 -0800 Subject: Object type check Message-ID: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> Hi to all, in statically-types languages, let's say C# for example, we use polymorphism through interfaces. So we define an interface I with method M and then a class C that implements I interface and write code for the M method. So, if we have a function that takes a parameter of type I, we know before-hand that it will have an M method to call. But in dynamic languages this is not the case and we can pass whatever we want to that function. Assuming that someone writes a library in Python that other programmers will use, what is the correct way to check inside that function if the parameter passed is of the correct type, maybe "isinstance" BIF ? Thanks in advance! From rstupplebeen at gmail.com Mon Feb 26 09:26:43 2007 From: rstupplebeen at gmail.com (rstupplebeen at gmail.com) Date: 26 Feb 2007 06:26:43 -0800 Subject: a=b change b a==b true?? In-Reply-To: <1172498883.061877.123340@k78g2000cwa.googlegroups.com> References: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> <1172498883.061877.123340@k78g2000cwa.googlegroups.com> Message-ID: <1172500003.797450.7960@v33g2000cwv.googlegroups.com> All, It works great now. Thank you for all of your incredibly quick replies. Rob From fuzzyman at gmail.com Sun Feb 4 13:09:50 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Feb 2007 10:09:50 -0800 Subject: [ANN] ConfigObj 4.4.0 and Validate 0.2.3 Message-ID: <1170612590.875783.146320@v45g2000cwv.googlegroups.com> Updated versions of both `ConfigObj `_ and `Validate `_ are now available. * `ConfigObj 4.4.0 `_ * `Validate 0.2.3 `_ **ConfigObj** is a Python module for the simple reading and writing of config files. It has many features, whilst remaining easy to use. With the assistance of **Validate** it can validate a config file against a specification, and convert members to the expected type. Thanks to Nicola Larosa who implemented most of the fixes in this release. What is New in ConfigObj 4.4.0? ======================= * Made the import of compiler conditional so that ConfigObj can be used with IronPython. * Fix for Python 2.5 compatibilities. * String interpolation will now check the current section before checking DEFAULT sections. Based on a patch by Robin Munn. * Added Template-style interpolation, with tests, based on a patch by Robin Munn. * Allowed arbitrary indentation in the ``indent_type`` parameter. * Fixed Sourceforge bug #1523975 by adding the missing ``self`` What is New in Validate 0.2.3? ====================== Fixed validate doc to talk of boolean instead of bool; changed the ``is_bool`` function to ``is_boolean`` (Sourceforge bug #1531525). From domingo.aguilera at gmail.com Tue Feb 27 14:56:14 2007 From: domingo.aguilera at gmail.com (batok) Date: 27 Feb 2007 11:56:14 -0800 Subject: Has anybody tried jasper reports Message-ID: <1172606174.350865.188940@v33g2000cwv.googlegroups.com> Has anybody tried jasper reports ( java ) from python using jpype module ? It would be great to see an example of this. I've tried so many times with jpype but can't make this work out. Any hint would be appreciated. Tks. From paddy3118 at netscape.net Sat Feb 3 04:02:23 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 01:02:23 -0800 Subject: main In-Reply-To: References: <1170481031.861396.248680@j27g2000cwj.googlegroups.com> Message-ID: <1170493343.369984.279280@m58g2000cwm.googlegroups.com> On Feb 3, 8:51 am, "Gabriel Genellina" wrote: > En Sat, 03 Feb 2007 02:37:11 -0300, Paddy > escribi?: > > >> and what is > >> __name__ > >> __main__ > > >> use for in terms of Java? > > > With respect, (hehe), maybe you need to indicate that you've searched > > the Python documentation on __name__ and __main__? > > (Hah! I did that without saying RTFM. - Oh pooh! Fiddlesticks). > > Have you acually tried to do the search? The Python tutorial doesn't > menction that at all. And no one should expect that a beginner would have > to read section 26.3 on the Language Reference (__main__ -- Top-level > script environment) just to know what's that stuff about __name__ and > "__main__"... > > -- > Gabriel Genellina Good point. Googling for : tutorial "if __name__ = '__main__'" http://www.google.co.uk/search?hl=en&safe=off&q=tutorial+%22if +__name__+%3D+%27__main__%27%22&btnG=Search&meta= Gives this excellent page by the effbot: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm In fact, fatwallet should add its index page to his bookmarks: http://effbot.org/pyfaq/ Thanks Gabriel, - Paddy. From gagsl-py at yahoo.com.ar Tue Feb 6 19:49:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 21:49:11 -0300 Subject: Dictionary/Hash question References: <2adc542f0702061531g7504de83ob01b56933794a37e@mail.gmail.com> Message-ID: En Tue, 06 Feb 2007 20:31:17 -0300, Sick Monkey escribi?: > Even though I am starting to get the hang of Python, I continue to find > myself finding problems that I cannot solve. > I have never used dictionaries before and I feel that they really help > improve efficiency when trying to analyze huge amounts of data (rather > than > having nested loops). You are right, a list is not the right data structure in your case. But a dictionary is a mapping from keys to values, and you have no values to store. In this case one should use a set: like a list, but without ordering, and no duplicated elements. Also, it's not necesary to read all lines at once, you can process both files line by line. And since reading both files appears to be the same thing, you can make a function: def mailsfromfile(fname): result = set() with open(fname,'r') as finput: for line in finput: mails = some_regular_expression.findall(line) if mails: result.update(mails) return result mails1 = mailsfromfile(f1name) mails2 = mailsfromfile(f2name) for mail in mails1 & mails2: # & = set intersection, mails present on both files # write mail to output file -- Gabriel Genellina From joshua at eeinternet.com Thu Feb 22 15:21:35 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 22 Feb 2007 11:21:35 -0900 Subject: Creating a daemon process in Python References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Message-ID: <45ddeec1$0$16344$88260bb3@free.teranews.com> Benjamin Niemann wrote: >> What is the easiest way to create a daemon process in Python? Google >> says I should call fork() and other system calls manually, but is >> there no os.daemon() and the like? > You could try > Also, more discussion on the topic here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From sulsa at gazeta.pl Sat Feb 3 19:52:30 2007 From: sulsa at gazeta.pl (Sulsa) Date: Sun, 4 Feb 2007 01:52:30 +0100 Subject: Parser module Message-ID: <20070204015230.5b9345d8.sulsa@gazeta.pl> Is there some way to tell parser module (parser.suite function) not to stop parsing after it have found some syntax error but to proceed with parsing and construct the abstract syntax tree for rest of the code. From ptaku2 at tlen.pl Mon Feb 26 09:50:11 2007 From: ptaku2 at tlen.pl (w.p.) Date: 26 Feb 2007 06:50:11 -0800 Subject: wxPython - 2 x foldpanelbar with tree... Message-ID: <1172501410.183507.4300@p10g2000cwp.googlegroups.com> Hello! I have some trouble with my GUI. I have left panel with foldpanelbar, but i need one item but not collapsed - simple button. I split my left panel into two foldpanelbars with one button between. But a have trouble... Sorry for english :/ Simple code: #------------------------------------------------------------------------------------------------------ import sys import wx import wx.html as html import wx.lib.foldpanelbar as fpb import os import sys ID_New = wx.NewId() ID_Exit = wx.NewId() #------------------------------------------------------------------------------ class MyMDIChildFrame(wx.MDIChildFrame): #------------------------------------------------------------------------------ def __init__(self,parent,id,name=""): wx.MDIChildFrame.__init__(self,parent, id, name) self.InitGUI() #-------------------------------------------------------------------------- def InitGUI(self): #-------------------------------------------------------------------------- self.mainSplitter = wx.SplitterWindow(self, -1, style=wx.SP_NOBORDER) self.infoViewer = html.HtmlWindow(self.mainSplitter, -1, style=wx.NO_FULL_REPAINT_ON_RESIZE) #self.infoViewer.LoadPage("http://wxwidgets.org/manuals/2.5.4/ wx_wxbutton.html") self.infoViewer.SetPage("Here is some formatted text loaded from a string.") self.leftPanel = wx.Panel(self.mainSplitter) self.CreateFoldPanel() self.mainSplitter.Initialize(self.infoViewer) self.mainSplitter.SplitVertically(self.leftPanel, self.infoViewer, 180) #-------------------------------------------------------------------------- def CreateFoldPanel(self): #-------------------------------------------------------------------------- # foldpanel #1 self.foldPanel1 = fpb.FoldPanelBar(self.leftPanel, -1, wx.DefaultPosition, wx.Size(-1,-1), fpb.FPB_DEFAULT_STYLE, fpb.FPB_SINGLE_FOLD) self.bs = wx.BoxSizer(wx.VERTICAL) self.leftPanel.SetSizer(self.bs) self.leftPanel.SetBackgroundColour(wx.BLACK) item = self.foldPanel1.AddFoldPanel("Documents", collapsed=False) item.SetBackgroundColour(wx.RED) button1 = wx.Button(item, wx.ID_ANY, "In") button2 = wx.Button(item, wx.ID_ANY, "Out") self.foldPanel1.AddFoldPanelWindow(item, button1) self.foldPanel1.AddFoldPanelWindow(item, button2) item = self.foldPanel1.AddFoldPanel("Projects", collapsed=False) item.SetBackgroundColour(wx.BLUE) button1 = wx.Button(item, wx.ID_ANY, "Name") button2 = wx.Button(item, wx.ID_ANY, "Type") button3 = wx.Button(item, wx.ID_ANY, "Data") self.foldPanel1.AddFoldPanelWindow(item, button1) self.foldPanel1.AddFoldPanelWindow(item, button2) self.foldPanel1.AddFoldPanelWindow(item, button3) item = self.foldPanel1.AddFoldPanel("Contacts", collapsed=False) item.SetBackgroundColour(wx.CYAN) button1 = wx.Button(item, wx.ID_ANY, "Name") button2 = wx.Button(item, wx.ID_ANY, "Mail") button3 = wx.Button(item, wx.ID_ANY, "City") self.foldPanel1.AddFoldPanelWindow(item, button1) self.foldPanel1.AddFoldPanelWindow(item, button2) self.foldPanel1.AddFoldPanelWindow(item, button3) self.bs.Add(self.foldPanel1, 0, wx.EXPAND) # button button1 = wx.Button(self.leftPanel, wx.ID_ANY, "Calendar") self.bs.Add(button1, 0, wx.ALL|wx.EXPAND, 4) # foldpanel #2 self.foldPanel2 = fpb.FoldPanelBar(self.leftPanel, -1, wx.DefaultPosition, wx.Size(-1,-1), fpb.FPB_DEFAULT_STYLE, fpb.FPB_SINGLE_FOLD) item = self.foldPanel2.AddFoldPanel("Treenote", collapsed=True) item.SetBackgroundColour(wx.GREEN) self.tree = wx.TreeCtrl(item, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,wx.TR_HAS_BUTTONS| wx.TR_EDIT_LABELS| wx.TR_HIDE_ROOT)#| wx.TR_MULTIPLE#| wx.TR_HIDE_ROOT) self.foldPanel2.AddFoldPanelWindow(item, self.tree) self.LoadTree() self.bs.Add(self.foldPanel2, 0, wx.EXPAND) self.foldPanel1.Bind(fpb.EVT_CAPTIONBAR, self.OnPressCaption) self.foldPanel2.Bind(fpb.EVT_CAPTIONBAR, self.OnPressCaption) self.bs.Fit(self) self.bs.Layout() self.foldPanel1.Layout() self.foldPanel2.Layout() #-------------------------------------------------------------------------- def OnPressCaption(self, event): #-------------------------------------------------------------------------- self.bs.Layout() event.Skip() #-------------------------------------------------------------------------- def LoadTree(self): #-------------------------------------------------------------------------- self.root = self.tree.AddRoot("The Root Item") for x in range(15): child = self.tree.AppendItem(self.root, "Test item %d" % x) for y in range(5): last = self.tree.AppendItem(child, "test item %d-%s" % (x, chr(ord("a")+y))) for z in range(5): item = self.tree.AppendItem(last, "test item %d-%s-%d" % (x, chr(ord("a")+y), z)) #------------------------------------------------------------------------------ class MyParentFrame(wx.MDIParentFrame): #------------------------------------------------------------------------------ #-------------------------------------------------------------------------- def __init__(self): #-------------------------------------------------------------------------- wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size=(800,600)) self.winCount = 0 menu = wx.Menu() menu.Append(ID_New, "&New Window") menu.AppendSeparator() menu.Append(ID_Exit, "E&xit") menubar = wx.MenuBar() menubar.Append(menu, "&File") self.SetMenuBar(menubar) self.CreateStatusBar() self.my_canvas = None self.Bind(wx.EVT_MENU, self.OnNewWindow, id=ID_New) self.CreateNewWindow() #-------------------------------------------------------------------------- def OnNewWindow(self, evt): #-------------------------------------------------------------------------- self.CreateNewWindow() #-------------------------------------------------------------------------- def CreateNewWindow(self): #-------------------------------------------------------------------------- self.winCount = self.winCount + 1 win = MyMDIChildFrame(self, -1, "Child Window: %d" % self.winCount) win.Maximize() if __name__ == '__main__': class MyApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame = MyParentFrame() frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(False) app.MainLoop() From broek at cc.umanitoba.ca Thu Feb 8 17:28:21 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 08 Feb 2007 16:28:21 -0600 Subject: doctests for interactive functions In-Reply-To: <87veic9xb2.fsf@benfinney.id.au> References: <45CB77E3.3040108@cc.umanitoba.ca> <87veic9xb2.fsf@benfinney.id.au> Message-ID: <45CBA405.2080905@cc.umanitoba.ca> Ben Finney said unto the world upon 02/08/2007 03:03 PM: > Brian van den Broek writes: > >> Since the classes are for getting input interactively, a >> straightforward use of doctest is not going to work. (The tests >> won't run automatically.) I've come up with a way to make it work, >> but I would like to know from more experienced people if there are >> better ways that I am overlooking. > > One suggestion I can give is to decouple the task of "get input from > the user" and "validate this value against particular criteria". The > former should be so simple and *stupid* in its implementation that > very little can go wrong. The latter should be each of your validation > classes, or some re-implementation of them, that is non-interactive > and therefore easy to test. > > Then, the application simply uses these building blocks (that are now > well-tested and reliable) to do what it does: get input, then validate > that input, and possible ask for input again. > Hi Ben and all, Thanks for the suggestion. I'm a uni-lingual hobbyist Python programmer; consequently, I'm not positive I grasp your intent. In particular, as I want invalid input to cause a reprompting of the user, I am unsure how to decouple as you suggest. Can I run the rough structure of my code past you to see if it is in the vicinity of what you mean? (I have removed some details for sake of a short(er :-)) post.) My .get method looks like: def get(self, input_function=raw_input): while True: self._prompt_user() self._input = input_function() if self._is_valid_input(): break else: self._process_invalid_input() self._set_data() The base class ._prompt_user just displays a prompt. Individual subclasses might implement ._prompt_user to both display a prompt, and further information about constraints on valid inputs, or generate a menu of options on the fly, etc. Subclasses implement ._is_valid_input to return True if the input meets the desired constraints, False otherwise. So, YesNo._is_valid_input ensures that ._input.lower() is in ['y', 'n', 'yes', 'no'], for instance. ._process_invalid_input is implemented to provide useful feedback about invalid input. So, YesNo._process_invalid_input() emits a reminder that a value in ['y', 'n', 'yes', 'no'] is needed, for instance. ._set_data is usually implemented to just store the user's input as .data, but in some cases, it first subjects it to further processing. For instance YesNo._set_data sets .data to True if the user entered a yes value, False if they entered a no value. Is this the sort of thing you mean, or is this the sort of coupling you suggest I avoid? I do believe I can test each bit separately as the code is currently organized. My original concern was how to best create doctests that could also serve as illuminating examples in the documentation. In that context, I don't want implementation detail methods tested directly, but instead I desire to show the user how to actually use the class. (If it matters, I am writing the documentation in LaTeX, using doctest.testfile to run the examples in my .tex file.) Thanks and best, Brian vdB From spazziam at gmail.com Thu Feb 8 17:18:16 2007 From: spazziam at gmail.com (spazziam) Date: 8 Feb 2007 14:18:16 -0800 Subject: Python Newbie Message-ID: <1170973096.113660.264600@l53g2000cwa.googlegroups.com> SyntaxError: invalid syntax File "C:\Python23\vdrop2\final py\vdrop2.py", line 123 def INIT_HIGHS(): ^ SyntaxError: invalid syntax Why would this come up? From horpner at yahoo.com Mon Feb 5 08:22:40 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 5 Feb 2007 14:22:40 +0100 Subject: HELP NEEDED ... Regd. Regular expressions PyQt References: Message-ID: On 2007-02-03, vishal at veriwave.com wrote: > I am trying to work out a regular expression in a PyQt > environment for time in hh:mm:ss format. Any suggestions? After you find your time in hh:mm:ss format, be sure to check out time.strptime for a quick conversion. -- Neil Cerutti From worlman385 at yahoo.com Sun Feb 4 14:58:22 2007 From: worlman385 at yahoo.com (worlman385 at yahoo.com) Date: Sun, 04 Feb 2007 11:58:22 -0800 Subject: nokia s60 python code debugging with komodo Message-ID: anyway I can setup and debug nokia s60 python in komodo ( a python IDE )? thanks From baur79 at gmail.com Thu Feb 1 13:51:09 2007 From: baur79 at gmail.com (baur79) Date: 1 Feb 2007 10:51:09 -0800 Subject: mysqldb duplicate entry error handling In-Reply-To: References: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> Message-ID: <1170355868.967026.240510@h3g2000cwc.googlegroups.com> now it gives this error except IntegrityError, NameError: NameError: global name 'IntegrityError' is not defined any idea i have python 2.3.2 installed From greg at cosc.canterbury.ac.nz Thu Feb 8 01:11:15 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 08 Feb 2007 19:11:15 +1300 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: References: <45C9A137.8090009@v.loewis.de> Message-ID: <52vtc4F1pngrdU1@mid.individual.net> > Martin v. L?wis schrieb: > >>A partial class is a fragment of a class definition; >>partial classes allow to spread the definition of >>a class over several modules. When I want to do this, usually I define the parts as ordinary, separate classes, and then define the main class as inheriting from all of them. That avoids the monkeypatching-like behaviour of what you're doing -- the main class definition makes it clear what parts it's made up of -- and it uses only standard Python techniques, so it doesn't harbour any surprises. -- Greg From skpeterson at nospam.please.ucdavis.edu Sun Feb 11 07:42:27 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 04:42:27 -0800 Subject: Parsing HTML References: <1171148616.780656.13230@m58g2000cwm.googlegroups.com> Message-ID: "mtuller" on 10 Feb 2007 15:03:36 -0800 didst step forth and proclaim thus: > Alright. I have tried everything I can find, but am not getting > anywhere. I have a web page that has data like this: [snip] > What is show is only a small section. > > I want to extract the 33,699 (which is dynamic) and set the value to a > variable so that I can insert it into a database. [snip] > I have also tried Beautiful Soup, but had trouble understanding the > documentation. ==================== from BeautifulSoup import BeautifulSoup as parser soup = parser(""" LETTER 33,699 1.0 """) value = \ int(soup.find('td', headers='col2_1').span.contents[0].replace(',', '')) ==================== > Thanks, > Mike Hope that helped. This code assumes there aren't any td tags with header=col2_1 that come before the value you are trying to extract. There's several ways to do things in BeautifulSoup. You should play around with BeautifulSoup in the interactive prompt. It's simply awesome if you don't need speed on your side. -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From laurent.pointal at limsi.fr Mon Feb 12 09:40:04 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 12 Feb 2007 15:40:04 +0100 Subject: Help with Optimization of Python software: real-time audio controller In-Reply-To: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> References: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> Message-ID: craiglewiston at gmail.com a ?crit : > As mentioned above, my application deals with music training. I have a > Tkinter GUI, which communicates via pyserial with an external device I > built myself. The code reads in a MIDI file and converts the song to > "output data " for the external device and the GUI, all adjusted to > the user-selected tempo. While the MIDI file is playing, there are 4 > main actions the code must take: > 1) Send "output data" signals out to the external hardware. > 2) Poll the input from the external hardware device for incoming > keypresses. If detected, then the play the sound corresponding to > that key. > 3) Start and keep a metronome running for the durations of the song. > 4) Update GUI > > I'm able to get all the above "accomplished" through the use of > threads and a top-level loop (for updating the Tkinter GUI - if > you've worked with threads and Tkinter, then you know that you can't > update a Tkinter GUI from a thread, but instead have to do it on the > top level loop). > Also, just for reference, here's a list of the modules I'm using and > my system info: > Audio: SndObj > Ser com: pyserial > GUI: Tkinter > System: Apple PowerBook G4 (PowerPC), Mac OS 10.4, Python 2.4.4 > > Thanks, > Craig Lewiston > You may take a look at PureData, interface is in TCL/Tk, but realtime sound management layers are in compiled C. "just" copy it using Python as high level language... I dont think Python itself just using scripting can achieve needed performance for *realtime* (like) audio. http://www.puredata.info/ http://www-crca.ucsd.edu/~msp/ From giles_brown at hotmail.com Sun Feb 4 05:38:15 2007 From: giles_brown at hotmail.com (Giles Brown) Date: 4 Feb 2007 02:38:15 -0800 Subject: ctypes.com.IUnknown In-Reply-To: <45C4F24C.7060204@jessikat.plus.net> References: <45C4F24C.7060204@jessikat.plus.net> Message-ID: <1170585495.897502.148500@v45g2000cwv.googlegroups.com> On 3 Feb, 20:36, Robin Becker wrote: > I find that ctypes.com has disappeared from the ctypes extension bundled > with Python 2.5. I think I only need the IUnknown, I was playing with > building a dialog using venster, but it needs IUnknown, STDMETHOD, > HRESULT, GUID from ctypes.com. Any ideas what should replace those or is > venster now too old to bother with. > -- > Robin Becker What about downloading the spin-off library? http://sourceforge.net/projects/comtypes/ (I think this was created to move the com stuff out of ctypes?) Giles From gagsl-py at yahoo.com.ar Wed Feb 14 12:46:04 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 14:46:04 -0300 Subject: rot13 in a more Pythonic style? References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <1171472657.567241.302690@h3g2000cwc.googlegroups.com> Message-ID: En Wed, 14 Feb 2007 14:04:17 -0300, Andy Dingley escribi?: > I still don't understand what a lambda is _for_ in Python. I know what > they are, I know what the alternatives are, but I still haven't found > an instance where it permits something novel to be done that couldn't > be done otherwise (if maybe not so neatly). A lambda is a shorthand for a simple anonymous function. Any lambda can be written as a function: lambda args: expression is the same as: def __anonymous(args): return expression (but the inverse is not true; lambda only allows a single expression in the function body). Except for easy event binding in some GUIs, deferred argument evaluation, and maybe some other case, the're not used much anyway. Prior common usage with map and filter can be replaced by list comprehensions (a lot more clear, and perhaps as fast - any benchmark?) -- Gabriel Genellina From luismgz at gmail.com Wed Feb 28 14:26:41 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Feb 2007 11:26:41 -0800 Subject: class declaration shortcut Message-ID: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> I've come across a code snippet in www.rubyclr.com where they show how easy it is to declare a class compared to equivalent code in c#. I wonder if there is any way to emulate this in Python. The code is as follows: Person = struct.new( :name, :birthday, :children) I tried something like this, but it's nothing close to what I'd like: def klass(table, *args): cls = new.classobj(table, (), {}) for i in args: setattr(cls, i, i) return cls But this above is not what I want. I guess I should find a way to include the constructor code inside this function, but I don't know if this is possible. Also, I wonder if there is a way to use the variable name in order to create a class with the same name (as in "Person"above). Well, if anyone has an idea, I'd like to know... Luis From edreamleo at charter.net Fri Feb 16 07:47:38 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 06:47:38 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> Message-ID: > There is also the 2to3 converter. The aim is that this will be effective enough that coders should be able to maintain a 2.X (2.6 ?) codebase, run it through 2to3 and have the result run unchanged on Python 3. That way there will be no need to maintain two code bases. I have offered a proof that the converter must change print to print2 (or some other name) in order to maintain a common code base. How much clearer can I be? If a common code base is desired, it *is* the end of print Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From gherron at islandtraining.com Wed Feb 7 15:50:49 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 07 Feb 2007 12:50:49 -0800 Subject: Simple SVN/CVS-like library in Python? In-Reply-To: References: Message-ID: <45CA3BA9.9030703@islandtraining.com> Andrea Gavana wrote: > Hi All, > > in our office we work with quite complex input files for a > reservoir simulator. Those files have thousands of keywords, switches, > sub-keywords and whatever. Every time a modification is requested, we > modify the input file and re-run the simulator. Obviously, the > possible modifications are innumerable: so, after few months, we lose > the records of all the changes we made during time and we don't have > anymore a clear history of our work. This can be a problem, as > sometimes it happens that an old input file is requested by > collegues/sub-companies, and it is a pain to retrieve the correct file > and results. > So, I have written a GUI in wxPython that could help us in tracking > the history, but I was wondering if there exists a small and simple > SVN/CVS-like library in Python that may help us in a better way, > storing modifications/changes and showing which input file are the > "children" of (are derived from) another input file (older). > But I am open to all possible suggestions to improve/modify the > software, as this is an area in which my experience is about nothing > above zero. > > Why not just use SVN? (Or any other version control system for that matter.) Subversion would allow you to save changes, create and merge branches of changes, compare any two revisions, label (tag) specific revisions, retrieve by tag or date, ... It's got far more feature than you're likely to get into any Python scripts in the near future. (Plus it's scritable from Python so you can automate some tasks if you wish. Gary Herron > Thank you very much for every hint. > > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.virgilio.it/infinity77/ > From tiarno at sas.com Fri Feb 23 13:57:11 2007 From: tiarno at sas.com (Tim Arnold) Date: Fri, 23 Feb 2007 13:57:11 -0500 Subject: Finding non ascii characters in a set of files References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:pan.2007.02.23.18.41.03.317525 at gmx.net... > In , Tim Arnold wrote: > > .... Untested: > > import os, sys, codecs > > def checkfile(filename): > f = codecs.open(filename,encoding='ascii') > > try: > for num, line in enumerate(f): > pass > except UnicodeError: > print 'problem: line %d' % num > > f.close() > > Ciao, > Marc 'BlackJack' Rintsch Thanks Marc, That looks much cleaner. I didn't know the 'num' from the enumerate would persist so the except block could report it. thanks again, --Tim From fatwallet961 at yahoo.com Sat Feb 3 00:48:45 2007 From: fatwallet961 at yahoo.com (fatwallet961 at yahoo.com) Date: Fri, 02 Feb 2007 21:48:45 -0800 Subject: python bracket Message-ID: there is no bracket in python how can i know where a loop or a function ends? From grante at visi.com Tue Feb 20 10:05:29 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 20 Feb 2007 15:05:29 -0000 Subject: Weird result returned from adding floats depending on order I add them References: Message-ID: <12tm3hpom0tkqc7@corp.supernews.com> On 2007-02-20, joanne matthews (RRes-Roth) wrote: > I'm getting different results when I add up a list of floats depending > on the order that I list the floats. That's how floats work. > For example, the following returns > False: > def check(): > totalProp=0 > inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1] > for each in inputs: > > totalProp+=each > print "totalProp=",totalProp > if totalProp != 1: Floating point operations are not exact. This test requires them to be. [...] > Can anyone tell me whats going on IEEE floating point can not exactly represent 0.2 nor 0.1, so you get approximations. > and how I can avoid the problem. Don't use floating point if you expect exact results. -- Grant Edwards grante Yow! I feel better about at world problems now! visi.com From newsuser at stacom-software.de Thu Feb 1 12:59:02 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Thu, 01 Feb 2007 18:59:02 +0100 Subject: Heap problems in Mulithreaded Python extension Message-ID: Hi, I'm near the ground and need help. I'm building a multithreaded extension with boost.python. python extension ----------------------------------------------------- import extension extension.init() -> PyEval_InitThreads(); setup 3 threads (pthreads) and do a lot of things, but no python api calls while true: time.sleep(0.1) PyGILState_STATE gGILState; gGILState = PyGILState_Ensure(); (...) // Do python API calls PyGILState_Release(gGILState); So my questions: - Is it enough to do the following in the extension, regardless wich thread it does ? PyGILState_STATE gGILState; gGILState = PyGILState_Ensure(); (...) // Do python API calls PyGILState_Release(gGILState); What happens is, that inside the extension (C++) from time to time _CrtIsValidHeapPointer(...) fails. Any comments/experience on "python and threaded extensions" is very welcome. Alexander From greg at cosc.canterbury.ac.nz Thu Feb 22 18:13:53 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 23 Feb 2007 12:13:53 +1300 Subject: Local class variables? (mod_python problem) In-Reply-To: References: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> Message-ID: <546mhpF1uaf6rU1@mid.individual.net> Rory Campbell-Lange wrote: > class Part (object): > totalgia = 0 > def __init__(self, gia): > self.gia = gia # gross internal area > self.giaratio = 0 > Part.totalgia += self.gia > > if __name__ == '__main__': > p1 = Part(20) > p2 = Part(30) > for p in p1, p2: > p.addavgbm() > print p You need another class, such as PartGroup, to keep track of the totalgia of a group of parts (as an instance variable, not a class variable). Then you can create a new instance of it in your __main__ code, e.g. class PartGroup(object): def __init__(self): self.parts = [] self.totalgia = 0 class Part(object): def __init__(self, group, gia): self.gia = gia group.parts.append(self) group.gia += gia if __name__ == "__main__": parts = PartGroup() p1 = Part(parts, 10) p2 = Part(parts, 20) print parts.totalgia A possible variation would be not to store the totalgia at all, but have a function or method that calculates it from the list of parts when you need it. Whether that's better or not will depend on how frequently you need the value. -- Greg > > totalgia keeps incrementing when this code is used under mod_python. > > We most certainly are in 'murky waters of accidental concurrent access'. > A life vest would be gratefully received. > > Kind regards > Rory > > > On 22/02/07, Rory Campbell-Lange (rory at campbell-lange.net) wrote: > >>We have a set of classes using static methods to retain reference >>variables between operations. The problem is that the static variables >>are not reset between operations when used through mod_python. >> >>Although it is possible to reset the class variables between invocations >>of the system, this has the potential of 'wiping out' these variables >>when another user is using the system. >> >>Is there a way of getting the equivalent of 'local class variables'? In >>other words, a way of making 'print a' and 'print b' below provide the >>same output? > > > On 22/02/07, Piet van Oostrum (piet at cs.uu.nl) wrote: > >>>>>>>Rory Campbell-Lange (RC) wrote: > > >>There are several errors in your python code: quite a number of comma's >>have to be replaced by semicolons (or newlines), and there is a spurious >>comma. > > > > On 22/02/07, Diez B. Roggisch (deets at nospam.web.de) wrote: > >>Rory Campbell-Lange wrote: > > >>It's very unclear what you mean here, and I'm additionally under the >>impression that you are deep in the murky waters of accidential >>concurrent access errors here. > > > From duncan.booth at invalid.invalid Fri Feb 23 08:23:23 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Feb 2007 13:23:23 GMT Subject: Finding a tuple in a tuple References: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> Message-ID: Philipp Pagel wrote: > Another way to go instead of using sets, although probably less elegant: > >>>> True in [x in t1 for x in t2] > True >>>> True in [x in t1 for x in t3] > True >>>> True in [x in t1 for x in t4] > False >>>> True in [x in t1 for x in t5] > False Slightly more elegant for Python 2.5 users: >>> any(x in t1 for x in t2) True >>> any(x in t1 for x in t3) True >>> any(x in t1 for x in t4) False >>> any(x in t1 for x in t5) False From pavlovevidence at gmail.com Thu Feb 1 09:14:40 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 1 Feb 2007 06:14:40 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: References: <1170275061.786779.74910@a34g2000cwb.googlegroups.com> Message-ID: <1170339280.420231.304370@s48g2000cws.googlegroups.com> On Jan 31, 3:37 pm, Jean-Paul Calderone wrote: > On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: > > >Michele Simionato wrote: > >> On Jan 31, 5:23 pm, "Frank Potter" wrote: > >> > I want to find a multithreaded downloading lib in python, > >> > can someone recommend one for me, please? > >> > Thanks~ > > >> Why do you want to use threads for that? Twisted is the > >> obvious solution for your problem, > > >Overkill? Just to download a few web pages? You've got to be > >kidding. > > Better "overkill" (whatever that is) than wasting time re-implementing > the same boring thing over and over for no reason. "I need to download some web pages in parallel." "Here's tremendously large and complex framework. Download, install, and learn this large and complex framework. Then you can write your very simple throwaway script with ease." Is the twisted solution even shorter? Doing this with threads I'm thinking would be on the order of 20 lines of code. Carl Banks From a.schmolck at gmail.com Mon Feb 5 10:57:20 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 15:57:20 +0000 Subject: in place-ness of list.append References: Message-ID: Alexander Schmolck writes: > skip at pobox.com writes: > > > >>>>> "Bart" == Bart Van Loon writes: > > > > >> Such an operation will be O(N**2), > > > > Bart> why is that? > > > > The a[:] operation makes a copy of a (as will the x = a + [n] idiom). > > I'm pretty confident append itself (and a+[n]) are linear in N=len(a) since Sorry -- I just see that I missed your other post. 'as From bfritz at sprynet.com Sat Feb 17 18:40:30 2007 From: bfritz at sprynet.com (Captain) Date: Sat, 17 Feb 2007 23:40:30 GMT Subject: WHAT IS THIS? References: Message-ID: Thanks for the responses. I'll just leave it. Sorry about uppercase subject line. "Captain" wrote in message news:aLwBh.2502$_73.294 at newsread2.news.pas.earthlink.net... > Just bought a new PC with Windows XP Media Edition. I have two entries in > the "Add or Remove Programs" section of Control Panel, but there is no > corresponding item in the Start Menu. One entry says: Python 2.2.3 and > the other says: Python 2.2 pywin32 extensions (build203).. The size for > each is 29.28mb. I gather Python is a programming language, but I am > wondering why it was installed on my PC, and is it safe to remove it? I > have no intention of learning the program. Thanks in advance > From mobiledreamers at gmail.com Tue Feb 13 22:56:14 2007 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 13 Feb 2007 19:56:14 -0800 Subject: barcode generation Message-ID: Hi I want to generate barcode based on an input which can be numbers or numbers+alphabets. How do I do this? Is there any library that will doo this? thanks mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Wed Feb 7 11:42:42 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 7 Feb 2007 08:42:42 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <1170863305.476942.318420@s48g2000cws.googlegroups.com> References: <45C9A137.8090009@v.loewis.de> <1170863305.476942.318420@s48g2000cws.googlegroups.com> Message-ID: <1170866562.434637.209970@l53g2000cwa.googlegroups.com> On Feb 7, 10:48 am, "Michele Simionato" wrote: > > Martin v. L?wis schrieb: > > > > I'm happy to announce partial 1.0; a module to implement > > > partial classes in Python. It is available from > > > >http://cheeseshop.python.org/pypi/partial/1.0 > > > > A partial class is a fragment of a class definition; > > > partial classes allow to spread the definition of > > > a class over several modules. One location serves > > > as the original definition of the class. > > This looks the same as Ruby classes, right? > I don't like class definitions to be scattered in different files, for > the same reason > I don't like excessive inheritance, it is too easy to get lost when > debugging > code written by somebody else. But probably I am just overreacting due > to my > exposure to Zope ... The big difference from Ruby is that this can't extend most built- ins. Which means that a lot of Ruby horror stories wouldn't apply. Carl Banks From attn.steven.kuo at gmail.com Thu Feb 8 13:32:48 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 8 Feb 2007 10:32:48 -0800 Subject: Strings in Python In-Reply-To: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> References: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> Message-ID: <1170959568.410295.285410@l53g2000cwa.googlegroups.com> On Feb 8, 8:28 am, "Johny" wrote: > Playing a little more with strings, I found out that string.find > function provides the position of > the first occurance of the substring in the string. > Is there a way how to find out all substring's position ? > To explain more, > let's suppose > > mystring='12341' > import string > > >>> string.find(mystring ,'1') > > 0 > > But I need to find the possition the other '1' in mystring too. > Is it possible? > Or must I use regex? In this case, you can use: mystring = '12341' indices = [ _ for _ in range(len(mystring)) if mystring[_] == '1' ] print indices -- Hope this helps, Steven From horpner at yahoo.com Thu Feb 15 11:37:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Feb 2007 17:37:18 +0100 Subject: f---ing typechecking References: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Message-ID: On 2007-02-14, Farshid Lashkari wrote: > Szabolcs Nagy wrote: >>>>> L=[1] >>>>> L.extend((1,)) >>>>> L >> [1, 1] > > Are list.extend() and list concatenation supposed to behave > differently? I always thought concatenation was just shorthand > for calling extend(). They are different. list.extend() mutates the list, returning None, while the + operator returns a new, concatenated list. += on the other hand works very similarly to list.extend(). However: >>> [1, 2].extend([3]) >>> [1, 2] += [3] SyntaxError: augmented assign to list literal or comprehension not possible > It seems like the '+' operator for lists should accept any > iterable for the right side argument to be consistent with > extend() and the '+=' operator. += will only perform the operation in place "whenever possible", so there are objects for which a conversion to .extend wouldn't work, and you'd get an actual call of the + operation followed by the assignment operation. -- Neil Cerutti I don't know what to expect right now, but we as players have to do what we've got to do to make sure that the pot is spread equally. --Jim Jackson From gagsl-py at yahoo.com.ar Sat Feb 10 04:27:31 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 06:27:31 -0300 Subject: Embedding, "import site", PYTHONHOME, and an old, old issue References: Message-ID: En Sat, 10 Feb 2007 03:57:05 -0300, Jim Hill escribi?: > I want to do a simple embed, so I've followed the example in the > Extending and Embedding documentation: > > In the .c file, > > #include > > int routine() { > Py_Initialize(); > PyRun_SimpleString("from time import time,ctime\n" > "print 'Today is',ctime(time())\n"); > Py_Finalize(); > return 0; > } (Why routine() and not main()? Unfortunately you can't repeteadly initialize/finalize the interpreter, you must do that only once.) > The code compiles just fine, but when I execute it the call to > Py_Initialize() comes back with: > > 'import site' failed; use -v for traceback > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named time Try this: PyRun_SimpleString("import sys; print sys.path"); to see where Python expects to find its library (or call the Py_GetPath function). You may need to call Py_SetProgramName (before Py_Initialize) so it can find where the standard library resides. At least for testing purposes, you can copy your executable into the same directory where Python is installed. -- Gabriel Genellina From deets at nospam.web.de Fri Feb 23 08:39:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Feb 2007 14:39:01 +0100 Subject: jython import search path References: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> <1172105604.157543.191450@k78g2000cwa.googlegroups.com> <5457q8F1rqvu1U1@mid.uni-berlin.de> <1172174634.566542.312360@h3g2000cwc.googlegroups.com> Message-ID: <54893lF1udktaU1@mid.uni-berlin.de> > Accepted strategy? It doesn't seem very portable. It assumes that > everyone puts their library > modules in the exact same place. Or do they just figure that changing > the sys.path.append > line is easy enough? Portability has nothing to do with it. If you arrange your project in a way that these paths can be figured out at runtime, it's fine. If not, you might need some installation routine that will figure them out when installing the software, hard-coding such paths in some way (as parameter lists or whatsoever) >> java -Dpython.path= > > I'm not using Java at all. I just want to generate Java bytecode for > purposes of code analysis > by existing tools. If you are using jython, you are using java. Diez From nagle at animats.com Wed Feb 7 03:37:50 2007 From: nagle at animats.com (John Nagle) Date: Wed, 07 Feb 2007 00:37:50 -0800 Subject: sgmllib bug in Python 2.5, works in 2.4. In-Reply-To: References: Message-ID: John Nagle wrote: > (Was prevously posted as a followup to something else by accident.) > > I'm running a website page through BeautifulSoup. It parses OK > with Python 2.4, but Python 2.5 fails with an exception: > > Traceback (most recent call last): > File "./sitetruth/InfoSitePage.py", line 268, in httpfetch > self.pagetree = BeautifulSoup.BeautifulSoup(sitetext) # parse into > tree form > File "./sitetruth/BeautifulSoup.py", line 1326, in __init__ > BeautifulStoneSoup.__init__(self, *args, **kwargs) > File "./sitetruth/BeautifulSoup.py", line 973, in __init__ > self._feed() > File "./sitetruth/BeautifulSoup.py", line 998, in _feed > SGMLParser.feed(self, markup or "") > File "/usr/lib/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib/python2.5/sgmllib.py", line 291, in parse_starttag > self.finish_starttag(tag, attrs) > File "/usr/lib/python2.5/sgmllib.py", line 340, in finish_starttag > self.handle_starttag(tag, method, attrs) > File "/usr/lib/python2.5/sgmllib.py", line 376, in handle_starttag > method(attrs) > File "./sitetruth/BeautifulSoup.py", line 1416, in start_meta > self._feed(self.declaredHTMLEncoding) > File "./sitetruth/BeautifulSoup.py", line 998, in _feed > SGMLParser.feed(self, markup or "") > File "/usr/lib/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib/python2.5/sgmllib.py", line 285, in parse_starttag > self._convert_ref, attrvalue) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: > ordinal > not in range(128) > > The code that's failing is in "_convert_ref", which is new in > Python 2.5. > That function wasn't present in 2.4. I think the code is trying to > handle single quotes inside of double quotes, or something like that. > > To replicate, run > > http://www.bankofamerica.com > or > http://www.gm.com > > through BeautifulSoup. > > Something about this code doesn't like big companies. Web sites of smaller > companies are going through OK. > > Also reported as a bug: > > [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 Found the problem and updated the bug report with a fix. But someone else will have to check it in. There's a place in SGMLParser where someone assumed that values 0..255 were valid ASCII characters. But in fact the allowed range is 0..127. The effect is that Unicode strings containing values between 128 and 255 will blow up SGMLParser. In fact, you can even make this happen with an ASCII source file by using an HTML entity which has a Unicode representation between 128 and 255, (such as "§"), then using something Unicode-oriented like BeautifulSoup on it. John Nagle From exarkun at divmod.com Thu Feb 1 09:20:37 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Feb 2007 09:20:37 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170339280.420231.304370@s48g2000cws.googlegroups.com> Message-ID: <20070201142037.25807.225507165.divmod.quotient.6201@ohm> On 1 Feb 2007 06:14:40 -0800, Carl Banks wrote: >On Jan 31, 3:37 pm, Jean-Paul Calderone wrote: >> On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: >> >> >Michele Simionato wrote: >> >> On Jan 31, 5:23 pm, "Frank Potter" wrote: >> >> > I want to find a multithreaded downloading lib in python, >> >> > can someone recommend one for me, please? >> >> > Thanks~ >> >> >> Why do you want to use threads for that? Twisted is the >> >> obvious solution for your problem, >> >> >Overkill? Just to download a few web pages? You've got to be >> >kidding. >> >> Better "overkill" (whatever that is) than wasting time re-implementing >> the same boring thing over and over for no reason. > >"I need to download some web pages in parallel." > >"Here's tremendously large and complex framework. Download, install, >and learn this large and complex framework. Then you can write your >very simple throwaway script with ease." > >Is the twisted solution even shorter? Doing this with threads I'm >thinking would be on the order of 20 lines of code. > The /already written/ solution I linked to in my original response was five lines shorter than that. Hmm. Jean-Paul From gagsl-py at yahoo.com.ar Fri Feb 16 23:56:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 01:56:49 -0300 Subject: how to use Dispatch to open an application in win32com.client References: <1171679786.355275.191860@h3g2000cwc.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 23:36:26 -0300, vithi escribi?: > I am trying to launch an application. When I try like that > When I try like that Excel is opening > import win32com.client > object = win32com.client.Dispatch("Excel.Application") > object.Visible = 1 > > But when I try my application which is QeepIt.exe > which is in the c:\ drive it is not running > Any body tell me how to give path to open an exectable application in > Dispatch modules > I try like that > object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") > It give an error. The above code is used to launch a COM server registered under the name "Excel.Application" and then control it. If you don't know what a COM server is, surely your application can't be used this way. For launching another program, perhaps sending it some text, and capturing its output, look at the subprocess module. If you are only interested in executing it, with no additional communication, os.system() may be enough. -- Gabriel Genellina From tombry at cisco.com Mon Feb 26 15:46:29 2007 From: tombry at cisco.com (Tom Bryan) Date: Mon, 26 Feb 2007 15:46:29 -0500 Subject: starship.python.net is down In-Reply-To: <1172072586.601115.304110@s48g2000cws.googlegroups.com> References: <1171634223.13643@sj-nntpcache-2.cisco.com> <1172072586.601115.304110@s48g2000cws.googlegroups.com> Message-ID: <1172522790.976949@sj-nntpcache-2.cisco.com> Matthew.Cahn at gmail.com wrote: > Any news on starship.python.net? It still seems to be down. Yes. Unfortunately, there may be a hardware problem. Stefan, the admin who owns the hosted machine, is working with the host company to determine what's going on. I think that they are still in the "investigation" stage at the moment, so it's hard to give an estimate of when the problem will be fixed. Thanks for your patience, ---Tom From sjmachin at lexicon.net Mon Feb 12 08:29:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 12 Feb 2007 05:29:22 -0800 Subject: string.replace non-ascii characters In-Reply-To: References: Message-ID: <1171286962.105515.103150@a34g2000cwb.googlegroups.com> On Feb 12, 11:44 pm, Deniz Dogan wrote: > Duncan Booth wrote: > > "Gabriel Genellina" wrote in triplicate: > > >> If I were paid for the number of lines *written* that would not be a > >> great deal :) > > > You don't by any chance get paid by the number of posts to c.l.python? > > I was thinking the same thing. O maker of the monstrous millisecond-muncher, I was thinking that you were paid by the number of times that you typed 3600000 :-) From bignose+hates-spam at benfinney.id.au Thu Feb 1 01:18:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 17:18:21 +1100 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170308178.823986.322700@h3g2000cwc.googlegroups.com> Message-ID: <87mz3ytn82.fsf@benfinney.id.au> "Paddy" writes: > On Feb 1, 2:42 am, krypto.wiz... at gmail.com wrote: > > How to divide a number by 7 efficiently without using - or / operator. > > >>> int.__div__(14,2) > 7 > >>> > > Not a minus or division operator in sight ;-) I salute you, sir. That's the perfect answer to the boneheaded constraints of the problem :-) -- \ "What I resent is that the range of your vision should be the | `\ limit of my action." -- Henry James | _o__) | Ben Finney From codecraig at gmail.com Wed Feb 28 12:46:20 2007 From: codecraig at gmail.com (abcd) Date: 28 Feb 2007 09:46:20 -0800 Subject: pyHook or SetWindowsHookEx In-Reply-To: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> References: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> Message-ID: <1172684780.613003.30350@z35g2000cwz.googlegroups.com> anyone? From arkanes at gmail.com Fri Feb 16 10:59:11 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 16 Feb 2007 09:59:11 -0600 Subject: why I don't like range/xrange In-Reply-To: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: <4866bea60702160759w36cad825s3e78b975d41ae644@mail.gmail.com> On 16 Feb 2007 07:30:15 -0800, stdazi wrote: > Hello! > > Many times I was suggested to use xrange and range instead of the > while constructs, and indeed, they are quite more elegant - but, after > calculating the overhead (and losen flexibility) when working with > range/xrange, and while loops, you get to the conclusion that it isn't > really worth using range/xrange loops. > > I'd like to show some examples and I'll be glad if someone can suggest > some other fixes than while a loop :-) > > a) range overfllow : > > > for i in range(0, 1 << len(S)) : > ..... > OverflowError: range() result has too many items > > ok, so we fix this one with xrange ! > > b) xrange long int overflow : > > for i in xrange(0, 1 << len(S)) : > ........ > OverflowError: long int too large to convert to int > xrange should be able to handle this. It's probably worth a bug report. > Next thing I miss is the flexibility as in C for loops : > > for (i = 0; some_function() /* or other condition */ ; i++) > You'd use a regular for or a while loop here, without the loop index. > or, > > for (i = 0 ; i < 10 ; i++) > i = 10; > This doesn't do anything as written. For all reasonable uses of it, you can do it the same way in Python. Writing C code in Python is a waste of time and an exercise in frustration. > > I don't think range/xrange sucks, but I really think there should be > some other constructs to improve the looping flexibility. Other thing > may be, that I just miss an equally elegant alternative that's why I'd > like to hear some suggestions on how to fix the above issues.. (btw, > I've already browsed the archives related to my issue,but i don't see > any good solution) > Enumeration over range() and xrange() is rare in Python. loops like: data = [...] for ii in xrange(len(data)): datum = data[ii] are a wart. Enumerate over whatever you're going to work with. In some cases, you want the index and the item. Use enumerate for that: for index, datum in enumerate(data): .... From nagle at animats.com Fri Feb 2 02:53:05 2007 From: nagle at animats.com (John Nagle) Date: Fri, 02 Feb 2007 07:53:05 GMT Subject: mysqldb duplicate entry error handling In-Reply-To: <13Awh.21950$X72.6049@newsread3.news.pas.earthlink.net> References: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> <13Awh.21950$X72.6049@newsread3.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber wrote: > On 1 Feb 2007 10:17:31 -0800, "baur79" declaimed the > following in comp.lang.python: >>IntegrityError: (1062, "Duplicate entry 'email at domain.com' for key 1") > > So show us the schema for the database... My take: Your database > ALREADY HAS a record with that "email at domain.com" value AND emails.email > is defined as a unique key field. Right. That's not a bug; it's supposed to do that when you try to add a duplicate. What do you want to happen? If you want to allow duplicates, remove the UNIQUE on that field from the schema. If you want the new entry to replace the old entry, use REPLACE instead of INSERT. If you just want to detect the problem, provide import MySQLdb kmysqlduplicateentry = 1062 # MySQL error code when INSERT finds a duplicate try : ... # do INSERT except MySQLdb.IntegrityError, message: errorcode = message[0] # get MySQL error code if errorcode == kmysqlduplicateentry : # if duplicate ... # handle duplicate else: raise # unexpected error, reraise John Nagle From S.Mientki-nospam at mailbox.kun.nl Tue Feb 6 15:56:16 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 06 Feb 2007 21:56:16 +0100 Subject: electronics and python In-Reply-To: <1170787134.923982.197760@v33g2000cwv.googlegroups.com> References: <1170787134.923982.197760@v33g2000cwv.googlegroups.com> Message-ID: <202af$45c8eb63$d443bb3a$10437@news.speedlinq.nl> lee wrote: > Hi guys.....Is there any software written using python for > electronics.....i mean any simulation software or something?? > There are a few starts, (I can't find my notes right now, so from my head) - there's a 68c11 simulator - there's a spice implementation or at least a good coupling - the most promising combination is Python+Modelica, some seem to have it workin - and there's another one, can't remember as an exercise I tried to build a PIC simulator, works, but it is slow. cheers, Stef Mientki From paddy3118 at netscape.net Sat Feb 3 04:17:19 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 01:17:19 -0800 Subject: Regd. Kodos In-Reply-To: References: Message-ID: <1170494239.351279.302030@m58g2000cwm.googlegroups.com> On Feb 3, 8:59 am, vis... at veriwave.com wrote: > I am trying to use Kodos..but not getting thru'..dont know whats goin > on..does anyone have a regular expression for time in hh:mm:ss > -Vishal Well, with just knowing the above, the following raw string when used as a regular expression will capture the hh,mm,ss as groups 1,2,3 r'\b(\d\d):(\d\d):(\d\d)\b' - Paddy From codecraig at gmail.com Tue Feb 27 09:01:16 2007 From: codecraig at gmail.com (abcd) Date: 27 Feb 2007 06:01:16 -0800 Subject: pyHook or SetWindowsHookEx Message-ID: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> I am having trouble with pyHook on python 2.4.1. Basically I have a python app that uses pyHook to capture keyboard events and write them straight to a file. The application is running as a service on a windows machine. If I am at that windows machine the application works just fine, logging my keystrokes. However, if I use Remote Desktop to connect to the machine and open up say Notepad it doesn't capture the keystrokes. Is this a problem with pyHook? or is it he way Windows handles the events? Is there a way to setup my own hook without pyHook using just python? i think the function I am interested in is SetWindowsHookEx. Thanks in advance. From istvan.albert at gmail.com Fri Feb 9 09:18:50 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 9 Feb 2007 06:18:50 -0800 Subject: python shelve on win vs unix In-Reply-To: References: Message-ID: <1171030730.538466.212970@m58g2000cwm.googlegroups.com> On Feb 9, 6:06 am, Tor Erik Soenvisen wrote: > Any suggestions for a quick and dirty solution (such as alternatives to > shelve for persistent storage) to this problem would be appreciated. the easiest might be to just pickle your data into files. You could also use Durus http://www.mems-exchange.org/software/durus/ or ZODB, there are also some other object persistence libraries that I've recently seen mentioned. i. From cs07 at verizon.net Thu Feb 8 19:12:18 2007 From: cs07 at verizon.net (John) Date: Thu, 8 Feb 2007 19:12:18 -0500 Subject: Newbie Question References: Message-ID: Visual Basic is also good. "Reid" wrote in message news:LeNyh.4130$R71.62146 at ursa-nb00s0.nbnet.nb.ca... > Hello all > > I am just starting to play with programing again as a hobby. I have heard > good things about python. I have not really looked into the language much. > My question is, will python make programs with a gui under windows xp. If it > will do this I will explore the language more, if not I will try some other > language. > > Reid > > From greg at cosc.canterbury.ac.nz Thu Feb 22 03:16:27 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 22 Feb 2007 21:16:27 +1300 Subject: f---ing typechecking In-Reply-To: References: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Message-ID: <5451v0F1v9782U1@mid.individual.net> Hendrik van Rooyen wrote: > I don't think its reasonable - its just an accident of implementation. There's nothing accidental about the implementation of the in-place operators. It was designed the way it is so that it would work in a reasonable way with both mutable and immutable objects. -- Greg From mail at timgolden.me.uk Fri Feb 23 04:07:13 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 23 Feb 2007 09:07:13 +0000 Subject: How can I track/monitor an application and system resources. In-Reply-To: <1172219486.020466.54560@z35g2000cwz.googlegroups.com> References: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> <1172219486.020466.54560@z35g2000cwz.googlegroups.com> Message-ID: <45DEAEC1.8080906@timgolden.me.uk> richard_l at latter.demon.co.uk wrote: > The phone reference is actually because the target device is WM 5.0. > I've found a python port Pyce that will run on this platform. We have > a target application that runs on this platform which we would like to > develop some automated tests for. The application is written in VC++ > and we're using python to stress test it! You'll have to investigate a bit to see what APIs are available for the platform. I'm afraid I've no experience with portable devices, but some of my colleagues who've done embedded database work on GPRS scanners tell me that the API is quite cut-back. Apart from WMI -- which could well not be there -- there are also the Performance APIs which are exposed by pywin32 in the win32pdh module. Again, though, you'd have to check if they're supported. TJG From brochu121 at gmail.com Tue Feb 27 11:13:12 2007 From: brochu121 at gmail.com (David Brochu) Date: Tue, 27 Feb 2007 11:13:12 -0500 Subject: book for a starter Message-ID: <9583ed900702270813y1d44e918n48ba944818e73f59@mail.gmail.com> From: "Wensui Liu" To: python-list at python.org Date: Tue, 27 Feb 2007 10:09:57 -0500 Subject: book for a starter Good morning, all, [I just start learning python and have a question regarding books for a newbie like me. If you are only allowed to buy 1 python book, which one will you pick? ^_^. Thank you so much!] - If your new to programming I would recommend reading Learning Python (O'Reilly). Along with that the tutorial by Guido on the Python website is a good foundation. If you have programming experience I would recommend Dive Into Python. Either way you probably should have Learning Python and/or Programming Python on your bookshelf for reference if you are going to really program using Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at eventuallyanyway.com Sat Feb 10 10:42:05 2007 From: paul at eventuallyanyway.com (Paul Hummer) Date: Sat, 10 Feb 2007 15:42:05 +0000 Subject: Hacking in python In-Reply-To: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> References: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> Message-ID: <45CDE7CD.5000200@eventuallyanyway.com> enes naci wrote: > i would like to know about hacking in python too whether its illegal > or not is not the point and anyway it doesn't mean i'm gong to use it. > > Does your mom know you're using her computer to take down the government? I'm gonna tell on you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steveo at syslang.net Mon Feb 19 12:11:40 2007 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 19 Feb 2007 12:11:40 -0500 (EST) Subject: Can I reverse eng a .pyc back to .py? Message-ID: The short story is that someone left, but before he left he checked in a .pyc and then both the directory was destroyed and the backups all got shredded (don't ask*). Is there anything that can be extracted? I looked on the web and the subject seems to get different answers, all old. Any joy? TIA * Murphy's Ultimate Corollary: If it could have gone wrong earlier and it didn't, it ultimately would have better for it to have. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From steve at REMOVEME.cybersource.com.au Thu Feb 22 22:09:44 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Feb 2007 14:09:44 +1100 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <7x4ppdhlmu.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 22 Feb 2007 14:29:13 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> Arrays don't support XOR any more than strings do. What's the advantage to >> using the array module if you still have to jump through hoops to get it >> to work? > > It's a lot faster. Sometimes that matters. But is it? >>> import array >>> import timeit >>> >>> def flip1(text): ... mask = ord('U') ... return ''.join([chr(ord(c) ^ mask) for c in text]) ... >>> def flip2(text): ... mask = ord('U') ... text = array.array('b', [b ^ mask for b in array.array('b',text)]) ... return text.tostring() ... >>> text = "Python" >>> setup = 'from __main__ import flip1, flip2, text' >>> >>> timeit.Timer('flip1(text)', setup).repeat() [25.757978916168213, 23.174431085586548, 23.188597917556763] >>> timeit.Timer('flip2(text)', setup).repeat() [25.736327886581421, 25.76999306678772, 26.135013818740845] For a short string like "Python", using an array is a tiny bit slower, at the cost of more complex code. What about for a long string? >>> text = 'Python'*1000 >>> >>> timeit.Timer('flip1(text)', setup).repeat(3, 2000) [24.483185052871704, 26.007826089859009, 24.498424053192139] >>> timeit.Timer('flip2(text)', setup).repeat(3, 2000) [12.18204402923584, 12.342558860778809, 12.16040301322937] Well, that answers that question -- if you're converting a long string, using array is faster. If it is a short string, it doesn't make much difference. -- Steven D'Aprano From Ingo.Wolf at gmx.de Wed Feb 28 07:19:03 2007 From: Ingo.Wolf at gmx.de (iwl) Date: 28 Feb 2007 04:19:03 -0800 Subject: Creating arrays (builtin) in C Extensions Message-ID: <1172665143.602420.185920@q2g2000cwa.googlegroups.com> Hello, there is an builtin documented array module in phyton, but no documentation how such an array can be created in C-Extension functions. So I have to use Lists at time, but this is I think inefficient with large data sets. Is there some interface aviable which I can link to my Programm without any change to standard python? From martin at v.loewis.de Mon Feb 26 23:50:26 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 27 Feb 2007 05:50:26 +0100 Subject: Pep 3105: the end of print? In-Reply-To: References: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> Message-ID: <45E3B892.2040007@v.loewis.de> Neil Cerutti schrieb: > On 2007-02-23, I V wrote: >> While that's true, C++ compiler vendors, for example, take >> backwards compatibility significantly less seriously, it seems >> to me. > > Compiler vendors usually take care of their customers with > compiler switches that enable backwards compatibility. That's a bold statement, after I V already gave two examples (g++ and MSVC 2005) of compilers that broke backwards compatibility without providing compiler switches to bring it back. These two aren't "minor" compilers. Regards, Martin From liuwensui at gmail.com Sun Feb 18 23:33:27 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Sun, 18 Feb 2007 23:33:27 -0500 Subject: numpy, numarray, or numeric? In-Reply-To: <6addebae0702151640p4128d333necdd7cfce4be2f4@mail.gmail.com> References: <6addebae0702151640p4128d333necdd7cfce4be2f4@mail.gmail.com> Message-ID: <1115a2b00702182033v18c37266sca04876f8f0796f3@mail.gmail.com> I have the same doubt when I started using DataFrame class by Andrew Straw. When I used his code as it is, it didn't work because python can't find numeric module. But after I made a small change by 'import numpy' to his code, everything seems to work now. To me, it seems numpy works as same as numeric. HTH. On 2/15/07, Christian Convey wrote: > I need to bang out an image processing library (it's schoolwork, so I > can't just use an existing one). But I see three libraries competing > for my love: numpy, numarray, and numeric. > > Can anyone recommend which one I should use? If one is considered the > officially blessed one going forward, that would be my ideal. > > Thanks, > Christian > -- > http://mail.python.org/mailman/listinfo/python-list > -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From dlenski at gmail.com Thu Feb 15 15:13:45 2007 From: dlenski at gmail.com (Dan Lenski) Date: 15 Feb 2007 12:13:45 -0800 Subject: Python code to do the *server* side of digest authentication? Message-ID: <1171570425.442828.73170@p10g2000cwp.googlegroups.com> Hi all, I've got a very simple HTML proxy server to access the web from my cell phone (based on this code: http://www.okisoft.co.jp/esc/python/proxy/). It's a very retarded phone that freezes if there's no Content-Length header and some other circumstances, so I have to tweak and modify the headers received slightly. But it works quite well with these hacks. Now I'd like to add proxy authentication so that I'm not running this open proxy all the time. I would like to use Digest authentication (http://en.wikipedia.org/wiki/Digest_access_authentication) rather than Basic authentication so as not to expose any plaintext password. It appears that there are plenty of Python libraries to do the *client* side of the authentication (e.g. urllib2) but I have not found much code that does the *server* side of the authentication. That is, I am looking for code to generate the WWW-Authentication header (including appropriate nonce and opaque string) and to verify the Authorization header sent by the client when it retries. It does not look *too* hard to implement, but it does involve crypto and I'd just as soon use some tried-and-true code rather than roll my own in this case. Does anyone have any suggestions of where to find such code? Thanks! Dan From aboudouvas at panafonet.gr Tue Feb 27 04:23:37 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 27 Feb 2007 01:23:37 -0800 Subject: NetUseAdd mystery In-Reply-To: <1172513667_19595@sp6iad.superfeed.net> References: <1172508987.854983.162370@j27g2000cwj.googlegroups.com> <1172513667_19595@sp6iad.superfeed.net> Message-ID: <1172568217.190749.83030@z35g2000cwz.googlegroups.com> > You need to use level 2 info to pass the username. > Level 1 is for the old-style share with its own password. > Also, it should be 'username': instead of just 'user':. > > hth > Roger Roger many-many thanks! That was it, i had to put "username" instead of "user" and 2 instead of 1 at the calling... Thanks again! From steve at REMOVE.THIS.cybersource.com.au Sun Feb 11 06:33:11 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Feb 2007 22:33:11 +1100 Subject: pygame and python 2.5 References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> Message-ID: On Sun, 11 Feb 2007 01:08:21 -0800, mensanator at aol.com wrote: >> An update is in the works for those >> using more recent releases, > > That's good news, although the responsible thing > to do was not relaease version 2.5 until such issues > are resolved. I realize you're a Windows user, and a Windows user with an AOL email address at that, so it may come as a shock to learn that the computer industry doesn't start and finish on Windows. I don't see why the needs of Windows users like yourself should come ahead of the needs of users on Mac OS, Linux, Solaris, etc. >> but that won't help users who don't have >> access to Visual Studio. > > That can be solved by throwing money at the problem. > But money doesn't help when the solution is on the > far side of the moon. You're mixing metaphors and I don't understand what you mean. >> >> Yes, it's >> >> occasionally very frustrating to the rest of us, but that's life. >> >> > As the Kurds are well aware. >> >> I really don't think you help your argument by trying to draw parallels >> between the problems of compiler non-availability and those of a >> population subject to random genocide. > > You missed the point of the analogy. > > The US government suggested to the oppressed tribes > in Iraq that they should rise up and overthrow > Saddam Hussein at the end of the first Gulf War. > And what did the US government do when they rose up? > Nothing. They were left to twist in the wind. Both the southern Iraqis (mostly so-called "marsh Arabs" and Shiites) and the northern Kurds rose up against Saddam Hussein. After the Kurdish rebellion failed, the US and UK belatedly provided them with aid, lots of aid, and kept the northern no-fly zone going until it was no longer relevant (2003, the second invasion of Iraq). It was the southern Iraqis who were left to be slaughtered. Although technically there was a no-fly zone in the south, it wasn't enforced when it really counted -- while the rebellion was in full force, the Iraqi government asked the US for permission to fly into the south. Permission was given, and the Iraq air force used combat aircraft against the rebels. Unlike the Kurds, they got no aid, neither money nor military support. The end result was that the southern Iraqs were hung out to dry, while the Kurds ended up a virtually independent state-within-a-state, with their own "government", their own army, and US and British aircraft protecting them. >> Try to keep things in perspective, please. > > See if you can see the similarity. > > I buy into Python. I spend a lot of effort > developing a math library based on GMPY to use > in my research. I discover a bug in GMPY and > actually go to a lot of effort and solve it. Good on you, and I'm not being sarcastic. But do try to keep a bit of perspective. Whatever your problem, you're not being bombed or shot. Frankly, the fact that you not only came up with the analogy, but continue to defend it, suggests an over-active sense of your own entitlement. > But _I_ can't even use it because I've been > left to twist in the wind by the fact that > Python 2.5 for Windows was built with an > obsolete compiler that's not even available. > Luckily, unlike the Kurds, my situation had > a happy ending, someone else compiled the fixed > GMPY source and made a 2.5 Windows version > available. But can anyone say what will happen > the next time? Get yourself a compiler, then you won't be relying on the kindness of strangers. If that's not practical, for whatever reason, then remember: you're relying on the kindness of strangers. They don't owe you a thing. If anything, you owe them. [snip] >> Your efforts would probably be far better spent trying to build a >> back-end for mingw or some similar system into Python's development >> system, to allow Python for Windows to be built on a regular rather than >> a one-off basis using a completely open source tool chain. > > No, as I said elsewhere, I'm not a software developer, > I'm an amateur math researcher. My efforts are best spent > as an actual end user If you won't scratch your own itch, don't be surprised if nobody else cares enough to scratch it for you. > to find and report bugs that the > developers never see. Remember, a programmer, because he > wrote it, only _thinks_ he knows how the program works. > Whereas I, the user, _know_ how it works. Oh wow. That's the most audacious, self-involved and sheer arrogant claim I've ever heard, and I've heard a lot of nonsense sprouted by arrogant know-nothings with delusions of grandeur. For the sake of your credibility, I hope you can support that claim. [snip] >> It's much harder than sniping on a newsgroup, > > That figures. You try and contribute and you get > accused of being a troll. "I have a problem. I demand that somebody fix it for me!" is hardly contributing. If you don't have the technical skills to fix it yourself, have you considered putting hand in pocket and paying a software developer to do it? It might even come out cheaper than buying a commercial compiler, and it would help others. That should appeal to somebody as altruistic as you. > > but you earn rather more kudos. > > Guess what kudos I got for solving the GMPY divm() > problem? None. How much effort would it have been > to mention my contribution in the source code > comments (as was the case for other contributers)? > Not that I'm bitter, after all, I'm altruistic. Naturally. > By the way, on the sci.math newsgroup I promote > Python every chance I get. That's mighty big of you. > One fellow thanked me > profusely for recommending Python & GMPY and asked > for some help with a program he was having problems > with. We worked it out fine but his problem made me > suspect there may be more bugs in GMPY. What's my > motivation for tracking them down? Because you want the bugs fixed so you can get on with whatever coding you want to do. Because you're altruistic. Because you want people to know how clever you are. Are those enough reasons? -- Steven. From richard.charts at gmail.com Thu Feb 1 11:23:18 2007 From: richard.charts at gmail.com (Richard Charts) Date: 1 Feb 2007 08:23:18 -0800 Subject: Germany issues warrants for 13 American CIA agents In-Reply-To: References: <1170286881.262636.315770@a75g2000cwd.googlegroups.com> Message-ID: <1170346998.054119.159780@a75g2000cwd.googlegroups.com> On Jan 31, 10:52 pm, "Overlord" wrote: > Fuck the Germans. Didn't we kick their ass a couple times already? > > OL Thank god, I can just get my world news from c.l.p instead of having to find another "news" site. I salute you thermate2 at india.com From theller at ctypes.org Wed Feb 7 08:51:50 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 07 Feb 2007 14:51:50 +0100 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <45C9A137.8090009@v.loewis.de> References: <45C9A137.8090009@v.loewis.de> Message-ID: <45C9D976.9050403@ctypes.org> Martin v. L?wis schrieb: > I'm happy to announce partial 1.0; a module to implement > partial classes in Python. It is available from > > http://cheeseshop.python.org/pypi/partial/1.0 > > A partial class is a fragment of a class definition; > partial classes allow to spread the definition of > a class over several modules. One location serves > as the original definition of the class. > > To extend a class original_module.FullClass with > an additional function, one writes > > from partial import * > import original_module > > class ExtendedClass(partial, original_module.FullClass): > def additional_method(self, args): > body > more_methods > > This module is licensed under the Academic Free License v3.0. > > Please send comments and feedback to martin at v.loewis.de Nice idea. I had to apply this change to make it work, though: diff -u c:\python25\lib\site-packages\partial-1.0-py2.5.egg\partial.py.orig c:\python25\lib\site-packages\partial-1.0-py2.5.egg\partial.py --- c:\python25\lib\site-packages\partial-1.0-py2.5.egg\partial.py.orig Wed Feb 07 13:47:55 2007 +++ c:\python25\lib\site-packages\partial-1.0-py2.5.egg\partial.py Wed Feb 07 13:47:55 2007 @@ -36,7 +36,7 @@ continue if k in base.__dict__ and not hasattr(v, '__replace'): raise TypeError, "%s already has %s" % (repr(base), k) - base.__dict__[k] = v + setattr(base, k, v) # Return the original class return base otherwise I get this: Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\site-packages\partial-1.0-py2.5.egg\partial.py", line 39, in __new__ base.__dict__[k] = v TypeError: Error when calling the metaclass bases 'dictproxy' object does not support item assignment IIUC, wouldn't be 'partial.extend' or something like that be a better name for the base class? Thanks, Thomas From openopt at ukr.net Thu Feb 22 11:37:11 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 22 Feb 2007 08:37:11 -0800 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? In-Reply-To: <1172149355.710034.224770@v45g2000cwv.googlegroups.com> References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> <1172149355.710034.224770@v45g2000cwv.googlegroups.com> Message-ID: <1172162231.815455.253200@k78g2000cwa.googlegroups.com> > Think on the bright side: > > you have to type ":" at the beginning of loop and conditional blocks, > but you don't have to type "end" at the end... you are still saving > two strokes... > ;-)) No, there no profits: instead of 'end' I must type , ':' and backspace in the end of block - so 3 keypress are used, same as 'end' Of course Python is much more better in syntax vs C/C++ but I would prefere tcl-style or caml-style x = fun arg1 arg2 ... argn however, in tcl annoing things are 'set' and 'expr' and in ocaml '<-' and 'let x = ... in' - too many keypress instead of '=' but their func calls still is better then fun(arg1, arg2, ..., argn) and help _something_ or which _something_ in MATLAB is much more better then help(_something_) in Python the only bad thing in MATLAB (+absence of x = fun arg1 arg2 ... argn call) is indexing arrays by () instead of [] - holding shift key dozens times per day is very unconvinient. And in Python vs MATLAB is very unconvinient arrays creation. I'm very afraid of proposition that I noticed at http://wiki.python.org/moin/SummerOfCode Base multidimensional array type for Python core Student: KarolLangner Mentor: Travis E. Oliphant I don't know about anyone mentioned but I'm not sure this is a good idea to hire ordinary student for such important thing. And writing 'dimarray(...)' dozens times per day is much more bad than x = matrix('...'), x = array([...]) or, of course, MATLAB-style x = [1 2 3] I guess it should 10 times more think about the array and make it once and forever - Python already has some array-related classes and all with syntax much more bad than MATLAB. I guess there should be only 2 types: one for storing data in convinient way without reallocating (something like C++ STL vector<>) and one for quick calculations (something like C++ valarray). WBR, Dmitrey. From sjdevnull at yahoo.com Mon Feb 5 03:36:44 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 5 Feb 2007 00:36:44 -0800 Subject: Python does not play well with others In-Reply-To: <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> Message-ID: <1170664604.049592.164180@h3g2000cwc.googlegroups.com> John Nagle wrote: > Graham Dumpleton wrote: > > On Feb 4, 1:05 pm, Paul Rubin wrote: > > > >>"Paul Boddie" writes: > >> > >>>Probably the biggest inhibitor, as far as I can see, has been the > >>>server technology chosen. Many hosting providers have historically > >>>offered no better than CGI for Python, whilst PHP runs within Apache > >>>itself, and it has previously been stated that mod_python has been > >>>undesirable with regard to isolating processes from each other. > >>>Consequently, a number of Python people seem to have held out for > >>>other "high performance" solutions, which various companies now offer. > >> > >>Your point that shared hosting with Python isn't so easy because of > >>insufficient isolation between apps is valid. Maybe Python 3.0 can do > >>something about that and it seems like a valid thing to consider while > >>fleshing out the 3.0 design. > > > > > > To clarify some points about mod_python, since these posts do not > > properly explain the reality of the situation and I feel people are > > getting the wrong impression. > > > > First off, when using mod_python it is possible to have it create > > multiple sub interpreters within each Apache child process. > > Realistically, mod_python is a dead end for large servers, > because Python isn't really multi-threaded. The Global Python > Lock means that a multi-core CPU won't help performance. The GIL doesn't affect seperate processes, and any large server that cares about stability is going to be running a pre-forking MPM no matter what language they're supporting. From gonzlobo at gmail.com Sat Feb 3 21:48:45 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Sat, 3 Feb 2007 19:48:45 -0700 Subject: Decimating Excel files In-Reply-To: <1170556471.579611.37140@v33g2000cwv.googlegroups.com> References: <1170556471.579611.37140@v33g2000cwv.googlegroups.com> Message-ID: Yeah, it definitely an Excel file (so says Kate). > Is the file format really native Excel, or is a CSV or TSV file? I've > seen apps (one is a data acquisition program, as a matter of fact) > that create "Excel" files that are just CSV or TSV files. Try opening > the file with a text editor to see if it's plain ASCII text. From usenet at nicko.org Fri Feb 2 12:36:17 2007 From: usenet at nicko.org (Nicko) Date: 2 Feb 2007 09:36:17 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170361512.204099.191740@a75g2000cwd.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> Message-ID: <1170437777.785549.214730@l53g2000cwa.googlegroups.com> On Feb 1, 8:25 pm, "Krypto" wrote: > The correct answer as told to me by a person is > > (N>>3) + ((N-7*(N>>3))>>3) > > The above term always gives division by 7 No it doesn't. The above term tends towards N * (9/64), with some significant rounding errors. 9/64 is a fairly poor (6 bit) approximation of 1/7 but the principle is the same as the solution I proposed above. Nicko From pink at odahoda.de Wed Feb 14 03:58:09 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 14 Feb 2007 09:58:09 +0100 Subject: calling php function from python References: <1171439793.002812.189790@v45g2000cwv.googlegroups.com> Message-ID: Rob Wolfe wrote: > > mark wrote: >> is it possible to call a php function from python and use a class from >> php in python? i want to use mmslib which creates mms messages and the >> only implementation is a php mmslib implementation. > > You can consider to use some kind of RPC (remote procedure call) > for example XML-RPC. This is a platform and language independent > solution. > Here you have some information: > http://www.faqs.org/docs/Linux-HOWTO/XML-RPC-HOWTO.html > http://groups.google.pl/group/comp.lang.python/msg/5a6ae6290593fc97 For a quickstart it's probably easier to run the PHP code using the CGI version of the PHP interpreter. E.g. os.system('/usr/bin/php mms.php') or using the subprocess module, if you want to pass some data to the script (using stdin/out). As long as no remote PHP server is involved this is easier and perhaps even faster than the RPC approach... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From greg at cosc.canterbury.ac.nz Mon Feb 5 19:21:41 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 06 Feb 2007 13:21:41 +1300 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: <52q04iF1pl3l8U1@mid.individual.net> Alexander Schmolck wrote: > For example I once wrote this (slow) code to display > part of a mandelbrot fractal: > > load'viewmat' > viewmat+/2&>:|((j.~/~(%~i:)99)&+@:*:)^:(i.32)0 > > It'll likely require you more typing in python, Yes, but with Python you wouldn't have to spend a couple of weeks sitting and thinking before starting to type that line... -- Greg From harlinseritt at yahoo.com Sat Feb 17 15:29:24 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 17 Feb 2007 12:29:24 -0800 Subject: Getting a class name Message-ID: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> Hi, How does one get the name of a class from within the class code? I tried something like this as a guess: self.__name__ Obviously it didn't work. Anyone know how to do that? Thanks, Harlin From ptmcg at austin.rr.com Thu Feb 15 00:58:35 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 Feb 2007 21:58:35 -0800 Subject: Method overloading? In-Reply-To: <1171515271.811324.218020@s48g2000cws.googlegroups.com> References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> Message-ID: <1171519115.463977.220700@j27g2000cwj.googlegroups.com> On Feb 14, 10:54 pm, "placid" wrote: > Hi all, > > Is it possible to be able to do the following in Python? > > class Test: > def __init__(self): > pass > > def puts(self, str): > print str > > def puts(self, str,str2): > print str,str2 > > if __name__ == "__main__": > t = Test() > t.puts("hi") > t.puts("hi","hello") > > Cheers No, Python does not do overloading as part of the language, you have to do the variable argument interpretation for yourself. For instance, if you want a method to accept a single argument of various types, it would look something like this: def multiAccept( argOfVariousTypes ): if isinstance(argOfVariousTypes,int): # treat like an int elif isinstance(argOfVariousTypes,float): # treat like a float elif isinstance(argOfVariousTypes,(list,tuple)): # treat like a container This is not really all that Pythonic a style. More generally accepted is to just *use* the arg in the way you want, and throw exceptions when the arg doesn't conform - if the user sends invalid args, let him/ her deal with the resulting exceptions. Here's a method that will handle an arg of various types: def containerStats(cont): print "Container is of type %s" % cont.__class__.__name__ print "- min value is", min(cont) print "- max value is", max(cont) print "- length is", len(cont) >>> containerStats( [1,2,3] ) Container is of type list - min value is 1 - max value is 3 - length is 3 >>> containerStats( ('abc', 'def', 123) ) Container is of type tuple - min value is 123 - max value is def - length is 3 >>> containerStats( dict(zip("abc",range(3))) ) Container is of type dict - min value is a - max value is c - length is 3 >>> containerStats("lsjlsja;s") Container is of type str - min value is ; - max value is s - length is 9 What's really interesting, is that this method could have been written back in Python 1.5 days, and in Python 2.3 with the introduction of sets, we could use this new data type, which didn't even exist when the original code was written, and get some interesting results: >>> containerStats(set("SLKFJDSLJDFSLJFSLKFS")) Container is of type set - min value is D - max value is S - length is 6 And if we don't send a container? This happens: >>> containerStats( 3.14159 ) Container is of type float - min value is Traceback (most recent call last): File "", line 1, in ? File "", line 3, in containerStats TypeError: iteration over non-sequence But what did I expect, sending a single float to a method that clearly expects a sequence of some kind?! Python does include in the language the ability to send a variable number of arguments to a method, using *args and **kwargs. Your original puts method can accept a variable argument list in something like this: class Test: def __init__(self): pass def puts(self, *args): print " ".join(map(str,args)) if __name__ == "__main__": t = Test() t.puts("hi") t.puts("hi","hello") t.puts("hi",1,3.45) Prints: hi hi hello hi 1 3.45 Combine these techniques, and you can overload your methods to your heart's content! -- Paul From sergey at fidoman.ru Thu Feb 15 02:37:33 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Thu, 15 Feb 2007 10:37:33 +0300 Subject: f---ing typechecking References: Message-ID: wrote in message news:mailman.4019.1171498160.32031.python-list at python.org... > It's effectively a tuple with field names. I don't know when the switch > occurred (it's in 2.2, as far back as my built interpreter versions > currently go), but back in the day os.stat used to return a plain old > tuple. posix.stat_result is CLASS, not regular tuple. classes is the only way in python to approximate records/structs (may be dict can be considered as record too, if we agree with strange syntaxis). To consider tuples as struct, one must have a GREAT imagination, as tuples functionally are _arrays_, with only difference from lists as freezeness - the have NO filed names. > I have no idea if the schizophrenic personality of tuples will improve > with > drugs^H^H^H^H^H Python 3, but I wouldn't be at all surprised if it did. I think the best thing is to be more democratic when asked to add two arrays :) From steve at REMOVEME.cybersource.com.au Wed Feb 14 00:37:44 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 14 Feb 2007 16:37:44 +1100 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> Message-ID: On Tue, 13 Feb 2007 21:15:19 -0800, agent-s wrote: > I have a function, generally described as so: [snip function] > which is used in: > > if function(args): > print "ok" > > so here basically "text" will print out when condition3 is true but it > will not print out "ok" when condition3 is true. When it's true it > should print out borth "text" and "ok" Thank you for sharing. Do you have an actual question? -- Steven D'Aprano From pwatson at redlinepy.com Tue Feb 13 12:52:10 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 13 Feb 2007 11:52:10 -0600 Subject: Scripting Visio using Python Message-ID: <53ec6aF1rdistU1@mid.individual.net> I would like to create some additional shapes in Microsoft Visio using the Python language. It would appear that Visio can use any CLR language. Has anyone done this? Can I use the Python package from python.org, or must I use IronPython? From sriram.sundararajan at gmail.com Tue Feb 27 14:08:46 2007 From: sriram.sundararajan at gmail.com (Sriram) Date: 27 Feb 2007 11:08:46 -0800 Subject: book for a starter In-Reply-To: <54j9qfF20cqgnU1@mid.individual.net> References: <54j9qfF20cqgnU1@mid.individual.net> Message-ID: <1172603326.853903.315620@z35g2000cwz.googlegroups.com> Hi, If you have experience programming, just read the online tutorial at http://docs.python.org/tut/tut.html I find Python Essential Reference (3rd Edition) (Developer's Library) (Paperback) invaluable though. BTW I have the 2nd edition. Amazon link : http://www.amazon.com/gp/pdp/profile/A9N9B1L0O4BYJ/ref=cm_blog_dp_pdp/002-7062034-2980840 On Feb 27, 10:58 am, Bjoern Schliessmann wrote: > Wensui Liu wrote: > > I just start learning python and have a question regarding books > > for a newbie like me. > > http://wiki.python.org/moin/IntroductoryBooks > > > If you are only allowed to buy 1 python book, which one will you > > pick? ^_^. > > I'd pick a reference. YMMV. > > Regards, > > Bj?rn (having been allowed to buy more than one Python book) > > -- > BOFH excuse #314: > > You need to upgrade your VESA local bus to a MasterCard local bus. From stj911 at rock.com Thu Feb 22 13:44:24 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 22 Feb 2007 10:44:24 -0800 Subject: American Expertise in Science and China, amazing good life at the end Message-ID: <1172169864.899075.303240@a75g2000cwd.googlegroups.com> http://www.newsreview.com/sacramento/Content?oid=oid%3A16418 Google search for Robert Hanson accidentally led to the amazing story in the link above From steven.bethard at gmail.com Fri Feb 16 12:43:08 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 16 Feb 2007 10:43:08 -0700 Subject: builtin set literal In-Reply-To: References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> Message-ID: Sch?le Daniel wrote: >> {:} for empty dict and {} for empty set don't look too much atrocious >> to me. > > this looks consistent to me Yes, a lot of people liked this approach, but it was rejected due to gratuitous breakage. While Python 3.0 is not afraid to break backwards compatibility, it tries to do so only when there's a very substantial advantage. I guess enough people felt that having a shortcut for set() was less important than keeping the current spelling of dict() the same. STeVe From steve at REMOVE.THIS.cybersource.com.au Sun Feb 18 01:34:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 18 Feb 2007 17:34:21 +1100 Subject: How do I save the contents of a text buffer References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> <1171761050.149331.208910@v45g2000cwv.googlegroups.com> Message-ID: On Sat, 17 Feb 2007 17:10:50 -0800, google wrote: > I just included file opening code just to show how i read the file > into the text buffer - I have no issues with this as such. Problem is > only with the writing of the text buffer back to a file. When I try to > write the buffer to a file it gave the following, > > > Traceback (most recent call last): > File "./configbox.py", line 78, in ? > TextViewExample() > File "./configbox.py", line 53, in __init__ > outfile.write(textbuffer.get_text(0,1000, > include_hidden_chars=True)) > TypeError: start should be a GtkTextIter Ah, well there's your problem. start should be a GtkTextIter, just like the exception says. Question for you: in the line of code in the traceback, which function takes an argument called "start"? > How can I use outfile.write() to wite the contents of the text buffer > correctly? Your problem isn't with outfile.write(). -- Steven. From joerg.rech at gmail.com Mon Feb 26 13:53:41 2007 From: joerg.rech at gmail.com (Joerg Rech) Date: 26 Feb 2007 10:53:41 -0800 Subject: Last Reminder: Survey about Architecture and Design Patterns Message-ID: <1172516021.419661.147160@z35g2000cwz.googlegroups.com> Dear software practitioners, consultants, and researchers, we are currently conducting an international survey about architecture and design patterns. Our goal is to discover how familiar people are with these patterns (and anti-patterns) as well as to elicit the information need, the usage behavior, and the experience of software organizations regarding architecture patterns and design patterns. Therefore, we would like to invite you and members of your organizations to participate in the survey at http://softwarepatterns.eu. Answering the survey should take about 20-30 minutes. The survey will close on 1 March 2007. All data will be treated confidentially. Please pass information about this survey on to your colleagues and managers as well as other contacts who might be interested in this topic and have experience with architecture and design patterns. Many thanks in advance, Joerg Rech --- Joerg Rech Speaker of the GI-Workgroup Architecture and Design Patterns (AKAEM) Web: http://www.architekturmuster.de (in German) XING: http://www.xing.com/profile/Joerg_Rech/ From has.temp3 at virgin.net Wed Feb 28 21:31:50 2007 From: has.temp3 at virgin.net (has) Date: 28 Feb 2007 18:31:50 -0800 Subject: questions on dynamically binding the Python interpreter Message-ID: <1172716310.484321.241980@h3g2000cwc.googlegroups.com> Hi all, need a little bit of advice on dynamically binding an embedded Python interpreter. First, the code for anyone that wants a look: http://trac.macosforge.org/projects/appscript/browser/py-osacomponent/trunk/PyOSA It's a Python OSA component for OS X. The idea is that you wrap up a scripting language interpreter as a Carbon Component Manager component (similar to writing a COM component); applications can then call the OSA API to load this component into memory whenever they need to run scripts written in that language. The advantage of this approach over embedding an interpreter directly in the application is that it's language-agnostic, so application users can write their scripts in any language they like (AppleScript, JavaScript, Python, etc.), as long as there's an OSA component available for it (AppleScript, JavaScriptOSA, PyOSA, etc.). Great concept - at least in theory. Now, one of the things about the OSA is that, as one of the old MacOS school, it was pretty much designed on the assumption that interpreters would be hosted by the application process itself. Whereas Python is more of the Unix school, and its own preference would no doubt be to run as separate processes from the main application process, with two-way IPC to hook the two together. I'll likely attempt the latter approach later on (which'll no doubt open a whole new can of worms), but for now I'm having a go at the former as it's appears a bit simpler to implement (at least on paper) and will have better runtime performance (since there's no IPC overhead). For flexibility, and compatibility with application processes that may already a Python framework loaded, I'm linking Python dynamically via CoreFoundation's CFBundle API (which basically provides a nice wrapper around dlopen &co., amongst other things). I've made some reasonable progress so far, and the pythonloader code can now locate and bind a Python.framework without triggering bus errors or anything (a big achievement for me;). However, there's a couple of places I'm a bit uncertain on how to proceed: 1. Py_IncRef() and Py_DecRef() only appear to have been added in Python 2.4; is this right? I really need to support Python 2.3 as well (since that's the version included as standard on OS X 10.3 & 10.4). At the moment when 2.3 is imported I'm providing it stubs of these functions that don't really do anything except leak like sieves; obviously I'd like to replace these. Do I need to start copying and pasting chunks of header/code out of Python 2.3, or is there a better way of doing things? 2. I need to make several C functions callable from within the Python code. Actually these are part of a larger ADT - the opaque data being passed in separately as a CObject - but implementing them as a Python type was going to be more work so the ADT approach seemed like a good idea at the time. At the moment I'm using PyMethodDef + Py_InitModule4() to wrap those C functions as an extension and inject it into the interpreter's module namespace; the problem I've found is that this API is version-sensitive (e.g. 1012 in older Python vs 1013 in newer). Is there some other way to expose those C function to Python that isn't version-sensitive? If not, what's the best way to work with the existing API so that users don't get inflicted with warnings or worse? Lastly, one other question not directly related to the above: I would like to provide a degree of insulation between unrelated scripts (separate module namespaces in particular); and while I realise they still provide than perfect separation, sub-interpreters do seem to be the one and only game in town as far as in-process solutions go. Just how badly am I going to smoke things when I try to enable the sub- interpreter support? Should I take out house insurance, move well clear of inhabited areas, etc? Anywhere I can get more information on the techniques and pitfalls involved? (The Python documentation is terribly thin on this stuff.) Many thanks, and apologies for length, has From ajdeshpande at gmail.com Sat Feb 10 11:25:47 2007 From: ajdeshpande at gmail.com (Analog Kid) Date: Sat, 10 Feb 2007 21:55:47 +0530 Subject: pyTTS question ... Message-ID: <4ccf86300702100825h225c0a70u7d3e41c215ae5a8c@mail.gmail.com> hi all: i need to know how other voices besides MSMary, MSSam and MSMike can be installed and used along with pyTTS. i tried downloading voices (PeterUK to be precise) but looks like it has not been registered, since pyTTS doesn't recognize it. Do I have to manually register the voice in Windows? TIA, -Ajay -------------- next part -------------- An HTML attachment was scrubbed... URL: From vatamane at gmail.com Tue Feb 6 07:23:13 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 6 Feb 2007 04:23:13 -0800 Subject: Two mappings inverse to each other: f, g = biject() In-Reply-To: <45C856E4.6090307@pytex.org> References: <45C856E4.6090307@pytex.org> Message-ID: <1170764593.777423.287240@h3g2000cwc.googlegroups.com> On Feb 6, 5:22 am, Jonathan Fine wrote: > Hello > > As part of the MathTran project I found myself > wanting to maintain a bijection between long > names and short names. > http://www.open.ac.uk/mathtran > > In other words, I wanted to have two dictionaries > f and g such that > f[a] == b > g[b] == a > are equivalent statements. > > A google search for biject.py and bijection.py > produced no hits, so I suspect that this may not > have been done before. > > I've written a partial implementation of this, > and would appreciate comments. > > http://texd.cvs.sourceforge.net/texd/tex/util.py?revision=1.1&view=ma...http://texd.cvs.sourceforge.net/texd/test_tex/test_util.py?revision=1... > > Here's the code from test_util.py, that shows how it > works. The weakref stuff is so that there isn't a > circular reference f to g to f. > === > from tex.util import biject > > f, g = biject() > assert f.inverse is g > assert g.inverse is f > > f[1] = 2 > assert f[1] == 2 > assert g[2] == 1 > assert f.has_value(2) > > import weakref > > wr_g = weakref.ref(g) > del g > assert wr_g() == None > assert f.inverse == None > === > > best regards > > Jonathan Jonathan, If you need to get a short name, given a long name or vice-verse _and_ the set of short names and long names is distinct (it would be confusing if it wasn't!) then you can just have one dictionary, no need to complicate things too much: f[a]=b f[b]=a You won't know which is a short and which is a long based just on this, so you need to keep track of it. But it will give you the mapping. Here is an example: ------------------------------------ >>> S=('a','b','d') >>> L=('alpha,'beta','delta') >>> f={} >>> for i in range(3): ....: f[S[i]]=L[i] ....: f[L[i]]=S[i] >>> f {'a': 'alpha', 'alpha': 'a', 'b': 'beta', 'beta': 'b', 'd': 'delta', 'delta': 'd'} >>> f['b'] 'beta' >>> f['beta'] 'b' ---------------------------------- Hope this helps, And remember : "Simple Is Better Than Complex" [http://www.python.org/ doc/Humor.html#zen] Nick Vatamaniuc From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 28 21:32:56 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 03:32:56 +0100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> Message-ID: <54msaoF21c6h3U3@mid.individual.net> Bruno Desthuilliers wrote: > class Toto(object): > pass > > print Toto.__name__ Okay, I revoke my statement and assert the opposite. But what's it (__name__) good for? Regards, Bj?rn -- BOFH excuse #179: multicasts on broken packets From azricareers at gmail.com Tue Feb 27 06:22:55 2007 From: azricareers at gmail.com (Azri Careers) Date: 27 Feb 2007 03:22:55 -0800 Subject: [Job Posting] EXCITING OPPORTUNITY FOR EXPERIENCED PYTHON DEVELOPER Message-ID: <1172575375.254694.268950@s48g2000cws.googlegroups.com> Azri Solutions Pvt Limited ( http://www.azri.biz) provides a challenging work environment, an open work culture & competitive remuneration : the right ingredients to facilitate superlative performance.Vacancies for Experienced PYTHON DEVELOPER are currently open. Azri is an extremely flexible & sustainable networked enterprise with presence in Germany, the U.S.A. & India. Our team has intense hands-on experience in designing, deploying and managing high-volume Service-Oriented Architectures (SOA) including RDBMS-backed Webservices. In most cases, we leverage tried and tested open-source software. Join our highly motivated and dedicated team to embark upon a challenging and rewarding career where you get to make decisions, create great products and in the process, have some fun! We believe in the concept of continuous learning, taking on responsibilities and providing growth opportunities for every team member. Our environment encourages innovation. Ideas are welcome and every individual is empowered to think, share and take ownership of their ideas and creations. MAIL YOUR RESUME TO edev at azri.biz General : ? Should have developed applications using Open Source systems. ? Scripting : TCL, PHP, Perl, Python(Mandatory), Ruby. ? Languages : C, C++ development experience is an added advantage. ? OS : Linux / Unix, Windows. (Must have Linux / Unix experience). ? Frameworks : Should have used Open Source languages like PHP / Perl/ Ruby / TCL and frameworks like Drupal / Mojave / Rails / OpenACS. Job Location : Hyderabad Candidate Profile : ? Should enjoy programming. ? Experience : One to four years' programming experience. ? Knowledge of Linux, Shell scripting, Web application development, Quality software development. ? Excellent conceptual, analytical and programming skills. ? Should have Application Design experience. ? Familiarity with Open Source Application Development. ? Familiarity with Open Source Web Application Frameworks. ? Participation in open source communities is an added advantage. SOFTSKILLS : Good communication and interpersonal skills. LOCATION : HYDERABAD MAIL YOUR RESUME TO edev at azri.biz From felipe.lessa at gmail.com Tue Feb 20 05:52:38 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 20 Feb 2007 08:52:38 -0200 Subject: Can I reverse eng a .pyc back to .py? In-Reply-To: References: Message-ID: On 2/19/07, Steven W. Orr wrote: > The short story is that someone left, but before he left he checked in a > .pyc and then both the directory was destroyed and the backups all got > shredded (don't ask*). Is there anything that can be extracted? I looked > on the web and the subject seems to get different answers, all old. Only for .pyc's of Python versions upto 2.3: http://packages.debian.org/unstable/python/decompyle -- Felipe. From sjmachin at lexicon.net Wed Feb 28 05:12:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2007 02:12:33 -0800 Subject: Installing java2python (Newbie) In-Reply-To: References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172654566.960775.66080@j27g2000cwj.googlegroups.com> Message-ID: <1172657553.589543.176850@v33g2000cwv.googlegroups.com> On Feb 28, 8:33 pm, "Troy Melhase" wrote: > > Hi Troy, Windows users don't really "want" to do that. They'd prefer > > to download a Windows installer, and "double-click on it". > > Hi John, > > Understood and agreed. I was thinking about Andy's problem, and I > realized that many users would benefit from a gui to do side-by-side > translation. If I ever have the time, I could write one I think. > > > This might save some wear'n'tear on their nervous systems, and > > > yours :-) > > Like so many projects, it works for me the way it is -- I'm driving > j2py via makefiles, and a gui just isn't something I need. But of > course patches are welcome -- even gui ones! Did you think I was suggesting that you write a GUI version of java2python? Please carefully (re)?read the documentation link that I gave you. The idea is that with a simple variation of your setup.py build comamnd, you create a Windows installer for your existing package, and make it available for download. Then, all the Windows user has to do is to double-click on it, and it guides them through the installation. This would save wear'n'tear on you having to try to explain to some newbie Windows user how to install your package. HTH take 2, John From arnodel at googlemail.com Wed Feb 28 12:34:45 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 28 Feb 2007 09:34:45 -0800 Subject: finding out the precision of floats In-Reply-To: <1172662682.590738.301630@k78g2000cwa.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> Message-ID: <1172684085.170332.323490@z35g2000cwz.googlegroups.com> On 28 Feb, 11:38, "Bart Ogryczak" wrote: > On Feb 27, 7:58 pm, "Arnaud Delobelle" wrote: > > This is one of the reasons (by no means the main) why I decided to > > write my own class. > > Why not GMP? I need decimals. > My point is, that neither is Decimal. It doesn't solve the problem, > creating additional problem with efficiency. > > > >>> 0.1+0.1+0.1==0.3 > > False > > >>> 3*0.1==0.3 > > > False > > > Decimals will behave better in this case. > > Decimal will work fine as long as you deal only with decimal numbers > and the most basic arithmetic. Any rational number with base that is > not power of 10, or any irrational number won't have an exact > representation. My problem is precisely to represent rational numbers whose denominator is a power of 10 (aka decimals) accurately. > So as long as you're dealing with something like > invoices, Decimal does just fine. When you start real calculations, > not only scientific, but even financial ones[1], it doesn't do any > better then binary float, and it's bloody slow. I'm not doing 'real world' calcultations, I'm making an app to help teach children maths. I need numerical values that behave well as decimals. I also need them to have an arbitrary number of significant figures. Floats are great but they won't help me with either. Amongst other things, I need 3.0*0.1==0.3 to be True. Please do not make the assumption that I have chosen to use a decimal type without some careful consideration. -- Arnaud From rdiaz02 at gmail.com Sun Feb 4 11:26:48 2007 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sun, 4 Feb 2007 17:26:48 +0100 Subject: Python does not play well with others In-Reply-To: <7xbqkaejrs.fsf@ruckus.brouhaha.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xejp89pa9.fsf@ruckus.brouhaha.com> <7xfy9n2pz4.fsf@ruckus.brouhaha.com> <7xbqkaejrs.fsf@ruckus.brouhaha.com> Message-ID: <624934630702040826g13a77f5bx7687d4e402179934@mail.gmail.com> I find Paul Rubin's arguments compelling and convincing. As just a Python user (i.e., someone who has contributed nothing) let me add a few comments along the same lines. On 03 Feb 2007 18:31:03 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > skip at pobox.com writes: > > Paul> Why would I expect your employer to solve my problems anyway, even > > Paul> if they relate to some module that you actually use? > > > > Your reasoning seems to be that Python should contain the functional union > > of everything at least in Java and PHP if not Perl, Ruby and Tcl as well. > > I wouldn't go quite that far. I think there are specific application > areas, such as web server apps, where the Python advocates here on > clpy pitch Python relentlessly against those other languages. Given > that context, Python's stdlib should try to match the libraries of > those other languages in those areas. There are other areas where > Python doesn't get pitched as hard and the other languages have > acknowledged advantages. So it's ok if Python's stdlib gets less > attention in those areas. > In fact, it is quite frustrating to operate under the impression that "Python is good for X, Y, Z, ...." and then realize "ooops, it is becoming a pain in the ass to do X, whereas language L does X just fine". It seems to me that Python advocates sometimes (often?) get carried away. DB "sure, no problem"; web-frameworks "who needs Rails, we have (lots of) frameworks that do it"; functional programming "Python can do all the functional programming anyone in his/her mind should ever try to do"; etc. Compare this to the, in my opinion, equanimous, fair, "advertisement" one finds in the Erlang page or the recognition by schemers that scheme is not the only game in town. > > > If you want to turn the Python distribution into a kitchen sink, > > make the argument on python-dev and be prepared to shoulder your > > share of the burden should your arguments sway the group as a whole. > > We've had this conversation before and I continue to think your > reasoning above is invalid. I'm not a Python developer, I'm just a > user, and my volunteer coding priorities are elsewhere, as I've > explained before. Python's developers and advocates have a declared > goal of reaching as many users as they can, and as a user I don't mind > offering suggestions about how to do that, but my responsibilities > don't go any further. R. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From jeremit0 at gmail.com Wed Feb 7 10:07:42 2007 From: jeremit0 at gmail.com (jeremito) Date: 7 Feb 2007 07:07:42 -0800 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170854927.013819.320020@a75g2000cwd.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> <1170795607.938431.144340@p10g2000cwp.googlegroups.com> <45c8f5b5$0$19714$426a74cc@news.free.fr> <1170854927.013819.320020@a75g2000cwd.googlegroups.com> Message-ID: <1170860862.438897.244820@a75g2000cwd.googlegroups.com> On Feb 7, 8:28 am, "jeremito" wrote: > On Feb 6, 5:10 pm, Bruno Desthuilliers > > > > wrote: > > jeremito a ?crit : > > > On Feb 6, 2:36 pm, Bruno Desthuilliers > wrote: > > > (snip) > > > >>Here's an alternative implementation, so you get the idea. > > > >>class Xs(dict): > > > oops ! I meant: > > class Xs(object): > > > of course... > > > (snip) > > > > I guess I just > > > need more experience. > > > Possibly - but not only. You may want to have a look at the > > FineManual(tm) for all this kind of "magic", starting with :http://docs.python.org/ref/specialnames.htmlhttp://docs.python.org/re... > > > HTH > > Thanks again! Sometimes the problem is simply not knowing where to > find the documentation, or finding the right portion of the > documentation. Your help has been invaluable. > > Jeremy One more question. I will be asking for the value of cs.xT *many* (~millions) times. Therefore I don't want it's value to be calculated on the fly. How can I set the value of xT whenever xS, xF, or xG are changed, but not allow it to be set directly? From the example given previously, it seems like it can't be done this way. Thans, Jeremy From gagsl-py at yahoo.com.ar Tue Feb 6 02:40:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 04:40:13 -0300 Subject: python for web programming References: Message-ID: En Tue, 06 Feb 2007 02:10:14 -0300, escribi?: > Can you show me some reference datas for python web programming?Thanks. http://wiki.python.org/moin/WebProgramming http://wiki.python.org/moin/WebApplications or search the wiki, or even use Google. -- Gabriel Genellina From ramen at lackingtalent.com Thu Feb 8 01:02:07 2007 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 07 Feb 2007 23:02:07 -0700 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: Neil Cerutti wrote: > There's been only one (or two?) languages in history that > attempted to provide programmers with the ability to implement > new infix operators, including defining precedence level and > associativity (I can't think of the name right now). You're probably thinking of SML or Haskell. OCaml also allows you to define new infix operators, but the associativities are fixed (and determined by what punctuation you use). From nagle at animats.com Wed Feb 7 12:17:10 2007 From: nagle at animats.com (John Nagle) Date: Wed, 07 Feb 2007 17:17:10 GMT Subject: multithreading concept In-Reply-To: <1170865166.423764.87050@s48g2000cws.googlegroups.com> References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> Message-ID: sturlamolden wrote: > On Feb 7, 2:53 am, "S.Mohideen" > wrote: > This has been discussed to death before. Win32 threads and pthreads > (which is what Python normally uses, depending on the platform) are > designed to stay idle most of the time. They are therefore not a tool > for utilizing the power of multiple CPUs, but rather make certain kind > of programming tasks easier to program (i.e. non-blocking I/O, > responsive UIs). Multithread compute-bound programs on multiple CPUs are how you get heavy number-crunching work done on multiprocessors. Of course, that's not something you use Python for, at least not until it gets a real compiler. It's also the direction games are going. The XBox 360 forced game developers to go that way, since it's a 3-CPU shared memory multiprocessor. That translates directly to multicore desktops and laptops. I went to a talk at Stanford last week by one of Intel's CPU architects, and he said we're going have hundreds of CPUs per chip reasonably soon. Python needs to get ready. John Nagle From ke5crp1 at verizon.net Sat Feb 3 01:32:59 2007 From: ke5crp1 at verizon.net (John Barrett) Date: Sat, 03 Feb 2007 06:32:59 GMT Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170482833.643671.254640@s48g2000cws.googlegroups.com> Message-ID: wrote in message news:1170482833.643671.254640 at s48g2000cws.googlegroups.com... >> >>Can a jet fuel/hydrocarbon fire collapse a steel structure? An >> >>experiment. >> >> > [snip] >> > Run your "experiment" again but add some pure oxygen such as was >> > escaping from the on-board breathing oxygen tanks on the >> > airplanes that were crashed into the WTC. > > No need to do it. We have the pictures of live humans waving from the > gaping holes in the towers where the planes crashed. We have the > testimonies of the fire fighters that the fires were not that hot and > minor. The fuel of the plane which is mainly in the wings were severed > outside the netting and much of them burnt outside in the fireball > that is visible in all the videos. Futhermore, the black soot that was > visible to the naked eye is indicative of bloody cold flame. Also, the > probability of the oxygen tanks oriented in such a way to inject > oxygen onto the steel as in a oxygen cutting torch is extremely low. > These cylinders have a 1000-3000psi of pressure which makes them into > a rocket or an explosive under uncontrolled gas release. And they > would not contaminate the molten metal with any sulfur. Either the > atmosphere inside was oxidising or reducing. If it was oxidising, how > did the sulfur in huge quantities contaminate the molten metal pools? > The official lies to explain sulfur is from the plaster wall. But that > requires a reducing atmosphere with finely divided and intimately > mixed reactants in a calciner where they are continuously rotated and > run for several hours. Yet the fires ran not even for an hour before > the building collapsed. > OK - given all that -- you are left with only one conclusion (or at least I am) -- progressive structural failure, the loss of support where the plane hit was sufficient to put excessive stress on the remaining structural members, resulting in a catastrophic sequential failure -- it doesnt take exotic chemical mixes to put excessive mechanical stress on a system... just chop out enough supports.. it may take time for the remaining supports to deform enough to reach the failure point.. but they will get there, as demonstrated -- occams razor dude -- the least hypothesis is usually the right one -- and I get enough conspiracy theory crap out of my dad -- makes a good movie -- but doesnt pan out in real life -- too many whistle-blowers around !! The city I live in is installing those red-light cameras to catch light-runners -- my dad likes to claim that they manipulate the yellow time to catch people in the intersection and increase revenue from traffic tickets -- I told him to shut up until he got out there with a stop watch and proved it -- and I say the same to you -- PROVE it -- then make some noise -- conjecture and conspiracy theories without proof are a waste of everyones time. -- how do you know the sulphur was in large quantities ?? did you do a chemical analysis ?? or can you produce one done by a reputable metalurgy company ?? Ohhh and by the way -- high sulphur steels are regularly used for machined components -- was the amount of sulphur detected incosistent with what may have been present due to the use of high sulphur steels ?? (where is that metalurgy report again ??) From gagsl-py2 at yahoo.com.ar Wed Feb 28 21:05:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Feb 2007 23:05:17 -0300 Subject: Installing java2python (Newbie) References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172703266.063800.153890@s48g2000cws.googlegroups.com> Message-ID: En Wed, 28 Feb 2007 19:54:26 -0300, MRAB escribi?: > On Feb 28, 5:27 am, "troy.melh... at gmail.com" > wrote: >> you want to run the windows command prompt, which is called "cmd.exe" >> in windows xp. press the "start menu", then select "run", then type >> "cmd.exe" without the quotes. > FYI, a quicker way to the command prompt is Start->All Programs- >> Accessories->Command Prompt. I dont like navigating deep menu structures... I prefer [WindowsKey]+R, cmd, [Enter] -- Gabriel Genellina From jordan.taylor2 at gmail.com Wed Feb 21 12:55:38 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 21 Feb 2007 09:55:38 -0800 Subject: Reading compressed files In-Reply-To: References: <409229.24331.qm@web38705.mail.mud.yahoo.com> Message-ID: <1172080538.754827.233390@v45g2000cwv.googlegroups.com> On Feb 21, 5:21 am, Steve Holden wrote: > Shadab Sayani wrote: > > Hi, > > I have compressed files compressed using different techniques > > (especially unix compress). So I want to have a module that reads any of > > these (.Z,.bz,.tgz files) files and manipulates the data. > > The data has a syntax.It contains > > HEADER (some information) > > BODY (some information) > > FOOTER (some information) > > If it were a normal text file I can get the values corresponding to > > HEADER BODY and FOOTER by open function. > > But here the files are in different format .Z , .bz ,.tgz,.gz .But I > > know these are the only formats.Also I cannot rely upon the extensions > > of the file (a .Z file can have no extension at all).Is there a way to > > identify which file am I reading and then read it?If so how to read it? > > Thanks and Regards, > > Shadab. > > > Send instant messages to your online friendshttp://uk. messenger.yahoo.com > > The usual way is that used by the "file" utility - take a look at the > /etc/magic file to see if you can gain any clues from that. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007- Hide quoted text - > > - Show quoted text - You really need to check the docs and do a little research before asking questions like this. Check out tarfile and zlib modules (use these for opening .tgz, .gz, .bz2 etc), and then go search for the different ways each (.Z, .tgz, .gz, .bz etc) formats their header files so that you can determine what each type of archive is. > The data has a syntax.It contains > HEADER (some information) > BODY (some information) > FOOTER (some information) > If it were a normal text file I can get the values corresponding to > HEADER BODY and FOOTER by open function. > But here the files are in different format .Z , .bz ,.tgz,.gz ... What do you mean if it was a normal text file?? Use 'rb' for reading binary and you shouldn't have a problem if you know the syntax for each of these files. What you need to do is research each syntax and write a regexp or other string searching function to determine each format based on the archive header syntax. While you're at it, open a few archives with a hex editor or using open(...,'rb') and take a look at the syntax of each file to see if you can determine it yourself. Goodluck. Cheers, Jordan From vinjvinj at gmail.com Mon Feb 12 18:10:32 2007 From: vinjvinj at gmail.com (vj) Date: 12 Feb 2007 15:10:32 -0800 Subject: Does anyone have the db_row module compiled for python 2.4 on windows? Message-ID: <1171321832.028911.45730@k78g2000cwa.googlegroups.com> Would really appreciate the binary files for the db_row. Thanks, VJ From steve at holdenweb.com Wed Feb 21 05:21:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Feb 2007 05:21:58 -0500 Subject: Reading compressed files In-Reply-To: <409229.24331.qm@web38705.mail.mud.yahoo.com> References: <409229.24331.qm@web38705.mail.mud.yahoo.com> Message-ID: Shadab Sayani wrote: > Hi, > I have compressed files compressed using different techniques > (especially unix compress). So I want to have a module that reads any of > these (.Z,.bz,.tgz files) files and manipulates the data. > The data has a syntax.It contains > HEADER (some information) > BODY (some information) > FOOTER (some information) > If it were a normal text file I can get the values corresponding to > HEADER BODY and FOOTER by open function. > But here the files are in different format .Z , .bz ,.tgz,.gz .But I > know these are the only formats.Also I cannot rely upon the extensions > of the file (a .Z file can have no extension at all).Is there a way to > identify which file am I reading and then read it?If so how to read it? > Thanks and Regards, > Shadab. > > Send instant messages to your online friends http://uk. messenger.yahoo.com > The usual way is that used by the "file" utility - take a look at the /etc/magic file to see if you can gain any clues from that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From wrongbad at gmail.com Fri Feb 23 02:48:34 2007 From: wrongbad at gmail.com (I V) Date: Thu, 22 Feb 2007 23:48:34 -0800 Subject: Pep 3105: the end of print? References: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> Message-ID: On Tue, 20 Feb 2007 10:46:31 -0800, Beliavsky wrote: > I think the C and C++ committees also take backwards compatibility > seriously, in part because they know > that working programmers will ignore them if they break too much old > code. While that's true, C++ compiler vendors, for example, take backwards compatibility significantly less seriously, it seems to me. A year or so ago, I tried compiling something I'd written for g++ 2, using a then-recent-ish g++ 3; it failed spectacularly. Likewise with Visual C++ 6 and a Visual C++ 2005. The suggestion that "working programmers" will reject python if a major version change introduces some backwards incompatibilities is not borne out by the experience of any other language I am aware of. From fuzzyman at gmail.com Fri Feb 16 19:52:06 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Feb 2007 16:52:06 -0800 Subject: output to console and to multiple files In-Reply-To: <1171669070.320984.283550@q2g2000cwa.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171645473.844315.152020@k78g2000cwa.googlegroups.com> <1171667267.259758.68440@k78g2000cwa.googlegroups.com> <1171669070.320984.283550@q2g2000cwa.googlegroups.com> Message-ID: <1171673526.579692.51040@q2g2000cwa.googlegroups.com> On Feb 16, 11:37 pm, "nathan.sh... at gmail.com" wrote: > On Feb 16, 4:07 pm, garri... at gmail.com wrote: > > > > > On Feb 16, 3:28 pm, "Gabriel Genellina" wrote: > > > > That's ok inside the same process, but the OP needs to use it "from a > > > subprocess or spawn". > > > You have to use something like tee, working with real file handles. > > > I'm not particularly familiar with this, but it seems to me that if > > you're trying to catch stdout/stderr from a program you can call with > > (say) popen2, you could just read from the returned stdout/stderr > > pipe, and then write to a series of file handles (including > > sys.stdout). > > > Or am I missing something? =) > > > ~G > > That works, but it isn't live streaming of stdout/stderr. Most of the > time, if you stream both, one could lock the process, or have the > stdout/stderr printed in the wrong order. Everytime I've looked to do something like this (non-blocking read on the stdout of a subprocess) I've always come back to the conclusion that threads and queues are the only reasonable way (particularly on windows). There may be a better solution using select. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From S.Mientki-nospam at mailbox.kun.nl Fri Feb 16 16:45:02 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 16 Feb 2007 22:45:02 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> ifti_crazy at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language but i > am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net > > so will you please guide me which GUI based language has worth with > complete OOPS Characteristics Although the GUI of Python is not as good as VB, (although others in this group will definitely have a different opinion), the beautiful thing about Python is, that you can easily embed /encapsulate it in VB, giving you the best of both worlds. cheers, Stef Mientki From lrahuel.notgood at voila.fr Thu Feb 15 12:13:34 2007 From: lrahuel.notgood at voila.fr (Laurent Rahuel) Date: Thu, 15 Feb 2007 18:13:34 +0100 Subject: The Python interactive interpreter has no command history References: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> Message-ID: <45d494c1$0$5104$ba4acef3@news.orange.fr> Hi, You need to have readline installed. Laurent ThomasC wrote: > Hello, > > How to configure Python2.5's interactive interpreter to get command > history ? > > I always got ^[[A and ^[[B . > > Thank you !! > > Thomas# From gagsl-py at yahoo.com.ar Fri Feb 2 11:44:40 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 2 Feb 2007 13:44:40 -0300 Subject: Interpreter window References: <1170417263.849798.151010@k78g2000cwa.googlegroups.com> <1170418796.996964.27350@q2g2000cwa.googlegroups.com> Message-ID: "Nils Overas Bergen" escribi? en el mensaje news:1170418796.996964.27350 at q2g2000cwa.googlegroups.com... > On 2 Feb, 13:07, "skyofdreams" wrote: >> "Nils Overas Bergen" >> 1170417263.849798.151... at k78g2000cwa.googlegroups.com... >> >> >I have created a Python application in Windows XP which uses >> > WxWidgets. When I start the application from the Python interpreter I >> > get one empty interpreter window in addition to the application >> > window. Is there a way to close the interpreter window without closing >> > the application? Or, can I start the interpreter and the application >> > script without starting the interpreter window? >> >> do you mean console window? >> you can try pythonw.exe instead of python.exe > > Thanks! Now my application starts without the console window. And, if you rename the .py to .pyw, it will open with pythonw.exe by default. -- Gabriel Genellina From sjdevnull at yahoo.com Sat Feb 17 15:01:53 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 17 Feb 2007 12:01:53 -0800 Subject: why I don't like range/xrange In-Reply-To: <45d744ad$0$30359$426a74cc@news.free.fr> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <45d61e34$0$29759$426a74cc@news.free.fr> <45d744ad$0$30359$426a74cc@news.free.fr> Message-ID: <1171742513.441273.87130@v33g2000cwv.googlegroups.com> Bruno Desthuilliers wrote: > Roel Schroeven a ecrit : > > Bruno Desthuilliers schreef: > > > >> stdazi a ecrit : > > > > > >>> for (i = 0 ; i < 10 ; i++) > >>> i = 10; > >> > >> > >> for i in range(10): > >> i = 10 > >> > >> What's your point, exactly ? > > > > > > In the first iteration, i is set equal to 10. Then, before starting the > > second iteration, i is incremented to 11; then the loop condition is > > checked and results in false. So the loop terminates after the first > > iteration. > > oops - my bad. But why would one do so when a break would do the trick: > for i in range(10): > break After the C loop finishes, i is 11. After the python loop-with-break finishes, i is 0. That may effect later code. From tdelaney at avaya.com Sun Feb 25 18:05:11 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 26 Feb 2007 10:05:11 +1100 Subject: BeautifulSoup modified to use weak refs and avoid circular links. Message-ID: <2773CAC687FD5F4689F526998C7E4E5F07446C@au3010avexu1.global.avaya.com> John Nagle wrote: > "weakref.proxy()" probably should work that way. > Weakref proxies are supposed to be transparent, but they're not > quite transparent enough. Submit a patch to SourceForge. Please don't use tabs in email/usenet postings - use 4-space indents. "return" is not a function, and comparisons with "None" should nearly always use "is". I've also changed backref() to use isinstance(obj, tuple) (available in Python 2.2 and later): def backref(p): if p is None: return None if isinstance(p, (weakref.ProxyType, weakref.CallableProxyType)): return p return weakref.proxy(p) Tim Delaney From laurent.pointal at limsi.fr Wed Feb 7 03:52:20 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 07 Feb 2007 09:52:20 +0100 Subject: How to prevent from race conditions to share data between many process and thread in python In-Reply-To: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> References: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> Message-ID: mars a ?crit : > I use TurboGears to do some web service. TurboGears use cherrypy. When > web browser access this site, the cherrypy will call my python > program. So my program looks like a lib. When web browser access the > site, the http server will fock a process or gerenate a thread. I need > share some data or operate some files. How can I prevent from race > conditions. Is there any way can I lock this. > Thank you in advance! See in the cookbook: http://aspn.activestate.com/ASPN/search?query=locking&x=0&y=0§ion=PYTHONCKBK&type=Subsection And test/choose one solution... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252495 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 ... A+ Laurent. From bignose+hates-spam at benfinney.id.au Sat Feb 3 03:50:34 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Feb 2007 19:50:34 +1100 Subject: main References: Message-ID: <87sldnsjz9.fsf@benfinney.id.au> fatwallet961 at yahoo.com writes: > is the main function in python is exact compare to Java main method? > all execution start in main which may takes arguments? There's no such thing in Python; a module is executed sequentially, with no particular regard to the names of any of the attributes. There is, though, a convention of writing a module that can be either imported or executed as a program, by testing inside the module whether the current module name is the magic string "__main__". === foo.py === # This code is executed whether or not this module is the main module print "Module foo.py is running with name:", __name__ if __name__ == '__main__': # This block is executed only if the module is the main program module print "Module foo.py is the main program" === foo.py === === bar.py === import foo print "Module bar.py is running with name:", __name__ === bar.py === ===== $ python ./foo.py # Run foo.py as a program Module foo.py is running with name: __main__ Module foo.py is the main program $ python ./bar.py # Run bar.py as a program, which imports foo.py as a module Module foo.py is running with name: foo Module bar.py is running with name: __main__ ===== That allows the following idiom: > if __name__ == "__main__": > sys.exit( main(sys.argv) ) All the rest of the code is executed whether or not the program is the main module; but right at the end, after defining all the attributes and functions and classes etc., this test says *if* this module is the main program, then *also* execute the "main" function (and then exit Python with the return value from that function). The benefit of this is that this module, designed to be run as a program, is *also* designed to be imported by other programs so that its functions etc. can be used as required, *without* necessarily running the main function. -- \ "If I haven't seen as far as others, it is because giants were | `\ standing on my shoulders." -- Hal Abelson | _o__) | Ben Finney From wolf_tracks at invalid.com Sat Feb 10 21:43:40 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 11 Feb 2007 02:43:40 GMT Subject: Python 2.4 pdf Tutorial--Available In-Reply-To: References: <1hpzh.5885$4H1.5133@newssvr17.news.prodigy.net> Message-ID: Gabriel Genellina wrote: > En Sat, 10 Feb 2007 21:20:43 -0300, W. Watson > escribi?: > >> Gabriel Genellina wrote: >>> En Sat, 10 Feb 2007 16:45:08 -0300, W. Watson >>> escribi?: >>> >>>> I was able to download the 2.5 tutorial, but think I may need the 2.4 >>>> tutorial (Guido van Rossum) if it exists. Anyone know where to find it? >>> >>> Go to http://docs.python.org/ and follow the link "Locate previous >>> versions" >>> >> Thanks. Found the 2.4 Python Tutorial web page by Guido van Rossum, but >> would like the pdf. > > Go to http://docs.python.org/ > Click on "Locate previous versions" > Click on "Python 2.4.4" (latest release on the 2.4 series) > Click on "Download all these documents" > Choose your format (PDF), page size (PDF A4 or PDF Letter), and your > favorite compression format (Zip or bzip2) and download it. > You get the whole documentation in the chosen format, not only the > tutorial. > On that same page, it says: "These documents are not available for > download individually." > > --Gabriel Genellina > Thanks again. I may get the hang of this eventually. It looks like a pattern is developing. :-) Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two billion years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From thomasbartkus at comcast.net Sat Feb 24 13:04:45 2007 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Sat, 24 Feb 2007 12:04:45 -0600 Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <1171901023.751608.280430@a75g2000cwd.googlegroups.com> Message-ID: On Mon, 19 Feb 2007 08:03:43 -0800, Andy Dingley wrote: > GUI-based" is fairly unimportant as it's just how you build your > programs, not what they do afterwards Most user apps. require 95% of coding effort to provide a usable user interface and 5% effort on the algorithmic meat. The "afterwards" you allude to. So why do we still endure so much programming effort on the unimportant part? Because elegent algorithms require bullet proof and intuitive user interfaces or people won't use or buy your software. > GUI programs are less important now than they were a few years ago, > owing to the huge importance of the web and HTML. Now with html the programming load rises to about 99.8% effort for the user interface and 0.2% on the algorithmic core. All that coding effort wasted on a user interface that looks and works like crap. The top poster is quite correct to ask for a system like VB6 that banishes the problem of user interface coding to the trivial role it deserves. Why should a programmer waste even so much as 10% of his effort to throw together a standard interface with ordinary textboxes, labels, and option buttons? Over and over again? Thomas Bartkus From wolf_tracks at invalid.com Thu Feb 8 19:24:04 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 09 Feb 2007 00:24:04 GMT Subject: Re-installing Numeric and PIL Files In-Reply-To: References: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> <45CBB3CA.7010501@invalid.com> Message-ID: <45CBBF26.9020405@invalid.com> Robert Kern wrote: > W. Watson wrote: > >> Here's the program I ran. >> >> ### begin >> #!/usr/bin/python >> >> # Check mysys >> >> import sys >> print sys.executable >> >> ### end >> >> It put up a black screen in a flash and disappeared. > > Run it from the terminal or execute those lines in the interactive interpreter > in IDLE. Also, you may want to use the Tutor list, instead of comp.lang.python. > It is more geared towards the questions you are asking. > > http://mail.python.org/mailman/listinfo/tutor > I entered each line in the shell, and the output shows C:\Python25\pythonw.exe, so it's not using 2.4. How do I change that? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two million years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From troy at gci.net Wed Feb 21 18:12:26 2007 From: troy at gci.net (Troy Melhase) Date: Wed, 21 Feb 2007 14:12:26 -0900 Subject: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API Message-ID: <200702211412.27065.troy@gci.net> IbPy - Interactive Brokers Python API ===================================== IbPy 0.7.0-9.00 Released 21 Feb 2007 What is IbPy? ------------------------------------------------------------------------------ IbPy is a third-party implementation of the API used for accessing the Interactive Brokers on-line trading system. IbPy implements functionality that the Python programmer can use to connect to IB, request stock ticker data, submit orders for stocks and futures, and more. What's new in this release? ------------------------------------------------------------------------------ IbPy is all new. TWS API version 9.00 is supported. IbPy is now generated by machine translation of the reference Java source code provided by Interactive Brokers. The translation is made possible by the java2python_ package. This version has 100% feature parity with the reference implementation. All API calls are supported, as are all options of each call. An additional interface (similar to the interface provided by earlier IbPy releases) is also included. Because the sources are translated, future versions of the TWS API will be supported in a matter of hours or days (not weeks or worse). Where can I get IbPy? ------------------------------------------------------------------------------ IbPy is available for download from Google Code: http://ibpy.googlecode.com/files/IbPy-0.7.0-9.00.tar.gz Project page: http://code.google.com/p/ibpy/ How do I use IbPy? ------------------------------------------------------------------------------ See the IbPy wiki page "Getting Started with IbPy": http://code.google.com/p/ibpy/wiki/GettingStarted What are the requirements? ------------------------------------------------------------------------------ IbPy requires Python 2.5 or newer. Previous versions are not supported. TWS requires a web browser capable of executing Sun(R) Java(tm) applets. TWS can also be started directly with Sun(R) Java(tm) and the stand-alone package supplied by Interactive Brokers. What is Interactive Brokers? ------------------------------------------------------------------------------ From the page "`About The Interactive Brokers Group`__": Interactive Brokers conducts its broker/dealer and proprietary trading businesses on 60 market centers worldwide. In its broker dealer agency business, IB provides direct access ("on line") trade execution and clearing services to institutional and professional traders for a wide variety of electronically traded products including options, futures, stocks, forex, and bonds worldwide. In its proprietary trading business IB engages in market making for its own account in about 6,500 different electronically traded products. Interactive Brokers Group and its affiliates now trade 19% of the world???s exchange traded equity options*, and executes approximately 500,000 trades per day. What is Python? ------------------------------------------------------------------------------ From the page "`What is Python?`__": Python is an interpreted, interactive, object-oriented programming language. It is often compared to Tcl, Perl, Scheme or Java. Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as well as to various windowing systems (X11, Motif, Tk, Mac, MFC). New built-in modules are easily written in C or C++. Python is also usable as an extension language for applications that need a programmable interface. The Python implementation is portable: it runs on many brands of UNIX, on Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't listed here, it may still be supported, if there's a C compiler for it. Ask around on comp.lang.python -- or just try compiling Python yourself. The Python implementation is copyrighted but freely usable and distributable, even for commercial use. What Else? ------------------------------------------------------------------------------ IbPy is not a product of Interactive Brokers, nor am I affiliated with IB. I am a satisfied IB customer, of course. IbPy is installed with distutils. Refer to the Python distutils documentation for more information. The digest version is:: $ tar xzf IbPy-0.7.0-9.00.tar.gz $ cd IbPy-0.7.0-9.00 $ python setup.py install The TWS demo system is available here: http://interactivebrokers.com/cgi-pub/jtslink.pl?user_name=edemo The stand-alone TWS and other API software is available from IB: http://interactivebrokers.com/ IbPy is distributed under the New BSD License. See the LICENSE file in the release for details. I'm very interested in your experience with IbPy. Please drop me an note with any feedback you have. Troy Melhase mailto:troy at gci.net .. _java2python: http://code.google.com/p/java2python/ __ http://www.interactivebrokers.com/en/general/about/about.php __ http://python.org/doc/Summary.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bernhard.voigt at gmail.com Thu Feb 8 10:56:44 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 8 Feb 2007 07:56:44 -0800 Subject: Running Application Within Emacs In-Reply-To: References: Message-ID: <1170950204.926643.306510@q2g2000cwa.googlegroups.com> You can call scripts from the interpreter with execfile('script.py'). If you use ipython there is a %run command that executes a script. Enjoy! Bernhard On Feb 7, 3:26 pm, rshep... at nospam.appl-ecosys.com wrote: > My editor is emacs in linux, and I have the python mode enabled. The two > menus -- IM-Python and Python -- allow me to navigate within the loaded > module and open execute buffers, among other things. But, I don't see a way > to run a wxPython application from within the editor as I would from the > command line. > > Is this possible? If so, how? > > Ric From gagsl-py at yahoo.com.ar Tue Feb 13 11:25:54 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 13:25:54 -0300 Subject: Regex highlight html References: <45D1B976.3080704@riddergarn.dk> Message-ID: En Tue, 13 Feb 2007 10:13:26 -0300, NOSPAM plz escribi?: > I want to write a function that highlights html code. Well, it's already done, you have Pygments http://pygments.pocoo.org/ and SilverCity http://silvercity.sourceforge.net/ > I have read the wiki page > http://en.wikipedia.org/wiki/Regular_expressions Ouch... Read some previous posts on why it's not a good idea to use regexps for parsing html code. -- Gabriel Genellina From jstroud at mbi.ucla.edu Thu Feb 15 01:21:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 22:21:43 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Wed, 14 Feb 2007 19:45:14 -0800, James Stroud wrote: >>Steven D'Aprano wrote: >>>Since lists and tuples are completely different objects with completely >>>different usages, what should concatenating a list and a tuple give? >>>Should it depend on the order you pass them? >> >>Is that a guess or just common sense? > > Sorry, is *what* a guess? That it should depend on order. > Conceptually, ints are a subset of floats (they certainly are in pure > mathematics). Automatic coercions from ints to floats makes sense; > automatic coercions the other way rarely do -- should you round up or > round down or truncate? What is right in one application is not right for > another. > > Lists and tuples, on the other hand, are conceptually two distinct data > types. Adding a list to a tuple is no more sensible than adding a list to > a string -- just because they're both sequences doesn't mean adding them > together is meaningful. >>Do you guess with __add__ and __radd__? > > No. If there is an obviously correct behaviour for addition (like with > ints and floats) then I coerce the objects appropriately. If there is no > obviously correct behaviour, I refuse to guess. > > The user's expected behaviour for [1] + (1,) might be to return a list, or > it might be to return a tuple. Since there is no obviously correct > behaviour, the right thing to do is to refuse to guess. I guess we differ on what is obvious. This seems obvious to me: [1] + (1,) => [1, 1] (1,) + [1] => (1, 1) simply becuase the operand on the left should take precendence because its "__add__" is called and its "__add__" returns a list. In essence, as we know the obviously correct behavior for __add__ and __radd__, then it would be the obviously correct behavior that the above would follow. I would venture to guess that most people would intuitively consider the above behavior correct, simply because the information content difference between a list versus a tuple is non-existent (outside of the information that one is a list and the other a tuple). Why would their types dictate coercion? With ints and floats, as you point out, the reasons that type dictates coercion are obvious and mathematical. Thus, for tuples and lists, it wouldn't make sense to consider one type taking precendence over the other, so we fall back to position, which seems to be the common sense approach. James From __peter__ at web.de Fri Feb 16 08:50:04 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Feb 2007 14:50:04 +0100 Subject: Regex - where do I make a mistake? References: <1171629872.499083.150140@p10g2000cwp.googlegroups.com> <1171632895.567625.129290@l53g2000cwa.googlegroups.com> Message-ID: Johny wrote: > On Feb 16, 2:14 pm, Peter Otten <__pete... at web.de> wrote: >> Johny wrote: >> > I have >> > string="""55. >> > 128 >> > 170 >> > """ >> >> > where I need to replace >> > 55. >> > 170 >> >> > by space. >> > So I tried >> >> > ############# >> > import re >> > string="""55.> > class="test123">128170 >> > """ >> > Newstring=re.sub(r'.*'," ",string) >> > ########### >> >> > But it does NOT work. >> > Can anyone explain why? >> >> "(?!123)" is a negative "lookahead assertion", i. e. it ensures that >> "test" is not followed by "123", but /doesn't/ consume any characters. >> For your regex to match "test" must be /immediately/ followed by a '"'. >> >> Regular expressions are too lowlevel to use on HTML directly. Go with >> BeautifulSoup instead of trying to fix the above. >> >> Peter- Hide quoted text - >> >> - Show quoted text - > > Yes, I know "(?!123)" is a negative "lookahead assertion", > but do not know excatly why it does not work.I thought that > > (?!...) > Matches if ... doesn't match next. For example, Isaac (?!Asimov) will > match 'Isaac ' only if it's not followed by 'Asimov'. The problem is that your regex does not end with the lookahead assertion and there is nothing to consume the '456' or '789'. To illustrate: >>> for example in ["before123after", "before234after", "beforeafter"]: ... re.findall("before(?!123)after", example) ... [] [] ['beforeafter'] >>> for example in ["before123after", "before234after", "beforeafter"]: ... re.findall(r"before(?!123)\d\d\dafter", example) ... [] ['before234after'] [] Peter From sickcodemonkey at gmail.com Sun Feb 18 18:16:22 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Sun, 18 Feb 2007 18:16:22 -0500 Subject: Python Threads Message-ID: <2adc542f0702181516g7bbfb08ga721b568cb528404@mail.gmail.com> Is there anyway to get 2 python threads to talk to one another? I have a GUI which is spawning a thread to make a large calculation (that way the GUI does not appear to be non responsive). I am trying to attach a progress bar to the threaded action. As the thread is calculating data, I would like it to communicate with the other (progress) thread to update it. On windows, when I spawn the progress bar without using threads, the progress bar stalls.... <> So I thought by spawning the progress bar by using a thread, it would not stall....... If anyone can think of another technique.... I am all ears. ~~~~~~~~~~START SAMPLE~~~~~~~~~~~~~~~~~~~~~~~~ def progressBar(status): mroot = Tkinter.Tk(className='Worker Bee') metric = Meter(mroot, relief='ridge', bd=3) metric.pack(fill='x') metric.set(status, 'Starting ...') def fetchFiles(file1,file2,file3): method = '' print file1 print file2 print file3 f1 = fopen(file1) a = f1.readlines(); f1.close() d1 = {} for c in a: for m in mailsrch.findall(c): d1[m.lower()] = None ####I Would like to Update the progress bar running in the other thread here. ## set status = .33 and update progress bar. if file2 == '': domain(d1,file3) #... def startProc(): status = 0 thread.start_new_thread(fetchFiles, (f1name,f2name,f3name,)) thread.start_new_thread(progressBar, (status,)) ~~~~~~~~~~END SAMPLE~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Thu Feb 15 08:13:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 10:13:17 -0300 Subject: AUX File Writing Error References: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> <1171521299.082449.67940@s48g2000cws.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 03:34:59 -0300, John Machin escribi?: > On Feb 15, 4:03 pm, thewritersc... at gmail.com wrote: >> Is there any way I can create an "AUX.csv" file without the error? > > Probably not. AUX, CON, NUL, PRN, LPT, COM1, COM2 etc (with or without > an extension) are reserved in Windows for specific devices for > compatibility with MS-DOS 1.00 programs, which did that for > compatibility with CP/M. (This is OT now) Do you know why "AUX.csv" is invalid too? I can accept that AUX (without extension) is an invalid filename, but it is quite different from "AUX.csv" -- Gabriel Genellina From joja15 at gmail.com Wed Feb 14 13:02:14 2007 From: joja15 at gmail.com (joja15 at gmail.com) Date: 14 Feb 2007 10:02:14 -0800 Subject: How to ping and shutdown a remote computer? In-Reply-To: <45d33458$0$417$426a74cc@news.free.fr> References: <1171469222.163242.157040@q2g2000cwa.googlegroups.com> <45d33458$0$417$426a74cc@news.free.fr> Message-ID: <1171476134.492731.156740@q2g2000cwa.googlegroups.com> On Feb 14, 10:09 am, Christophe wrote: > joj... at gmail.com a ?crit : > > > > > I am working on a Python script to perform as a remote computer > > manager. So far I have a WOL function working and I would like to add > > the ability to show if a machine is on or off (I figured I would do so > > by pinging the machine and seeing if I get a response). I would also > > like to add the ability to remotely shutdown a computer from the > > python script. Does anyone have a code snippet for pinging an IP, a > > code snippet for shutting down a remote Windows XP machine, and a code > > snippet for sending a HTTP request? > > > Here is my current setup: > > > - PC running python script > > - FreeNAS (media server running on FreeBSD. Can be shutdown from web > > interface so I planned on just sending that same web button click from > > the python script to shutdown the FreeNAS server) > > - Windows XP machine with folder share (What packet is sent over the > > network to remotely shutdown a Windows XP machine?) > > import os > os.system("shutdown -s -f") > Try other switches if you want. Requires Windows XP at the minimum. That is a good idea but I don't have Windows XP on the machine performing the shutdown. I should have been more detailed. I said PC but what it is is a Xbox running XBMC: http://www.xboxmediacenter.com I should have been more detailed in that. - John From deets at nospam.web.de Tue Feb 27 07:49:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Feb 2007 13:49:42 +0100 Subject: Is there a technic to avoid this bug References: Message-ID: <54inn6F2115doU1@mid.uni-berlin.de> hg wrote: > Hi, > > In C/C++ I got used to write an expression like so: > > #define TEST 0 > > if (TEST == value) > { > > } > > in order to avoid the usual bug: > if (value = TEST) > { > > } > > In a relatively similar domain, I spent a few hours find this bug: > > value == self.Get_Value() > if value == WHATEVER: > do this > > instead of > value = self.Get_Value() > if value == WHATEVER: > do this > > Is there a way to avoid such a bug with some type of construct ? No. In a language inherent with sideeffects, there is nothing that should force you to not write that. However, it might be that either pychecker or pylint will give you a warning for such statements. Diez From http Thu Feb 22 22:40:24 2007 From: http (Paul Rubin) Date: 22 Feb 2007 19:40:24 -0800 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <7x4ppdhlmu.fsf@ruckus.brouhaha.com> Message-ID: <7xabz5pmmv.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > For a short string like "Python", using an array is a tiny bit slower, at > the cost of more complex code.... if you're converting a long string, > using array is faster. If it is a short string, it doesn't make much > difference. I modified your array version slightly: def flip3(text): n = len(text) mask = ord('U') text = array('b', text) for i in xrange(n): text[i] ^= mask return text.tostring() and I got flip3("Python") a little faster than the listcomp version, but yeah, I was concerned mostly about long strings. For fixed-sized short strings, using array('l') and unrolling the loop makes a big difference: text = "Pythonic" mask = array('l','UUUU')[0] def flip4(text): text = array('l', text) text[0] ^= mask text[1] ^= mask return text.tostring() >>> timeit.Timer('flip1(text)', setup).repeat() # your version [35.932021141052246, 36.262560844421387, 40.019834041595459] >>> timeit.Timer('flip3(text)', setup).repeat() # flip3 above [33.44039511680603, 31.375681161880493, 31.374078035354614] >>> timeit.Timer('flip4(text)', setup).repeat() # flip4 above [15.349261045455933, 15.526498794555664, 15.351589202880859] See http://www.nightsong.com/phr/crypto/p3.py for an encryption routine written this way. From alan.franzoni_invalid at geemail.invalid Tue Feb 27 11:25:30 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Tue, 27 Feb 2007 17:25:30 +0100 Subject: gtk.mainquit is deprecated References: <1172570193.721466.286700@8g2000cwh.googlegroups.com> Message-ID: <3w6o7cbnr45v$.1hvyvdm2i2ffj$.dlg@40tude.net> Il 27 Feb 2007 01:56:33 -0800, awalter1 ha scritto: > But I don't want to quit the application, I need only to close the > window. > My application includes others places where "self.window.destroy()" > instruction is used and the execution is done without warning. > Very strange. But does then the application end, as if gtk.main_quit() were called? If it's the case, it's very likely you connected the 'destroy' signal on that very window and you set gtk.mainquit() as the callback. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From steve at REMOVEME.cybersource.com.au Wed Feb 28 21:01:55 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 01 Mar 2007 13:01:55 +1100 Subject: Changing directories in oswalk [was Re: Walk thru each subdirectory from a top directory] References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <1172529799.827628.321760@p10g2000cwp.googlegroups.com> <12ua1bo77j0n724@corp.supernews.com> Message-ID: On Wed, 28 Feb 2007 08:38:41 +0100, Peter Otten wrote: > Does the problem occur if you pass an absolute path to > os.walk()/os.path.walk()? Well, arguably the problem is that macunpack insists on writing to the current working directory. Or the problem is that os.walk sets the working directory to the initial argument when you start, and then keeps it until it finishes. (Arguably that's the right behaviour.) You can play around with this to check: def walker(where): """Walk through a directory tree, printing the current working directory." def _walk(data, dirname, files): print "dirname = '%s'; wd = '%s'" % (dirname, os.getcwd()) os.path.walk(where, _walk, None) For those times when os.walk's behaviour doesn't mesh well with that of the external program you are calling (like macunpack) is there an alternative to: - save the cwd; - change directories; - call the program; - return to the saved directory ? -- Steven D'Aprano From david.wishnie at gmail.com Fri Feb 23 15:29:38 2007 From: david.wishnie at gmail.com (David Wishnie) Date: Fri, 23 Feb 2007 23:29:38 +0300 Subject: Found a product for running Python-based websites off CDROM -have anybody tried it? In-Reply-To: References: Message-ID: Hello, Thank you for your input! We've looked at XAMPP, and it has the following disadvantages compared to Stunnix: * it's not targeted for putting to CDs at all (it's "unzip and run apache and stuff" type of thing). This means it probably can't autochoose port numbers for mysql and http. It has no functionality for easy stopping of webserver and stuff from inside a script (that allows to release media on Linux and OSX). It's seems not to be tested for running from read-only media. It has no "showing logo at startup" functionality. * XAMPP for Linux and OSX is considered beta * XAMPP is unsupported as a whole * XAMPP for Linux and OSX seem not to support Tomcat and mod_python * XAMPP for OSX won't work on OSX 10.3 * Even if one will be able to somehow create a CD with XAMPP, the database files and content of document root needs to be replicated for each platform. The only advantage of XAMPP is the price. But given a time needed for highly-skilled enginer (with good programming skills) to spend on XAMPP to make it ready for creating commercial CDs for Windows, Mac OSX - cost of Stunnix tool is very attractive, and don't forget about updates and support. -David On 2/20/07, Don Taylor wrote: > David Wishnie wrote: > > Hello, > > > > Recently I've found a product that allows to create CDs or DVDs with > > mod_python -based websites > > (and CGI python of course) so that apache-based webserver, python and > > mod_python are run directly > > off CD on Windows, MacOS X and Linux at the same time (also it seems > > to support perl, java, > > php and mysql + SQLite as databases). > > > > http://www.stunnix.com/prod/aws/overview.shtml > > > > Have anybody tried it? I'm considering to use it for several projects. > > > > Thanks, > > David > > > That is an expensive product ($789) especially considering it mostly > consists of FOSS pieces. > > I found XAMPP, a FOSS, that is almost the same thing: > > http://portableapps.com/apps/development/xampp > > and this thread for getting mod_python running (scroll down a bit to the > second post): > > http://www.apachefriends.org/f/viewtopic.php?t=21169&highlight=python > > I have not tried this yet. > > Don. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gisdudester at gmail.com Sun Feb 18 11:12:20 2007 From: gisdudester at gmail.com (GISDude) Date: 18 Feb 2007 08:12:20 -0800 Subject: search cursor in pythonwin 2.1 Message-ID: <1171815140.829723.87940@a75g2000cwd.googlegroups.com> Hi all. I am trying to create a little script(I think) that will basically use a search cursor. I am a GIS(geographic information systems) Analyst and in our software(ESRI ARCGIS 9.1) ESRI has implemented Python 2.1 as the scripting language of choice. In my script I'm going thru a dbf file and extracting NON-NULL values in a field. What I need to do with that is create a new dbf table with the values I found in it. Here is my sample code so far: # This is a basic script for searching thru a table # seeing if a field has a value, then writing that record # to a brand new dbf # # Import basic modules import win32com.client, sys, os, string # Create the basic Geoprocessor Object GP = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") # Make sure to setup proper licensce level from ESRI GP.SetProduct("arcview") # Set the input workspace - I WONT USE THE ARGUMENT DIALOG BOX GP.Workspace = "E:/IntermediateGISProgrammingGEOG376/labs/ neighborhoods" # THIS IS THE SPOT WHERE I'M MESSING UP # I THINK AT THIS POINT I NEED TO: # 1: OPEN THE SHAPEFILE # 2: INITIALIZE THE FC VARIABLE # 3: USE THE SEARCHCURSOR TO FIND THE RECORDS THAT HAVE A VALUE IN THE NAME FIELD # I looked in the Select Help file and a number of items popped up. # However, I opened up Select -> analysis and it shows how to select # from a shapefile. I assume this is what I need? GP.Select_Analysis("neighborhoods.shp", "neighborhoods_names.shp", ' "Names" <> \ "null\" ') #at this point I'm stuck. how do I query out a NON- NULL value? #or a value in the Names field? Could anyone throw me a bone over here? TIA From steve at holdenweb.com Mon Feb 19 16:43:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Feb 2007 16:43:58 -0500 Subject: Declare a variable global In-Reply-To: <1171907496.269876.295200@p10g2000cwp.googlegroups.com> References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> <1171907496.269876.295200@p10g2000cwp.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > On Feb 19, 11:09 am, Jean-Paul Calderone wrote: >> On 19 Feb 2007 09:04:19 -0800, "ying... at gmail.com" wrote: >> >>> Hi, >>> I have the following code: >>> colorIndex = 0; >>> def test(): >>> print colorIndex; >>> This won't work. >> Are you sure? >> >> exarkun at charm:~$ cat foo.py >> colorIndex = 0 >> >> def test(): >> print colorIndex >> >> test() >> exarkun at charm:~$ python foo.py >> 0 >> exarkun at charm:~$ >> >> The global keyword lets you rebind a variable from the module scope. It >> doesn't have much to do with accessing the current value of a variable. >> >> Jean-Paul > > Thanks. Then I don't understand why I get this error in line 98: > > Traceback (most recent call last): > File "./gensvg.py", line 109, in ? > outdata, minX, minY, maxX, maxY = getText(data); > File "./gensvg.py", line 98, in getText > print colorIndex; > UnboundLocalError: local variable 'colorIndex' referenced before > assignment > > > Here is my complete script: [... script elided ...] Well, now I've seen the error message I don't even need to see the script to explain what's going on. Unfortunately in your (entirely creditable) attempt to produce the shortest possible script that showed the error you presented a script that *didn't* have the error. Python determines whether names inside a function body are local to the function or global to the module by analyzing the function source. If there are bindings (assignments) to the name inside the body then the name is assumed to be local to the function unless a global statement declares otherwise. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From __peter__ at web.de Sun Feb 25 05:41:36 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 25 Feb 2007 11:41:36 +0100 Subject: Find the first element that meets the condition References: <1172397176.024303.257890@t69g2000cwt.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > I have a list and I want to find the first element that meets a > condition. I do not want to use 'filter', because I want to come out > of the iteration as soon as the first element is found. > I have implemented it this way, may be, there should be a built in > hiding somewhere in the standard libraries? > > def exists(iterable, condition): > ''' > Return the first element in iterble that meets the condition. > ''' > for x in iterable: > if condition(x): > return x > raise Exception('No element meets the given condition.') > > > >>>> exists(xrange(1000), lambda x: x>13) > 14 If you are only interested in existence you can use any() (new in Python2.5) >>> any(x>13 for x in xrange(1000)) True Otherwise there is itertools.ifilter() a lazy variant of the filter() builtin: >>> import itertools >>> items = iter(xrange(1000)) # just to prove... >>> itertools.ifilter(lambda x: x > 13, items).next() 14 >>> items.next() # that ifilter has consumed only the first 15 items 15 You may want to wrap the ifilter() call to get a more sensible exception, say ValueError instead of StopIteration: # untested def findfirst(items, predicate=bool): for item in itertools.ifilter(predicate, items): return item raise ValueError("No matching element") Peter From mike.klaas at gmail.com Sat Feb 17 00:22:04 2007 From: mike.klaas at gmail.com (Klaas) Date: 16 Feb 2007 21:22:04 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> <1171662509.736715.54400@t69g2000cwt.googlegroups.com> Message-ID: <1171689724.527879.304760@v45g2000cwv.googlegroups.com> On Feb 16, 2:31 pm, Sam wrote: > pass > except (ImportError, SyntaxError): > # python 3.0 > print2 = print > SyntaxError: invalid syntax > > Any and all aliasing must happen in compat26.py. My suggested solution is this: Good catch. Point is that it is not impossible. -mike From gagsl-py at yahoo.com.ar Mon Feb 5 18:46:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:46:45 -0300 Subject: Decimating Excel files References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> Message-ID: En Sat, 03 Feb 2007 18:52:10 -0300, mensanator at aol.com escribi?: > On Feb 3, 1:43?pm, gonzlobo wrote: >> We have a data acquisition program that saves its output to Excel's >> .xls format. Unfortunately, the programmer was too stupid to write >> files the average user can read. >> >> I'd like some advice on how to go about: >> 1. Reading a large Excel file and chop it into many Excel files (with >> only 65535 lines per file) > > An Excel sheet only has 65535 lines. Or do yo mean it has > multiple sheets? As I understand the problem, the OP has a program that generates the .xls files, but it's so dumb that writes files too large for Excel to read. I'd try the "xlrd" package - it is capable of reading Excel files on any platform. -- Gabriel Genellina From Finger.Octopus at gmail.com Fri Feb 9 10:28:00 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 9 Feb 2007 07:28:00 -0800 Subject: Database Programming with Python Message-ID: <1171034880.089616.113380@p10g2000cwp.googlegroups.com> Hi I wanted to connect Python to Ms-Access database using ADO or ODBC. I have Python 2.5 and on mxODBC site, it has no higher version build than 2.4. Moreoever, mxODBC is required for ADODB. Can anyone guide me on this what should I do to make it work on Python 2.5? I have python 2.5 running on server. From skip at pobox.com Thu Feb 8 23:18:18 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 8 Feb 2007 22:18:18 -0600 Subject: Looking for a MoinMoin guru - MoinMoin+SpamBayes == no wiki spam? In-Reply-To: <1170993580.119528.112650@s48g2000cws.googlegroups.com> References: <1170981347.050263.181360@j27g2000cwj.googlegroups.com> <1170993580.119528.112650@s48g2000cws.googlegroups.com> Message-ID: <17867.62986.983397.349558@montanaro.dyndns.org> T> I think it's a fantastic idea, myself. I think it should work well. T> It's probably important to filter the edit, not the whole article, T> otherwise the ham might obscure the spam. That would be a good second phase. My experience with most wiki spam so far is that the spammers replace the entire content of the page with their junk. My major concern at the moment is simply to get the MoinMoin mechanism working. I applied SpamBayes to the form submissions of another website (I was the author, so I was familiar with the server side code). It worked great there, so I'm hopeful it will do well in this environment as well. Skip From gagsl-py at yahoo.com.ar Tue Feb 13 15:00:24 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 17:00:24 -0300 Subject: _ssl.pyd is buggy? References: <45D1F804.8050609@designaproduct.biz> <45D21636.1080903@designaproduct.biz> Message-ID: En Tue, 13 Feb 2007 16:49:10 -0300, Laszlo Nagy escribi?: >> Services usually run under the LOCAL_SERVICE account, which is rather >> limited on what it is allowed to do (It has no access to network shares, >> by example). Perhaps this is afecting your program. >> > I'm sorry, it is not. My service only uses the standard output, writes > into different files and uses the http and https protocol. It does not > use microsoft networking, only TCP/IP. It is actually a spider that > downloads information from some web sites. The most strange thing is > that the main thread is enclosed in a try - except statement, and it > should log all exceptions into a file. The file is even not created, and > I see no way to debug it. Can a python win32 service program be debugged? Do you catch all exceptions on your working thread too? You didn't post that code. -- Gabriel Genellina From marco at waven.com Tue Feb 6 20:09:00 2007 From: marco at waven.com (Marco) Date: Wed, 7 Feb 2007 09:09:00 +0800 Subject: IOError: [Errno 4] Interrupted system call Message-ID: <5c62a320702061709s41dd7af2kd99be68e3afe3d58@mail.gmail.com> Hello,every one, I meet a question: in my old script, I usually use os.popen2() to get info from standard unix(LinuX) program like ps,ifconfig... Now, I write a OO-based programme, I still use os.popen2( check whether mplayer still working via ps command ), but some things I got the following message: Traceback (most recent call last): File "./mkt.py", line 351, in loop_timeout self.process(self.event.get_next()) File "./mkt.py", line 361, in process self.player.play(command[1]) File "./mkt.py", line 107, in play if self.is_playing(): File "./mkt.py", line 78, in is_playing info = rfd.readlines() IOError: [Errno 4] Interrupted system call why? Thank you! -- LinuX Power From ruan at jcmills.com Wed Feb 7 15:27:48 2007 From: ruan at jcmills.com (John) Date: Wed, 7 Feb 2007 15:27:48 -0500 Subject: Can somebody give me a python code for this? References: Message-ID: I solved it myself. Don't bother. "John" wrote in message news:eqd8hr$44dn$1 at netnews.upenn.edu... > Given an array of elements, look at it as a binary tree. Start at the last > interior node, and downheap it. Then downheap the previous interior node, > and continue in this fashion, up to the root. > From boyandin at gmail.com Thu Feb 8 03:18:46 2007 From: boyandin at gmail.com (Sagari) Date: 8 Feb 2007 00:18:46 -0800 Subject: Referencing vars, methods and classes by name Message-ID: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> Greetings, Sorry for a newbiw question: what is a most elegant and/or effective way to reference vars, methods and classes by their names in Python? To illustrate, PHP code: $a = ''b'; $$a = $something; // assign to $b $$a($p1); // call function b($p1) $obj->$a(); // call method b() of the instance $obj What is the Python way of performing the same indirections? References to online docs/articles related to the subject are very welcome. Thank you! Konstantin From phil at riverbankcomputing.co.uk Wed Feb 28 04:45:54 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 28 Feb 2007 09:45:54 +0000 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <1172654773.047745.83250@8g2000cwh.googlegroups.com> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172654773.047745.83250@8g2000cwh.googlegroups.com> Message-ID: <200702280945.54120.phil@riverbankcomputing.co.uk> On Wednesday 28 February 2007 9:26 am, boris.smirnov at gmail.com wrote: > On Feb 28, 10:22 am, Phil Thompson > > wrote: > > On Wednesday 28 February 2007 9:00 am, boris.smir... at gmail.com wrote: > > > On Feb 28, 9:07 am, boris.smir... at gmail.com wrote: > > > > On Feb 28, 8:56 am, Phil Thompson > > > > > > > > wrote: > > > > > On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > > > > > > When your programs stops with the error, it should also be > > > > > > printing a stack trace. This is a list of all the functions that > > > > > > have been called when Python had the problem. > > > > > > > > > > > > You shouldn't have to do anything extra to get the stack trace. > > > > > > > > > > The error is raised in Qt and aborts immediately. It never gets > > > > > back to Python to generate a trace. > > > > > > > > > > He needs to produce a short and complete test which demonstrates > > > > > the problem, then we can point out where the QPaintDevice is being > > > > > created. > > > > > > > > > > Phil > > > > > > > > OK, but before I do a complete test, could anybody tell/explain me > > > > why the same file is working on Windows? > > > > Did anybody already meet with something similar Win vs. Linux? > > > > > > > > b. > > > > > > Here is my simple script: > > > > > > import sys > > > from qt import * > > > class Optimizer(QWidget): > > > def __init__(self, parent = 0): > > > QWidget.__init__(self) > > > QGridLayout(self) > > > if __name__ == '__main__': > > > a = QApplication (sys.argv) > > > mywidget = Optimizer() > > > a.exec_loop() > > > > > > This produces this: > > > > python qt_script_bs_070228.py > > > > > > QPaintDevice: Must construct a QApplication before a QPaintDevice > > > > > > Any suggestions here? > > > > It works fine for me. > > > > > Thanks > > > > > > BTW: One question: > > > when I use "import qt" instead of "from qt import *" I get this error: > > > Traceback (most recent call last): > > > File "mscarideidtool_bs_070228.py", line 4, in ? > > > class Optimizer(QWidget): > > > NameError: name 'QWidget' is not defined > > > > > > What is the difference between "import qt" and "from qt import *" ? I > > > thought that these are the same. > > > > The first creates a new namespace called "qt" and imports the module's > > objects into it. To reference those objects you have to include the > > namespace name. > > > > The second imports the module's objects into the current namespace. > > > > Phil- Hide quoted text - > > > > - Show quoted text - > > OK, I have to apologize because I didn't mention that I use python > version 2.2.1, could it be the problem here? Bugs or something? I have > to use this version since it was delivered with a software that we use > here. So what versions of Qt, PyQt and SIP are you using? Were these included with the software you are using? If so, what is that software? Phil From sickcodemonkey at gmail.com Tue Feb 27 21:39:11 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 27 Feb 2007 21:39:11 -0500 Subject: Py2EXE problem Message-ID: <2adc542f0702271839u472dc57aj8c9bc6d7ad3c660d@mail.gmail.com> Maybe this is not the board to post this, but hopefully with all of the python experts out there maybe one of you have encountered this. I wrote an application that sends an email with an attachment. When I run it, it runs great with no issues what-so--ever. When I thought I was finally finished, I created an executable file using py2exe. Now, when I run the application, I am getting the following error: --------------------------------------------------- Exception in Tkinter callback Traceback (most recent call last): File "Tkinter.pyc", line 1403, in __call__ File "Suppression.py", line 401, in startProc File "Suppression.py", line 318, in emailInfo File "email\__init__.pyc", line 79, in __getattr__ ImportError: No module named multipart --------------------------------------------------- Any ideas on how to get around this one? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sun Feb 4 14:16:53 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Feb 2007 19:16:53 GMT Subject: Python does not play well with others In-Reply-To: <1170600807.504088.80150@m58g2000cwm.googlegroups.com> References: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170600807.504088.80150@m58g2000cwm.googlegroups.com> Message-ID: Paul Boddie wrote: > I was really advocating improvements to the built-in SSL support, > anyway, which was also what the complainant was suggesting before > people started asking him mistakenly why he thought that Python was > weakened by some third party packages (PyOpenSSL, M2Crypto). The real problems are with integration of modules that aren't written in Python. Python-only modules don't have the version compatibility problems which C modules do. Loading a Python-only module from an external source is usually not a big deal. Building a C module, especially one with dependencies on other components, can be a big deal. So, focus on problems with modules which have C components. John Nagle From dingbat at codesmiths.com Wed Feb 14 12:04:17 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 14 Feb 2007 09:04:17 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: <1171472657.567241.302690@h3g2000cwc.googlegroups.com> On 14 Feb, 16:23, Neil Cerutti wrote: > str.translate is what I'd do. That's what I hope to do too, but it might not be possible (for the live, complex example). It looks as if I have to make a test, then process the contents of the code differently depending. There might well be a translation inside this, but I think I still have to have an explicit 3-way switch in there. > How would it being a lambda help you? I'm going to use it in a context where that would make for cleaner code. There's not much in it though. I still don't understand what a lambda is _for_ in Python. I know what they are, I know what the alternatives are, but I still haven't found an instance where it permits something novel to be done that couldn't be done otherwise (if maybe not so neatly). From ruan at jcmills.com Thu Feb 1 22:31:13 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Thu, 1 Feb 2007 22:31:13 -0500 Subject: need help on a data structure problem Message-ID: Not quite related with Python. But my Data Structure course is experiemented on python and there is no data structure group, So I have to post here: Write a procedure (in pseudocode!) to increase the number of buckets in a (closed) hash table. Analyze its time and space complexity. From horpner at yahoo.com Thu Feb 8 15:25:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 8 Feb 2007 21:25:53 +0100 Subject: doctests for interactive functions References: Message-ID: On 2007-02-08, Brian van den Broek wrote: > All classes take an optional argument input_function that > determines how the class instance gets its input. If this is > not provided, it defaults to raw_input. doctest tests reassign > it so that they can be run automatically. What I've done in these cases is create a file containing my test input, and before running the doctests I remap sys.stdin to my file of test data. Then you don't need test code cluttering up your functions. -- Neil Cerutti We don't necessarily discriminate. We simply exclude certain types of people. --Colonel Gerald Wellman From __peter__ at web.de Thu Feb 1 07:52:15 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Feb 2007 13:52:15 +0100 Subject: Help me with this!!! References: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> Message-ID: TOXiC wrote: > Hi all, I've this code: No you don't. > regex = re.compile(r"(?si)(\x8B\xF0\x85\xF6)(?P.*) > (\xC6\x44\x24)",re.IGNORECASE) > file = open(fileName, "rb") > for line in file: > if (match): > print line > file.close() > > It search a text inside that hex value. > It works perfecly on a txt file but if I open a binary file (.exe,.bin > ecc...) with the same value it wont work, why? > Please help! Because the pattern isn't in the file, perhaps. Peter From http Tue Feb 20 11:41:22 2007 From: http (Paul Rubin) Date: 20 Feb 2007 08:41:22 -0800 Subject: file io (lagged values) newbie question References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> <1171984082.488529.76040@p10g2000cwp.googlegroups.com> Message-ID: <7xfy907pe5.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Would it be less crufty if I wrote it as a cryptic one liner without > comments? > > f.write(str(data)[1:-1].replace(',', '') + '\n') That doesn't look terribly cryptic to me, but maybe I'm used to it. > > Try this: f.write(' '.join(str(x) for x in data) + '\n') > That will only work in Python 2.5 or better. It should work in 2.4, I think. Though, I haven't tried 2.5 yet so I can't say from experience whether 2.4 is better than 2.5. Anyway, f.write(' '.join(map(str, data)) + '\n') should work in the whole 2.x series, if I'm not mistaken. From thegeoffmeister at gmail.com Sat Feb 10 18:26:36 2007 From: thegeoffmeister at gmail.com (Geoff Hill) Date: Sat, 10 Feb 2007 23:26:36 GMT Subject: Regular Expressions Message-ID: What's the way to go about learning Python's regular expressions? I feel like such an idiot - being so strong in a programming language but knowing nothing about RE. From horpner at yahoo.com Wed Feb 14 08:41:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 14 Feb 2007 14:41:53 +0100 Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: On 2007-02-13, Sam wrote: > On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn > wrote: >> Well, C++ is a better language than C in many ways. So, if he >> needs to learn one of them, why does it have to be C? >> >> Another reason some people choose C++ over Python for some >> tasks is that they feel that larger programs benefit from >> strong, static type checking. I like both ways, but depending >> on the task, one or the other is better. > > C++ is -not- strongly typed. You can cast anything to void *, > and manipulate it in ways unimaginable. Plus there's the whole > mess that is pointer arithmetic and a weak typesystem... Don't forget the lack of standard garbage collection. Also there's the hell known as exception safety. Python conceptually has many of the same issues with exception safety, but at least memory leaks aren't one of the consequences. I imagine most Python programmers don't even think about exception safety, but probably should be. We just happily raise exceptions willy-nilly, without worrying about our objects remaining in a reasonable state. Or do we? Maybe it's better not to think about it. ;-) > Disclaimer: I am unashamedly in the "C++ Is Evil" camp, and > wholly believe that if you want proper strong, static type > checking, use Haskell, or if you want proper, complete > object-orientation (C++'s primitive types compromise its object > system's integrity, and I believe I've already discussed > casting and pointers), use Python, and if you want > under-the-hood pointer-fu, use C. C++'s standard library seems such a huge win over the C library, that I'd hate to switch back. Of course it has its warts and cancers, but it's an awesome accomplishment. And you *can* get harder-to-use C versions that are basically portable. -- Neil Cerutti A billion here, a billion there, sooner or later it adds up to real money. --Everett Dirksen From fuzzyman at gmail.com Sun Feb 18 09:46:01 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 18 Feb 2007 06:46:01 -0800 Subject: Getting a class name In-Reply-To: <1171804946.810703.45810@a75g2000cwd.googlegroups.com> References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <_DJBh.20322$K8.18088@news.edisontel.com> <1171801487.767555.14150@v33g2000cwv.googlegroups.com> <1171804946.810703.45810@a75g2000cwd.googlegroups.com> Message-ID: <1171809961.229189.71490@p10g2000cwp.googlegroups.com> On Feb 18, 1:22 pm, "Michele Simionato" wrote: > On Feb 18, 1:24 pm, "Fuzzyman" wrote: > > > Why is the __name__ attribute not available to the instance? Why don't > > normal lookup rules apply (meaning that a magic attribute will be > > looked up on the class for instances) ? > > Because __name__ isn't really an attribute, it is a descriptor defined > on > the metaclass: > > >>> type(type.__dict__['__name__']) > > > > Seehttp://users.rcn.com/python/download/Descriptor.htmfor a guide to > descriptors, and the papers by me and David Mertz for a guide to > metaclasses. > Thanks, I'll do some more reading. I got as far as this on my own: My guess is that it is because magic attributes are looked up on the class. When you ask the *class* what its name is, the metaclass answers on its behalf. The class has no real ``__name__`` attribute, so when you ask the instance (which doesn't inherit from the metaclass) you get an ``AttributeError``. Is this right ? In which case, how does the metaclass (typically ``type`` which has many instance) know which answer to supply ? A simple test indicates that the name *is* looked up on the metaclass : .. raw:: html {+coloring} >>> class meta(type): ... __name__ = 'fish' ... >>> class Test(object): ... __metaclass__ = meta ... >>> Test.__name__ 'fish' {-coloring} So maybe ``__name__`` is a propery and ``type`` keeps a dictionary of instances to names, registered in ``type.__new__`` ? Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > Michele Simionato From http Sat Feb 3 10:54:53 2007 From: http (Paul Rubin) Date: 03 Feb 2007 07:54:53 -0800 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> Message-ID: <7xk5yz2q42.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > This is simply not true. J2SE doesn't include a web-framework. J2EE > does, but it's a separate multi-megabyte-download. I thought J2SE comes with JSP. Maybe that's not a "framework" in the fancy sense though. > PHP _is_ a web centered language, so to say it "includes" a > And _both_ of them don't contain DB connectivity modules! J2SE has > JDBC - which is just a bunch of interfaces. You need to download each > and every driver. Hmm, I thought it came with drivers. Maybe those come with the db instead? From mike.klaas at gmail.com Mon Feb 12 17:17:03 2007 From: mike.klaas at gmail.com (Klaas) Date: 12 Feb 2007 14:17:03 -0800 Subject: Help with Optimization of Python software: real-time audio controller In-Reply-To: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> References: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> Message-ID: <1171318623.938922.264640@v45g2000cwv.googlegroups.com> On Feb 11, 6:40 pm, craiglewis... at gmail.com wrote: > Currently, I have all of the above "working", although I'm running > into some serious timing issues. When I run the program, I get > irregular timing for my metronome (if it sounds at all), as well as > irregular timing in writing to the external device. It's extremely > crucial that threads #1 & #2 are executed as close to real-time as > possible, as they form the "core" of the song, and their elements > can't be delayed without "messing" the song up considerably. > > I've read up quite a bit on different optimization methods in Python, > but am not sure which direction to head. I've checked out profile, > Psyco, Pyrex, as well as just porting everything over to C. Since I'm > on a Mac (Power PC), I can't use Psyco. And doing any of the others > seemed like a big enough project that I should really ask someone else > before I embark. Your problems do not necessarily stem from slow code. Python only performs thread context switches every 100 ?pcodes, and the switch might not arrive at the right time. You can lower this value (sys.setcheckinterval). Your computationally- intensive threads may effectively lower their priority by calling time.sleep(.00001) every so often. Ultimately, maintaining explicity control over the scheduling of events is probably the way to go. Pyrex is my preferred optimization method, but it can take some knowledge of what's going on to get the most out of it. numpy is another option. -Mike From worlman385 at yahoo.com Sat Feb 3 03:12:06 2007 From: worlman385 at yahoo.com (worlman385 at yahoo.com) Date: Sat, 03 Feb 2007 00:12:06 -0800 Subject: nokia pys60 contacts + calendar Message-ID: anyone could give a hint on adding new entry to nokia phone's contact list and calendar what function in pys60 python modules would make this working or any examples on how to make this work thanks From danb_83 at yahoo.com Tue Feb 27 20:53:34 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 27 Feb 2007 17:53:34 -0800 Subject: os.system and quoted strings In-Reply-To: References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> Message-ID: <1172627614.008588.176800@p10g2000cwp.googlegroups.com> On Feb 27, 9:16 am, Steven D'Aprano wrote: > On Tue, 27 Feb 2007 06:24:41 -0800, svata wrote: ... > > import time > > import os > > > dir = "C:\\Documents and Settings\\somepath\\" > > I believe that Windows will accept forward slashes as directory > separators, so you can write that as: > > dir = "C:/Documents and Settings/somepath/" Windows system calls treat / and \ interchangeably, but the command prompt insists on backslashes. From chandrapsg at gmail.com Mon Feb 26 01:41:16 2007 From: chandrapsg at gmail.com (chandrapsg at gmail.com) Date: 25 Feb 2007 22:41:16 -0800 Subject: help regarding python and jsp Message-ID: <1172472076.032230.127280@k78g2000cwa.googlegroups.com> Hi, i am working with jsp .. i wanna help regarding how to import or how to call python modules to jsp if a piece of code is availabe will be very helpful for me chandra From thomas.pollet at gmail.com Wed Feb 7 12:17:58 2007 From: thomas.pollet at gmail.com (Thomas Pollet) Date: Wed, 7 Feb 2007 18:17:58 +0100 Subject: (n)curses or tcl/tk? In-Reply-To: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> References: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> Message-ID: Hi, you could try wxpython and the wxglade toolkit for building gui Regards, Thomas On 7 Feb 2007 08:35:41 -0800, magnate wrote: > > Hi All, > > Just learning Python - my first new language for about 18 years (I'm > not a programmer ...). I'm writing a small utility to manipulate some > text files (for the game VGA Planets, if you're interested: http:// > www.phost.de). It's currently working, but it looks a bit ugly with > raw_input and just basic text output. > > I have plans to expand the functions of the utility, and I want a > simple GUI frontend. I assumed I'd end up with something that looks a > bit like the Debian installer: a curses-driven thing with simple ascii > boxes and buttons. But reading a bit more about Python makes me think > that support for tcl/tk is much more developed than support for > curses. > > So my question is, should I go to the trouble of learning how to make > boxes and stuff using tcl/tk, or just go with ncurses as I imagined? > > Which is more portable? The basic idea is that this just runs on the > largest possible variety of systems (er, assuming they have Python > installed, of course). I use Debian mostly, but of course it needs to > run on bog-standard Windows boxes. Does that tilt the balance in > favour of curses or tcl/tk? Or should I just stick with ugly text? > > Thanks for all your help, > > CC (noob) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Thu Feb 15 01:34:59 2007 From: sjmachin at lexicon.net (John Machin) Date: 14 Feb 2007 22:34:59 -0800 Subject: AUX File Writing Error In-Reply-To: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> References: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> Message-ID: <1171521299.082449.67940@s48g2000cws.googlegroups.com> On Feb 15, 4:03 pm, thewritersc... at gmail.com wrote: > Hi guys! > > I'm new to python so please be aware that I'm probably missing the > obvious. Here's my problem... > > >>> t = "AUX" > >>> f = open('c:\\' + t + '.csv', 'a') > > Traceback (most recent call last): > File "", line 1, in > f = open('c:\\' + t + '.csv', 'a') > IOError: [Errno 2] No such file or directory: 'c:\\AUX.csv' > > >>> t = "A" > >>> f = open('c:\\' + t + '.csv', 'a') > > As you can see python has no problem opening a file when t = "A", but > not when it is "AUX" (no "A.csv" or "AUX.csv" exists on the C:\ folder > prior to when these are run). > > Is there any way I can create an "AUX.csv" file without the error? Probably not. AUX, CON, NUL, PRN, LPT, COM1, COM2 etc (with or without an extension) are reserved in Windows for specific devices for compatibility with MS-DOS 1.00 programs, which did that for compatibility with CP/M. HTH, John From grante at visi.com Tue Feb 13 10:40:54 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 13 Feb 2007 15:40:54 -0000 Subject: float print formatting References: Message-ID: <12t3n06pi0diobf@corp.supernews.com> On 2007-02-13, hg wrote: > Hi, > > Considering the float 0.0, I would like to print 00.00. > > I tried '%02.02f' % 0.0 ... but I get 0.00 ^^ That's the specifierfor how many total columns you want to use (including the decimal point and all digits to either side). > Any clue ? >>> "%05.02f" % 0.0 '00.00' -- Grant Edwards grante Yow! Yow!! "Janitor at trapped in sewer uses ESP visi.com to find decayed burger"!! From jfabiani at yolo.com Thu Feb 15 13:15:59 2007 From: jfabiani at yolo.com (johnf) Date: Thu, 15 Feb 2007 10:15:59 -0800 Subject: Which Object Database would you recommend for cross platform application? References: Message-ID: Thomas Ploch wrote: > Hello folks, > > I am currently developing an open source Event Managment software > (events in real-life, like concerts, exhibitions etc. :-) ) using wx for > the GUI, and I need an Object database. Since this is the first time I > actually need doing this, I wondered if anybody here could recommend > one. It can be fairly simple. It doesn't need threading support and will > only host one client (the application, but I am thinking about making > this database accessible via the web, but this is still far in the > future), although the database might get big (around 1GiB). It should be > available for linux, mac os and windows. > > I looked into ZODB, but thats totally overloaded for my purpose. I > looked into Durus (a re-implementation of ZODB, but without this > overloaded stuff, but the documentation is very thin). Both of them > don't really appeal. > > So I wondered if any of you could recommend one that (more or less) best > fits the described conditions. > > Thanks in advance, > Thomas This answer does not really answer your question. But have you looked a dabo (www.dabodev.com). It doesn't support the web (yet) but you said that's in the furture. Dabo was built for this type of app. Dabo supports Postgres,MsSQL,MySQL,Firebird, and SQLite. Non of the DB's are what I'd call an object database but is that a real requirement? BTW the first 4 DB's can support 1GB and more. Johnf From rzantow at gmail.com Sun Feb 4 12:37:05 2007 From: rzantow at gmail.com (rzed) Date: Sun, 04 Feb 2007 12:37:05 -0500 Subject: Dividing integers...Convert to float first? References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <12pt3f3kc1jmcf8@corp.supernews.com> Message-ID: "Simon Brunning" wrote in news:mailman.2339.1168019925.32031.python-list at python.org: > On 1/5/07, Grant Edwards wrote: >> >>> from __future__ import LotteryNumbers >> File "", line 1 >> SyntaxError: future feature LotteryNumbers is not defined >> >> Damn. >> >> I guess it's back to work then. > > Remember the PEP 8 module name standards. > >>>> from __future__ import lottery_numbers > [1, 16, 19, 20, 21, 39] > My Python version is so old that I only get three numbers. I guess I'll have to upgrade. -- rzed From aldcwatson at gmail.com Thu Feb 22 12:52:49 2007 From: aldcwatson at gmail.com (Andy Watson) Date: 22 Feb 2007 09:52:49 -0800 Subject: Possible to set cpython heap size? In-Reply-To: <5462tbF1vfhfrU1@mid.uni-berlin.de> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <5462tbF1vfhfrU1@mid.uni-berlin.de> Message-ID: <1172166768.967422.225960@p10g2000cwp.googlegroups.com> > Why do you want that? And no, it is not possible. And to be honest: I have > no idea why e.g. the JVM allows for this. > > Diez The reason why is simply that I know roughly how much memory I'm going to need, and cpython seems to be taking a fair amount of time extending its heap as I read in content incrementally. Ta, Andy -- From R.Brodie at rl.ac.uk Thu Feb 15 07:53:54 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 15 Feb 2007 12:53:54 -0000 Subject: basic jython question References: <1171543539.339651.319480@m58g2000cwm.googlegroups.com> Message-ID: "Gerard Flanagan" wrote in message news:1171543539.339651.319480 at m58g2000cwm.googlegroups.com... > I have a 'logger' module which is essentially just a facade over the > 'logging' standard module. Can this be called from jython, and how is > this acheived? This is a colleague's question but I have no knowledge > of jython or java, and I can't install them at present in order to > figure it out. Since the CPython module is heavily influenced by the native Java logging framework (and/or log4j), I would have thought that it would be easier to create a Jython wrapper for those. From mcfletch at vrplumber.com Fri Feb 9 14:23:11 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Fri, 09 Feb 2007 14:23:11 -0500 Subject: pygame and python 2.5 In-Reply-To: <17868.46349.59089.178486@montanaro.dyndns.org> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <17868.46349.59089.178486@montanaro.dyndns.org> Message-ID: <45CCCA1F.6050204@vrplumber.com> skip at pobox.com wrote: > Ben> Python extensions written in C require recompilation for each new > Ben> version of Python, due to Python limitations. > > Can you propose a means to eliminate this limitation? > Sure, write your wrapper-style extensions in ctypes :) . For example, pygame-ctypes[1] should work on Python 2.5. Of course, you need to get the PyGame dependencies (SDL) installed via some external mechanism, but the ctypes-based code should run in Python 2.5 today (with the caveat that it's not finished software). [1] http://www.pygame.org/ctypes/ Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From rachele.defelice at gmail.com Fri Feb 2 08:55:48 2007 From: rachele.defelice at gmail.com (ardief) Date: 2 Feb 2007 05:55:48 -0800 Subject: newbie/ merging lists of lists with items in common Message-ID: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Hi everyone Here is my problem: I have a list that looks like this - [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] and I would like to end up with something like this, i.e. with the only one list per letter: [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], ['e', ['11', '5', '16', '7']]] I have the feeling it's trivial, and I've scoured the group archives - sets might be a possibility, but I'm not sure how to operate on a list of lists with sets. This function also gives me what I want, more or less, but I don't know how to make it run until it's covered all the possibilities, if that makes sense... def sigh(list): for a in list: i = list.index(a) if a != list[-1]: ##if a is not the last one, i.e. there is a next one n = alist[i+1] if a[0] == n[0]: a.append(n[1:]) del alist[i+1] Sorry about the lengthy message and thanks for your suggestions - I'm trying to learn... From bj_666 at gmx.net Wed Feb 7 05:02:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 07 Feb 2007 11:02:21 +0100 Subject: Getting a class name from within main References: <1170838959.441543.19720@s48g2000cws.googlegroups.com> Message-ID: In <1170838959.441543.19720 at s48g2000cws.googlegroups.com>, bg_ie wrote: > class MyClass: > def __init__(self): > print (__name__.split("."))[-1] > > if __name__ == '__main__': > MyClassName = "MyClass" > > I can print the name of the class from within the class scope as seen > above in the init, but is there any way of printing it from within the > main without creating an object of the MyClass type. I need to assign > the name of the class within my script, to a variable in main. Yes:: print MyClass.__name__ Ciao, Marc 'BlackJack' Rintsch From yang at pyboo.com Sun Feb 11 07:16:40 2007 From: yang at pyboo.com (=?utf-8?Q?YySwing.=E6=9D=A8?=) Date: Sun, 11 Feb 2007 20:16:40 +0800 Subject: Python-list Digest, Vol 41, Issue 170 References: Message-ID: <012c01c74dd6$7f8b8aa0$0201a8c0@windskyf53b055> ----- Original Message ----- From: To: Sent: Sunday, February 11, 2007 5:10 PM Subject: Python-list Digest, Vol 41, Issue 170 > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > -------------------------------------------------------------------------------- > Today's Topics: > > 1. Re: pygame and python 2.5 (Steve Holden) > 2. Re: can't find a way to display and print pdf through python. > (Geoff Hill) > 3. Re: pygame and python 2.5 (Hendrik van Rooyen) > 4. Re: HTML Parsing (John Machin) > 5. irclib problems (Tina I) > 6. Re: pygame and python 2.5 (mensanator at aol.com) > -------------------------------------------------------------------------------- > -- > http://mail.python.org/mailman/listinfo/python-list From horpner at yahoo.com Mon Feb 26 10:24:19 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 26 Feb 2007 16:24:19 +0100 Subject: CSV(???) References: Message-ID: On 2007-02-24, David C Ullrich wrote: > On 23 Feb 2007 19:13:10 +0100, Neil Cerutti wrote: > >>On 2007-02-23, David C Ullrich wrote: >>> Is there a csvlib out there somewhere? >>> >>> And/or does anyone see any problems with >>> the code below? >>> >>> [...] >>> >>> (Um: Believe it or not I'm _still_ using python 1.5.7. So >>> comments about iterators, list comprehensions, string >>> methods, etc are irrelevent. Comments about errors in the >>> algorithm would be great. Thanks.) >> >>Two member functions of indexedstring are not used: next and >>lookahead. __len__ and __getitem__ appear to serve no real >>purpose. > > Hey, thanks! I didn't realize that using an object with methods > that were never called could cause an algorithm to fail... > shows how much I know. Sorry I couldn't provide the help you wanted. -- Neil Cerutti From alan.franzoni_invalid at geemail.invalid Tue Feb 27 11:40:35 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Tue, 27 Feb 2007 17:40:35 +0100 Subject: Python Source Code Beautifier References: Message-ID: Il Tue, 27 Feb 2007 09:45:42 +0100, Franz Steinhaeusler ha scritto: > Hello, I did not find any reasonable pyhton source code beautifier > program (preferable gui). Well, most of the things you ask should be written as such, not written and then beautified! > Use Spaces, size: 4 Your editor should support this. > convert structs like: if (a > b): to if a > b: Well... that's a matter of fact, not just style. Sometimes parentheses help the reading; if a,b are not just plain names but somewhat complex instructions, parentheses should stay. > fill in spaces, but not in functions between operators: > > a+=1 => a += 1 > p(t + 1) => p(t+1) Code should be written this way. > self.scriptcount = self.scriptcount + 1 => self.scriptcount += 1 the += operator is syntactic sugar just to save time... if one doesn't use it I don't think it's a matter of beauty. > > from "is" to "==" and "is not" to "!=" (ok a find replace could do that > easily also), but in a program that would be more comfortable. what? No, I think you're missing the difference between 'is' and '=='. You could say it the other way for None, True, False, e.g. if there's a 'a == None' it could be safely converted to 'a is None', but again: this should be done while writing the code. > break long lines (in a reasonable way) well... this could be useful sometimes, but again... 'reason' is usually something human beings should employ, and shouldn't be 'outsourced' to computer programs. > make from: > if len(string) > 0: => if string: > and > if if len(string) < 1 orr if string == "" => if not string That's impossibile! Python is dynamically typed! How could the 'beautifier' understand what the 'string' name is bound to? It could be whatever object! > detect mixed line ending > detect tabs mixed with space > trim trailing whitespaces. Those are editor tasks. Get a good Editor or IDE. You haven't told us what OS are you on. If you're on Windows, UltraEdit can do most of the things you'd like. And don't rely on a software to correct human behaviours ^_^. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From lionchao at gmail.com Fri Feb 23 02:44:26 2007 From: lionchao at gmail.com (Eric CHAO) Date: Fri, 23 Feb 2007 15:44:26 +0800 Subject: connection pool in python? Message-ID: Connection Pool is necessary in web applications with Java and JDBC. So does python have something like that? Thanks. From mrsanad1 at yahoo.com Sun Feb 4 06:36:07 2007 From: mrsanad1 at yahoo.com (Magdy Sanad) Date: Sun, 4 Feb 2007 03:36:07 -0800 (PST) Subject: Question Message-ID: <743068.47814.qm@web37312.mail.mud.yahoo.com> Dear All I'm a Researcher from Cairo, Egypt. I installed the language programmer Python Enthought Edition--Python 2.4.3 for Windows Enhanced Python Distribution. I have certain data in the default file format ( GADGET ) . I Will be appreciated if you guide me to read these data under Python ? I'm looking forward to hear from you. Best Regards Magdy Sanad National Research Institute of Astronomy and Geophysics Astronomy Department Helwan - Cairo - Egyp --------------------------------- Never miss an email again! Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skpeterson at nospam.please.ucdavis.edu Sun Feb 11 08:13:51 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 05:13:51 -0800 Subject: How to find all the same words in a text? References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: "Johny" on 10 Feb 2007 05:29:23 -0800 didst step forth and proclaim thus: > I need to find all the same words in a text . > What would be the best idea to do that? I make no claims of this being the best approach: ==================== def findOccurances(a_string, word): """ Given a string and a word, returns a double: [0] = count [1] = list of indexes where word occurs """ import re count = 0 indexes = [] start = 0 # offset for successive passes pattern = re.compile(r'\b%s\b' % word, re.I) while True: match = pattern.search(a_string) if not match: break count += 1; indexes.append(match.start() + start) start += match.end() a_string = a_string[match.end():] return (count, indexes) ==================== Seems to work for me. No guarantees. -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From horpner at yahoo.com Fri Feb 23 13:13:10 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Feb 2007 19:13:10 +0100 Subject: CSV(???) References: Message-ID: On 2007-02-23, David C Ullrich wrote: > Is there a csvlib out there somewhere? > > And/or does anyone see any problems with > the code below? > > What csvline does is straightforward: fields > is a list of strings. csvline(fields) returns > the strings concatenated into one string > separated by commas. Except that if a field > contains a comma or a double quote then the > double quote is escaped to a pair of double > quotes and the field is enclosed in double > quotes. > > The part that seems somewhat hideous is > parsecsvline. The intention is that > parsecsvline(csvline(fields)) should be > the same as fields. Haven't attempted > to deal with parsecsvline(data) where > data is in an invalid format - in the > intended application data will always > be something that was returned by > csvline. It seems right after some > testing... also seems blechitudinous. > > (Um: Believe it or not I'm _still_ using python 1.5.7. So > comments about iterators, list comprehensions, string methods, > etc are irrelevent. Comments about errors in the algorithm > would be great. Thanks.) Two member functions of indexedstring are not used: next and lookahead. __len__ and __getitem__ appear to serve no real purpose. > def parsecsvline(csvline): > """Inverts csvline(). Assumes csvline is valid, ie > is something as returned by csvline(); output undefined > if csvline is in invalid format""" > > s = indexedstring(csvline) > res = [] > > while not s.eos(): > res.append(s.getfield()) > > return res You'll be happy to know that iterators and list comprehensions will make your code better after you upgrade. ;-) In the meantime, I think your (relative lack of) error handling is OK. GIGO, as they say (garbage in, garbage out). -- Neil Cerutti From jstroud at mbi.ucla.edu Mon Feb 26 08:20:55 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 26 Feb 2007 13:20:55 GMT Subject: [OT] python notation in new NVIDIA architecture In-Reply-To: References: Message-ID: Daniel Nogradi wrote: > Something funny: > > The new programming model of NVIDIA GPU's is called CUDA and I've > noticed that they use the same __special__ notation for certain things > as does python. For instance their modified C language has identifiers > such as __device__, __global__, __shared__, etc. Is it a coincidence? > Probably it is. :) Cuda is usually taken as short for "barracuda", a fish. Fish have been known to slither under the right circumstances. Perhaps this is the link? James From fuzzyman at gmail.com Sun Feb 18 07:24:47 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 18 Feb 2007 04:24:47 -0800 Subject: Getting a class name In-Reply-To: <_DJBh.20322$K8.18088@news.edisontel.com> References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <_DJBh.20322$K8.18088@news.edisontel.com> Message-ID: <1171801487.767555.14150@v33g2000cwv.googlegroups.com> On Feb 17, 8:33 pm, deelan wrote: > Harlin Seritt wrote: > > Hi, > > > How does one get the name of a class from within the class code? I > > tried something like this as a guess: > > > self.__name__ > > Get the class first, then inspect its name: > > >>> class Foo(object): pass > ... > >>> f = Foo() > >>> f.__class__.__name__ > 'Foo' > >>> > Why is the __name__ attribute not available to the instance? Why don't normal lookup rules apply (meaning that a magic attribute will be looked up on the class for instances) ? Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > HTH > > -- > d. From nick at craig-wood.com Tue Feb 20 04:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 20 Feb 2007 03:30:05 -0600 Subject: f---ing typechecking References: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2007-02-14, Farshid Lashkari wrote: > > Szabolcs Nagy wrote: > >>>>> L=[1] > >>>>> L.extend((1,)) > >>>>> L > >> [1, 1] > > > > Are list.extend() and list concatenation supposed to behave > > differently? I always thought concatenation was just shorthand > > for calling extend(). > > They are different. list.extend() mutates the list, returning > None, while the + operator returns a new, concatenated list. > > += on the other hand works very similarly to list.extend(). It does make an inconsistency though... >>> L=[1] >>> L+=(1,) >>> L [1, 1] Wheras >>> L=[1] >>> L=L+(1,) Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate list (not "tuple") to list >>> Ie x += a does not equal x = x + a which it really should for all types of x and a (That is the kind of statement about which I'm sure someone will post a perfectly reasonable counterexample ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From silverfrequent at gmail.com Sat Feb 3 15:00:39 2007 From: silverfrequent at gmail.com (Silver Rock) Date: Sat, 3 Feb 2007 18:00:39 -0200 Subject: wave Message-ID: hallo, supose i?ve opened a sound with the wave module: >>> import wave >>> sound=wave.open(filename,'rb') now this is strange: >>> sound.getnframes() != len(sound.readframes(sound.getnframes()) True Why so? thanks in advance, Claire -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Feb 27 16:24:56 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Feb 2007 22:24:56 +0100 Subject: import parent References: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> Message-ID: <54jlt8F20dq64U1@mid.individual.net> Greg Hoover wrote: > How does one get access to the class that imported a module. For > example: foo imports bar -- how does bar access foo? Directly? Not at all in sane programs, IMHO. That's the job of clear interfaces. Regards, Bj?rn -- BOFH excuse #407: Route flapping at the NAP. From mau.conte at vodafone.it Wed Feb 28 04:37:02 2007 From: mau.conte at vodafone.it (Konte) Date: Wed, 28 Feb 2007 10:37:02 +0100 Subject: msvcr71.dll Message-ID: Are there news about the impossibility of redistributing msvcr71.ddl with own stand-alone application written in python for who doesn't have MSVC7 license? From rpmuller at gmail.com Fri Feb 16 09:19:00 2007 From: rpmuller at gmail.com (RickMuller) Date: 16 Feb 2007 06:19:00 -0800 Subject: numpy, numarray, or numeric? In-Reply-To: <1171607007.184589.78670@v33g2000cwv.googlegroups.com> References: <1171607007.184589.78670@v33g2000cwv.googlegroups.com> Message-ID: <1171635539.608570.33420@k78g2000cwa.googlegroups.com> On Feb 15, 11:23 pm, "Frank" wrote: > On Feb 15, 4:40 pm, "Christian Convey" > wrote: > > > I need to bang out an image processing library (it's schoolwork, so I > > can't just use an existing one). But I see three libraries competing > > for my love: numpy, numarray, and numeric. > > > Can anyone recommend which one I should use? If one is considered the > > officially blessed one going forward, that would be my ideal. > > > Thanks, > > Christian > > Hi, > > yeah numpy is the newest one. It has only one drawback, there is no > comprehensive documentation available that would be free but of course > you could buy one. numpy is very similar to the other two packages but > not identical that means one has always some troulbe finding out how > things work. For example, in numarray you can calculate the > eigenvectors of a matrix with eigenvectors(A), in numpy it is eig(A). > This looks similar, but the difference is that in numarray the > eigenvectors are returned as rows and in numpy as columns. > > If someone knows of a free manual, let me know. > > Frank Frank, I bought the manual, and I do recommend it, but I find the most useful documentation is in the docstrings, which I view via "pydoc -g" and then view in a browser. Rick From ccw.thomas at gmail.com Thu Feb 15 11:04:45 2007 From: ccw.thomas at gmail.com (ThomasC) Date: 15 Feb 2007 08:04:45 -0800 Subject: The Python interactive interpreter has no command history Message-ID: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> Hello, How to configure Python2.5's interactive interpreter to get command history ? I always got ^[[A and ^[[B . Thank you !! Thomas# From vodel at informatik.tu-chemnitz.de Wed Feb 28 06:58:49 2007 From: vodel at informatik.tu-chemnitz.de (Matthias Vodel) Date: Wed, 28 Feb 2007 12:58:49 +0100 Subject: py2exe, library.zip and python.exe References: Message-ID: Hey, [Offtopic:] Use PyInstaller...very easy to use - better than py2exe!! see here: http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi Bye, Matthias From malaclypse2 at gmail.com Wed Feb 7 16:35:27 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 7 Feb 2007 16:35:27 -0500 Subject: Array delete In-Reply-To: <45BC84B6.9080505@riddergarn.dk> References: <45BC84B6.9080505@riddergarn.dk> Message-ID: <16651e80702071335y251a76cep340745c0b7a1699@mail.gmail.com> On 1/28/07, Scripter47 wrote: > Can someone plz make a function for that takes a array, and then search > in it for duplicates, if it finds 2 or more items thats the same string > then delete all except 1. >>> myList = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10] >>> myList = list(set(myList)) >>> print myList [8, 1, 2, 4, 10] Maintaining sort order is left as an exercise for the reader. -- Jerry From melirizarry at gmail.com Wed Feb 28 12:55:55 2007 From: melirizarry at gmail.com (Mel) Date: 28 Feb 2007 09:55:55 -0800 Subject: How do I Color a QTableView row in PyQt4 Message-ID: <1172685355.820708.149990@q2g2000cwa.googlegroups.com> I am currently porting an SQL centered Visual Basic application to run on Linux, Python, and Qt4. Currently I am stumped on changing row colors in the QTableView widget. My test code is based on code from the PyQt4 examples and looks like this: *** Start Code *** import sys from PyQt4 import QtCore, QtGui, QtSql import connection class CustomSqlModel(QtSql.QSqlQueryModel): def data(self, index, role): value = QtSql.QSqlQueryModel.data(self, index, role) if value.isValid() and role == QtCore.Qt.DisplayRole: if index.column() == 0: return QtCore.QVariant(value.toString().prepend("#")) elif index.column() == 2: return QtCore.QVariant(value.toString().toUpper()) if role == QtCore.Qt.TextColorRole and index.column() == 1: return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue)) return value def initializeModel(model): model.setQuery("SELECT * FROM WaterOrder Where DateCanceled is NULL AND ActDateTimeOff is NULL and ActDateTimeOn is NOT NULL") offset = 0 views = [] def createView(title, model): global offset, views view = QtGui.QTableView() views.append(view) view.setModel(model) view.setWindowTitle(title) for i in range(model.columnCount()): view.resizeColumnToContents(i) view.setAlternatingRowColors(1) view.move(100 + offset, 100 + offset) offset += 20 view.show() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) if not connection.createConnection(): sys.exit(1) customModel = CustomSqlModel() initializeModel(customModel) createView(QtCore.QObject.tr(customModel, "Running Water"), customModel) sys.exit(app.exec_()) *** End Code *** Column 18 in the table shows a number from 1 to 3. I would like to change the color of the row based on the value in column 18 but I have not been able to find any resources that show me how. Can anyone lend a hand? Thanks, Mel From rory at campbell-lange.net Fri Feb 23 11:38:10 2007 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Fri, 23 Feb 2007 16:38:10 +0000 Subject: Local class variables? (mod_python problem) In-Reply-To: <548ageF1u22afU1@mid.uni-berlin.de> References: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> <20070222154239.GA12709@campbell-lange.net> <548ageF1u22afU1@mid.uni-berlin.de> Message-ID: <20070223163810.GA12546@campbell-lange.net> On 23/02/07, Diez B. Roggisch (deets at nospam.web.de) wrote: > > It is not desirable for the class variable to keep incrementing outside > > of invocations of '__main__', as is the case when it is loaded under > > mod_python under apache2 on linux. > > > > I'm still not clear on what you want to accomplish. In the end it boils down > to who is supposed to share that information in the variables, or in other > words: which scope has it. > > Is it per request? Then using some thread-local storage would be in order, > or "abusing" a possible request-object. > > Is it per user, over several requests? Then you need a session-mechanism. > > Is it per application, for several users, over several requests? Then your > approach is ok, but needs guarding against concurrrent access using > threading.Lock for example. However, I presume that is not the desired > usecase, from what I can extract from your posts I presume it's case two. Many thanks for your reply. The use case is per request, and I would be grateful to learn more about thread-local storage. Kind regards Rory -- Rory Campbell-Lange From tiedon_jano at hotmail.com Tue Feb 13 13:13:59 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 13 Feb 2007 18:13:59 GMT Subject: can't find a way to display and print pdf through python. In-Reply-To: References: <12t17gsjh6vgh94@corp.supernews.com> <12t1ch1n8hj9n69@corp.supernews.com> <12t2cgssrrbmf1a@corp.supernews.com> Message-ID: Dennis Lee Bieber kirjoitti: > On Tue, 13 Feb 2007 08:44:18 GMT, Jussi Salmela > declaimed the following in comp.lang.python: > > >> On Windows, this (where fileName is xyz.PDF, for example): >> webbrowser.open(r'file://' + fileName) >> starts Acrobat Reader with the document read in. I have no idea why, >> because Acrobat Reader sure ain't my browser;) >> > Most likely Adobe installed the Acrobat plug-in for the browser... > The browser identifies the file as PDF and passes it to the plug-in for > rendering. I can read PDFs with the browser if I open them in there. But as I was trying to tell the line above starts the Acrobat Reader EXE in its own window. The mechanism is probably caused by something I must have done/installed, but I don't know what. Anyway: it works just as I want although this may not be the general behaviour. (OS: Win XP SP2, Python 2.4.3) Cheers, Jussi From subscriber123 at gmail.com Tue Feb 27 21:08:49 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Tue, 27 Feb 2007 21:08:49 -0500 Subject: how to convert an integer to a float? In-Reply-To: <54k05cF218n10U1@mid.individual.net> References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> <54k05cF218n10U1@mid.individual.net> Message-ID: <4c0048df0702271808w512cc605o5ecb8abf063c5eb1@mail.gmail.com> How did the new division ever get approved?! That's not pythonic! What if you then need to divide two integers and find an element in a list or dict? It will give you an error! I know that at the moment it is not implemented unless imported from __future__, but I expect that it eventually might be. That would be a problem with backwards compatibility. On 2/27/07, Bjoern Schliessmann < usenet-mail-0306.20.chr0n0ss at spamgourmet.com> wrote: > > yinglcs at gmail.com wrote: > > > def compareValue(n1, n2): > > i1 = int(n1) > > i2 = int(n2) > > > > dx = abs(i2 - i1)/min(i2, i1) > > print dx > > return dx < 0.05 > > You could also prepend > > from __future__ import division > > Regards, > > > Bj?rn > > -- > BOFH excuse #237: > > Plate voltage too low on demodulator tube > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hg at nospam.org Tue Feb 13 01:53:50 2007 From: hg at nospam.org (hg) Date: Tue, 13 Feb 2007 07:53:50 +0100 Subject: float print formatting Message-ID: Hi, Considering the float 0.0, I would like to print 00.00. I tried '%02.02f' % 0.0 ... but I get 0.00 Any clue ? Thanks, hg From inigoserna at gmail.com Sun Feb 25 16:43:27 2007 From: inigoserna at gmail.com (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Sun, 25 Feb 2007 22:43:27 +0100 Subject: ANN: pynakotheka v1.1.0 Message-ID: <1172439807.1797.6.camel@inigo> Hi there, I'm pleased to announce a new release of Pynakotheka. Pynakotheka is a simple GPL-licensed python script which generates static HTML photo albums to be added to web sites or to be burnt into CDs. It includes some templates and it's easy to create more. It depends on python, Mako Templates, EXIF and PIL. Read more and download it from: http://inigo.katxi.org/devel/pynakotheka or http://www.terra.es/personal7/inigoserna/pynakotheka Changes from v1.0.3 to v1.1.0: ============================== * use Mako Templates instead of Cheetah Templating System: - html creation is much faster now - old problems with text encodings should be solved now * file names encoded in UTF8 works ok now, or so I hope * added a "--version" option As always, all comments, suggestions etc. are welcome. Best regards, I?igo Serna From sjmachin at lexicon.net Fri Feb 9 20:07:46 2007 From: sjmachin at lexicon.net (John Machin) Date: 9 Feb 2007 17:07:46 -0800 Subject: Matching Strings In-Reply-To: References: Message-ID: <1171069666.354520.209440@j27g2000cwj.googlegroups.com> On Feb 10, 12:01 pm, rshepard-at-appl-ecosys.com wrote: > On 2007-02-10, James Stroud wrote: > > > Assuming item is "(u'ground water',)" > > > import re > > item = re.compile(r"\(u'([^']*)',\)").search(item).group(1) > > James, > > I solved the problem when some experimentation reminded me that 'item' is > a list index AArrgghh it's not a list index, it's a ferschlugginer tuple containing 1 element. From jm.suresh at gmail.com Mon Feb 5 03:37:09 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 5 Feb 2007 00:37:09 -0800 Subject: Finding cpu time spent on my program Message-ID: <1170664629.719220.249570@k78g2000cwa.googlegroups.com> I am trying to measure the time the processor spends on some operation, and I want this measure to not depend on the current load of the machine. But doing the following prints different values each time a run. import time c1 = time.clock() for x in xrange(0xFFFFF): pass c2 = time.clock() print "Time spent is %f" % (c2-c1) Is there a way to measure the number of cpu cycles spent on my program alone irrespective of the current load etc of the machine. - Suresh From tiedon_jano at hotmail.com Thu Feb 22 03:16:21 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 22 Feb 2007 08:16:21 GMT Subject: Convert to binary and convert back to strings In-Reply-To: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: Harlin Seritt kirjoitti: > Hi... > > I would like to take a string like 'supercalifragilisticexpialidocius' > and write it to a file in binary forms -- this way a user cannot read > the string in case they were try to open in something like ascii text > editor. I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is there any > way to do this in Python? > > Thanks! > > Harlin > Here's my suggestion using compression. Seems to work, but a word of warning: I've never used the codecs explicitly before! #============== # -*- coding: cp1252 -*- import codecs s = 'This is so secret that it must be hidden ????' print s f = codecs.open('secret.txt', 'wb', 'zlib_codec') f.write(s) f.close() f = codecs.open('secret.txt', 'rb', 'zlib_codec') s2 = f.read() f.close() print s2 if s == s2: print 'OK' else: print '!"#?%%' #================ From larry.bates at websafe.com Mon Feb 5 10:47:49 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 05 Feb 2007 09:47:49 -0600 Subject: Watch folder for new file and execute extern program In-Reply-To: <1170682938.056015.238000@p10g2000cwp.googlegroups.com> References: <1170682938.056015.238000@p10g2000cwp.googlegroups.com> Message-ID: Michael Bo wrote: > Hi. > Can anyone guide me on how to minitor a folder for new files? And when > they appear I need to run and externe program with the file just > created (buy a 3rd program). > - Michael Bo > Here is a link that should help. http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html BTW-It helps us out here if you let us know what platform you are running on (e.g. Windows, Linux, Mac, etc.). -Larry From chuehbueb at gmail.com Thu Feb 22 07:15:48 2007 From: chuehbueb at gmail.com (ChuehBueb) Date: Thu, 22 Feb 2007 13:15:48 +0100 Subject: Informations about other computers in the network Message-ID: Hi all. I search a way to get informations, like NetBios-Name, os,..., about other workstations in my network. I searched google and the documentation, but i found nothing... can you help me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Mon Feb 26 23:46:35 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 27 Feb 2007 05:46:35 +0100 Subject: Pep 3105: the end of print? In-Reply-To: References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: <45E3B7AB.5080909@v.loewis.de> Edward K Ream schrieb: > In other words, the consequence of pep 3105 will be that *nobody* who wants > their app to be portable will be able to use print until *everybody* has > converted to Python 3.x. I doubt that is what Guido had in mind, but I may > be mistaken :-) That's not true. Many uses of print work just fine whether print is a function. For example, from the standard library: quopri.py: print "-t: quote tabs" can be rewritten as print("-t: quote tabs") shlex.py: print 'shlex: reading from %s, line %d' \ % (self.instream, self.lineno) can be rewritten as print('shlex: reading from %s, line %d' \ % (self.instream, self.lineno)) So people can rewrite their code so that it uses print, and still works in both Python 1.5 and 3.0. Of course, there are many uses that cannot be converted this way, but it's not true that *nobody* who want there app to be portable will be able to use print until *everybody* has converted to Python 3.x. Regards, Martin From paul at boddie.org.uk Wed Feb 28 06:51:35 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 28 Feb 2007 03:51:35 -0800 Subject: installing "pysqlite" In-Reply-To: <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> Message-ID: <1172663495.011225.76410@v33g2000cwv.googlegroups.com> On 28 Feb, 12:07, Nader Emami wrote: > > I am back with another problem. I suppose that I can tell it! > I have installed both, 'sqlite' and 'pysqlite' without any problem. But > If I try to test whether the 'pysqlite' interface works, I get the next > error message: [...] > /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so: > undefined symbol: sqlite3_set_authorizer > > I don't understand it. Could you tell me how I can solve this last > point? I hope so! It looks like Python (although it's really the dynamic linker) can't locate the SQLite libraries. If you have installed SQLite into a non- standard place, which I'm guessing is the case, then you will need to set your LD_LIBRARY_PATH environment variable to refer to the directory where the libraries were installed. So, if you installed SQLite into /usr/people/emami and you see files like libsqlite3.so in /usr/people/emami/lib, then you need to change your LD_LIBRARY_PATH as follows: export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib (The actual directory should be the same as the one you specified for library_dirs in the setup.cfg file for pysqlite.) If you're not using bash as your shell, the syntax for the command may be different. Don't forget to add this command to your shell configuration file (eg. .bashrc) so that your system remembers this information. Paul From attn.steven.kuo at gmail.com Sun Feb 25 21:15:32 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 25 Feb 2007 18:15:32 -0800 Subject: modifying a list while iterating through In-Reply-To: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> References: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> Message-ID: <1172456132.151803.75800@p10g2000cwp.googlegroups.com> On Feb 25, 5:12 pm, dustin.g... at gmail.com wrote: > consider the following working loop where Packet is a subclass of > list, with Packet.insert(index, iterable) inserting each item in > iterable into Packet at consecutive indexes starting at index. > > i=0 > while(i if packet[i:i+5]==Packet("01110"): > packet.insert(i, "01111") > i+=10 #skip the 5 bits inserted, and skip the 5 bits just > checked bc overlap should not trigger insertion > else: i+=1 > > is there a way to do this more elegantly? seems like a big kludge. If Packet consists of '0's and '1's, then it may be easier to convert to, or base the class on str (strings): packet = "1010101111011100111010001" print "BEFORE ", packet li = packet.split("01110") packet = "0111001111".join(li) print "AFTER ", packet -- Hope this helps, Steven From paul at boddie.org.uk Thu Feb 22 12:23:32 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Feb 2007 09:23:32 -0800 Subject: Bug in time module - %z works in perl, not in python? In-Reply-To: <1172161744.824760.187190@m58g2000cwm.googlegroups.com> References: <1172110679.681182.128350@j27g2000cwj.googlegroups.com> <1172112620.868130.139560@p10g2000cwp.googlegroups.com> <1172161744.824760.187190@m58g2000cwm.googlegroups.com> Message-ID: <1172165012.408685.41540@v45g2000cwv.googlegroups.com> On 22 Feb, 17:29, bwooste... at gmail.com wrote: > On Feb 21, 9:50 pm, attn.steven.... at gmail.com wrote: > > > On Feb 21, 6:17 pm, bwooste... at gmail.com wrote: > ... > > > 2007-02-21 21:15:58 EST+0000 (iso localtime, python) > > Seems to be a bug. I can duplicate the > > problem here (Python 2.4.3, Red Hat Desktop release 4). > > I searched the bug database, found this issue was closed as not a bug. As far as I can see, the reason for the differing behaviour of time.strftime is due to the way any supplied tuple is processed: 1. In Modules/timemodule.c, the time_strftime function calls gettmarg. 2. In gettmarg, various fields of struct tm are filled in, except for tm_gmtoff and tm_zone/__tm_zone (according to /usr/include/time.h). 3. Consequently, any structure produced from a tuple may lack those fields, in contrast to such structures produced directly by the system calls. 4. Thus, the strftime system call fails to find or make use of time zone information. So it looks like no call to strftime with a supplied argument will produce time zone information. Trying to use the datetime module to reproduce the problem seems to involve a need to produce "aware" datetime objects, apparently requiring me to define my own tzinfo class: class mytz(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(minutes=60) def dst(self, dt): return datetime.timedelta(0) def tzname(self, dt): return "CET" Only then will there be time zone or offset information on datetime objects: now = datetime.datetime.now(mytz()) now.strftime("%Y-%m-%d %H:%M:%S %z") # produced '2007-02-22 18:14:41 +0100' Some helper classes would really be useful for this kind of thing (and I remember that there is a time zone database module out there somewhere), but at least the time zone information gets through in the end. Paul From bignose+hates-spam at benfinney.id.au Thu Feb 1 16:52:02 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 08:52:02 +1100 Subject: OT: Variant name spellings (Re: how to "free" an object/var ?) References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> <1170264406.588032.116550@s48g2000cws.googlegroups.com> <52dl94F1nm406U1@mid.individual.net> Message-ID: <87zm7xv94t.fsf@benfinney.id.au> greg writes: > Or Mr. Luxury-Yacht, which as we all know is pronounced > Throatwarbler-Mangrove. With a silent hyphen. You're a very silly person and I'm not going to interview you anymore. -- \ "When I turned two I was really anxious, because I'd doubled my | `\ age in a year. I thought, if this keeps up, by the time I'm six | _o__) I'll be ninety." -- Steven Wright | Ben Finney From usenet200702 at tobyinkster.co.uk Wed Feb 21 11:43:20 2007 From: usenet200702 at tobyinkster.co.uk (Toby A Inkster) Date: Wed, 21 Feb 2007 16:43:20 +0000 Subject: BDFL in wikipedia References: Message-ID: <8e9ua4-voh.ln1@ophelia.g5n.co.uk> Jorge Vargas wrote: > shouldn't it mention Linus, Larry Wall, others?[3] Despite the link you posted, I don't think Linus, Larry Wall, Rasmus Lerdorf, etc describe themselves as BDFLs, even if they fulfil similar roles within their respective development communities. -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux Now Playing ~ ./vol/music/snug/from_solar_to_polar/04_naked_+_smiling.ogg * = I'm getting there! From gigs at hi.t-com.hr Tue Feb 13 19:11:51 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 14 Feb 2007 01:11:51 +0100 Subject: Tkinter: how; newbie In-Reply-To: <1171410264.493004.180800@v33g2000cwv.googlegroups.com> References: <1171410264.493004.180800@v33g2000cwv.googlegroups.com> Message-ID: Matimus wrote: >> How the callback function get this two number when it has only one >> argument (event)? > > It has one argument, event, which is an instance of a class that has > both x and y attributes. > >> print "clicked at", event.x, event.y > > It doesn't accept the coordinates as separate parameters because every > event binding uses that same signature, even ones for which > coordinates might not make any sense. I recommend you look over the > python tutorial: http://docs.python.org/tut/ > > that was fast, thanks From steve at holdenweb.com Sat Feb 10 03:42:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 08:42:23 +0000 Subject: pygame and python 2.5 In-Reply-To: <013b01c74cd8$8d913860$03000080@hendrik> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <17868.46349.59089.178486@montanaro.dyndns.org> <013b01c74cd8$8d913860$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > wrote: > "Ben Sizer" wrote: > > >> Ben> Python extensions written in C require recompilation for each new >> Ben> version of Python, due to Python limitations. >> >> Can you propose a means to eliminate this limitation? >> > > Yes. - Instead of calling something, send it a message... > I suppose you are proposing to use the ISO 19999.333 generic message-passing interface for this? The one that doesn't actually call a function to pass a message? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From pwuertz at students.uni-mainz.de Thu Feb 22 11:40:21 2007 From: pwuertz at students.uni-mainz.de (Peter Wuertz) Date: Thu, 22 Feb 2007 17:40:21 +0100 Subject: export an array of floats to python Message-ID: Hi, I'm writing a C module for python, that accesses a special usb camera. This module is supposed to provide python with data (alot of data). Then SciPy is used to fit the data. My question is, how to make python read from a C array? By reading the documentation, one could get the impression that PyBufferObjects do that job. http://docs.python.org/api/bufferObjects.html It says: "Two examples of objects that support the buffer interface are strings and arrays." Where this function looks promising: "PyBuffer_FromMemory - Return a new read-only buffer object that reads from a specified location in memory, with a specified size." All right, lets imagine I created a PyBufferObject from my float array in the C module, and passed it to python. I dont know what to do with a BufferObject in python, I would like to "cast" it to a Array of the type float, but Arrays do not have that kind of function... they can only be constructed from files or lists. Apart from creating these BufferObjects, there is no documentation about what to do with them :( Thanks for your help! From yinglcs at gmail.com Mon Feb 19 12:51:36 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 19 Feb 2007 09:51:36 -0800 Subject: Declare a variable global In-Reply-To: References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> Message-ID: <1171907496.269876.295200@p10g2000cwp.googlegroups.com> On Feb 19, 11:09 am, Jean-Paul Calderone wrote: > On 19 Feb 2007 09:04:19 -0800, "ying... at gmail.com" wrote: > > >Hi, > > >I have the following code: > > >colorIndex = 0; > > >def test(): > > print colorIndex; > > >This won't work. > > Are you sure? > > exarkun at charm:~$ cat foo.py > colorIndex = 0 > > def test(): > print colorIndex > > test() > exarkun at charm:~$ python foo.py > 0 > exarkun at charm:~$ > > The global keyword lets you rebind a variable from the module scope. It > doesn't have much to do with accessing the current value of a variable. > > Jean-Paul Thanks. Then I don't understand why I get this error in line 98: Traceback (most recent call last): File "./gensvg.py", line 109, in ? outdata, minX, minY, maxX, maxY = getText(data); File "./gensvg.py", line 98, in getText print colorIndex; UnboundLocalError: local variable 'colorIndex' referenced before assignment Here is my complete script: #!/usr/bin/python import re import sys import time import os import shutil colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00" ,"#FFA500" ,"#DA70D6"] colorIndex = 0 def getText( intputstr): rc = "" maxX = 0; maxY = 0; minX = 10000000; minY = 10000000; for str in intputstr: print str; if str != "": pattern = "x:(\d+) y:(\d+) w:(\d+) h:(\d+) (.*)" match = re.findall(pattern, str) if match: x, y, width, height, area = match[0] colorIndex = colorIndex + 1 rc = rc + "\n" % colors[colorIndex % len(colors)] _x = int(x) _y = int(y) _width = int(width) _height = int(height) minX = min(minX, _x); minY = min(minY, _y); maxX = max(maxX, _x+ _width); maxY = max(maxY, _y+_height); else: pattern = "\((\d+),(\d+)\)\((\d+),(\d+)\)(.*)" match = re.findall(pattern, str) if match: x1, y1, x2, y2, ignore = match[0] rc = rc + "" % locals() rc = rc + "\n" _x1 = int(x1) _y1 = int(y1) _x2 = int(x2) _y2 = int(y2) minX = min(_x1, _x2); minY = min(_y1, _y2); maxX = max(_x1, _x2); maxY = max(_y1, _y2); print colorIndex; print "match 2!" return rc, minX, minY, maxX, maxY; fileName = sys.argv[1] inputFile = open(fileName, 'r') data = inputFile.readlines(); outdata, minX, minY, maxX, maxY = getText(data); print minX, minY, maxX, maxY outputFile = open(fileName + '.svg', 'w') print >> outputFile, "" outputFile.write(outdata); print >>outputFile, "" From sjpiii at ya.delete.hoo.com Mon Feb 26 16:02:01 2007 From: sjpiii at ya.delete.hoo.com (sjpiii) Date: Mon, 26 Feb 2007 16:02:01 -0500 Subject: Python object to xml biding References: <1172517133.999532.180400@m58g2000cwm.googlegroups.com> Message-ID: "raf" wrote in message news:1172517133.999532.180400 at m58g2000cwm.googlegroups.com... > Hi there, > > > I'm looking for a python to XSD/xml biding library to easy handling > this very large protocol spec I need to tackle. I've searched google > quite extensibly and I haven't found anything that properly fits the > bill... I'm mostly interested at the xml -> python and python->xml > marshalling/unmarshalling much like jaxb for java. > > Any ideas? > Try the bindery component of the Amara XML Toolkit (http://mail.python.org/pipermail/xml-sig/2005-October/011234.html). At the time of this writing the project homepage says it is temporarily unavailable, but it's available from the Cheeseshop: http://cheeseshop.python.org/pypi/Amara/ From noreply at python.org Wed Feb 28 09:56:52 2007 From: noreply at python.org (Mail Administrator) Date: Wed, 28 Feb 2007 15:56:52 +0100 Subject: Mail System Error - Returned Mail Message-ID: <20070228145737.A1EB01E401B@bag.python.org> The original message was received at Wed, 28 Feb 2007 15:56:52 +0100 from [137.64.156.226] ----- The following addresses had permanent fatal errors ----- ----- Transcript of session follows ----- ... while talking to 189.80.161.199: 554 5.0.0 Service unavailable; [35.216.143.37] blocked using bl.spamcop.net, reason: Blocked Session aborted -------------- next part -------------- A non-text attachment was scrubbed... Name: Deleted0.txt Type: application/octet-stream Size: 142 bytes Desc: not available URL: From steve at holdenweb.com Sun Feb 11 05:24:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 10:24:39 +0000 Subject: pygame and python 2.5 In-Reply-To: <1171184901.012350.40140@q2g2000cwa.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Feb 11, 1:35?am, Steve Holden wrote: [...] >>>> After all, they have already given freely and generously, and if they choose >>>> not to give more on top of that, it's really up to them. >>> Right. Get people to commit and then abandon them. Nice. >> Anyone who committed to Python did so without being battered by a >> multi-million dollar advertising campaign. > > Multi-million dollar ad campaigns mean nothing to me. > I committed to Python because it's a great language. > I've dabbled in perl, Visual BASIC, UBASIC, REXX, Java, > Scheme, C and C++ but Python is the one I use. > Yes, but your decision must surely have been an informed one, and there must surely be reasons why Python remains your choice. >> The Python Software >> Foundation has only recently dipped its toes in the advocacy waters, >> with results that are still under evaluation. And the use of the >> Microsoft "free" VC6 SDK was never a part of the "official" means of >> producing Python or its extensions, it was a community-developed >> solution to the lack of availability of a free VS-compatible compilation >> system for extension modules. >> >> I agree that there are frustrations involved with maintaining extension >> modules on the Windows platform without having a copy of Visual Studio >> (of the correct version) available. One of the reasons Python still uses >> an outdated version of VS is to avoid forcing people to upgrade. Any >> such decision will have fallout. > > Such as anyone who tries to get in the game late. > I'm afraid it does seem to work out like that, yes. >> An update is in the works for those >> using more recent releases, > > That's good news, although the responsible thing > to do was not relaease version 2.5 until such issues > are resolved. > Well that would be an issue for the release team. I'm not sure what Anthony Baxter (the release manager) would have to say in response to this point. >> but that won't help users who don't have >> access to Visual Studio. > > That can be solved by throwing money at the problem. > But money doesn't help when the solution is on the > far side of the moon. > I see your problem, but I don't know what I can do to help you. There were also, as I remember it, issues with the updated version of Visual Studio being non-conformant with standards in some significant way, but I never took part in the discussions on those issues. >>>> Yes, it's >>>> occasionally very frustrating to the rest of us, but that's life. >>> As the Kurds are well aware. >> I really don't think you help your argument by trying to draw parallels >> between the problems of compiler non-availability and those of a >> population subject to random genocide. > > You missed the point of the analogy. > Perhaps because it wasn't a very good one? > The US government suggested to the oppressed tribes > in Iraq that they should rise up and overthrow > Saddam Hussein at the end of the first Gulf War. > And what did the US government do when they rose up? > Nothing. They were left to twist in the wind. > >> Try to keep things in perspective, please. > > See if you can see the similarity. > > I buy into Python. I spend a lot of effort > developing a math library based on GMPY to use > in my research. I discover a bug in GMPY and > actually go to a lot of effort and solve it. > But _I_ can't even use it because I've been > left to twist in the wind by the fact that > Python 2.5 for Windows was built with an > obsolete compiler that's not even available. > > Luckily, unlike the Kurds, my situation had > a happy ending, someone else compiled the fixed > GMPY source and made a 2.5 Windows version > available. But can anyone say what will happen > the next time? > Presumably not. I presume you have been reporting your bugs through the Sourceforge project to keep the developers in touch with the issues you have found? Normally a package's maintainers will produce updated installers, but this behaviour is unreliable and (no pun intended) patchy sometimes. >>>> The best I feel I can do is raise these things on occasion, >>>> on the off-chance that I manage to catch the attention of >>>> someone who is >>>> altruistic, knowledgeable, and who has some spare time on >>>> their hands! >>> Someone who, say, solved the memory leak in the GMPY >>> divm() function even though he had no way of compiling >>> the source code? >>> Just think of what such an altruistic, knowedgeable >>> person could do if he could use the current VC compiler >>> or some other legally available compiler. >> Your efforts would probably be far better spent trying to build a >> back-end for mingw or some similar system into Python's development >> system, to allow Python for Windows to be built on a regular rather than >> a one-off basis using a completely open source tool chain. > > No, as I said elsewhere, I'm not a software developer, > I'm an amateur math researcher. My efforts are best spent > as an actual end user to find and report bugs that the > developers never see. Remember, a programmer, because he > wrote it, only _thinks_ he knows how the program works. > Whereas I, the user, _know_ how it works. > >> The fact that the current maintainers of the Windows side of Python >> choose to use a commercial tool to help them isn't something I am going >> to try and second-guess. To do so would be to belittle efforts I would >> have no way of duplicating myself, and I have far too much respect for >> those efforts to do so. > > And I respect those efforts too. What I don't respect > is irresponsible behaviour. > >> There are published ways to build extension modules for Windows using >> mingw, by the way - have you tried any of them? > > Yeah, and got nowhere. > >> It's much harder than sniping on a newsgroup, > > That figures. You try and contribute and you get > accused of being a troll. > I wasn't accusing you of being a troll, rather bemoaning your (in my opinion) less-than-constructive tone. The points you raise are important, and I do feel that there ought to be easier solutions for people in your position. >> but you earn rather more kudos. > > Guess what kudos I got for solving the GMPY divm() > problem? None. How much effort would it have been > to mention my contribution in the source code > comments (as was the case for other contributers)? > Not that I'm bitter, after all, I'm altruistic. > I'm sure if you've made a contribution to the code you only have to ask for your name to be added as a contributor to be mentioned in the source. > By the way, on the sci.math newsgroup I promote > Python every chance I get. One fellow thanked me > profusely for recommending Python & GMPY and asked > for some help with a program he was having problems > with. We worked it out fine but his problem made me > suspect there may be more bugs in GMPY. What's my > motivation for tracking them down? > The satisfaction of a job well done? What's my motivation for acting as a director of the Python Software Foundation when I get accusations of irresponsibility? Anyway, thanks for taking the time to help maintain gmpy. This thread is starting to make me think that there's a case to be made for somehow providing supported build facilities for third-party extension modules. This wouldn't be a simple project, but since there's a Windows buildbot for Python there's no reason why the same couldn't be done for extensions. I'll raise this with the PSF and see what the response is: then your carping will at least have had some positive effect ;-) Stick with it, and let's try to make things better. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From http Thu Feb 15 00:59:27 2007 From: http (Paul Rubin) Date: 14 Feb 2007 21:59:27 -0800 Subject: threading and multicores, pros and cons References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> <7xzm7gt2sg.fsf@ruckus.brouhaha.com> Message-ID: <7xr6ssdkqo.fsf@ruckus.brouhaha.com> John Nagle writes: > If locking is expensive on x86, it's implemented wrong. > It's done right in QNX, with inline code for the non-blocking case. Acquiring the lock still takes an expensive instruction, LOCK XCHG or whatever. I think QNX is usually run on embedded cpu's with less extensive caching as these multicore x86's, so the lock prefix may be less expensive in the QNX systems. From gagsl-py at yahoo.com.ar Mon Feb 5 19:47:01 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 21:47:01 -0300 Subject: "flushing"/demanding generator contents - implications for injection of control References: <1170704863.646629.156310@h3g2000cwc.googlegroups.com> Message-ID: En Mon, 05 Feb 2007 16:47:43 -0300, metaperl escribi?: > For this program: > > def reverse(data): > for index in range(len(data)-1, -1, -1): > yield data[index] > > r = reverse("golf") > > for char in r: > print char > > > I'm wondering if the line: > > r = reverse("golf") > > "demands" the contents of the function reverse() all at once and if I > must write > > for char in reverse("golf"): > print char > > if I want the results streamed instead of generated complely. reverse is a generator; it executes one step at a time. That's the whole point of generators. -- Gabriel Genellina From http Mon Feb 12 01:20:24 2007 From: http (Paul Rubin) Date: 11 Feb 2007 22:20:24 -0800 Subject: randomly generate n of each of two types References: <3YOzh.1133$yg7.205@trnddc08> Message-ID: <7x3b5bzyl3.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > If you want to avoid shuffle, here's an alternative: > > def random_values(n, valuelist=[True, False]): > N = len(valuelist) > for _ in range(N*n): > yield valuelist[random.randrange(0, N)] That is not guaranteed to yield exactly equal numbers of true and false. From auch-ich-m at g-kein-spam.com Wed Feb 21 06:09:52 2007 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Wed, 21 Feb 2007 12:09:52 +0100 Subject: eval('000052') = 42? References: Message-ID: <542nk8F1t6krbU1@mid.individual.net> Astan Chee wrote: > Hi, > I just tried to do > eval('00052') and it returned 42. > Is this a known bug in the eval function? Or have I missed the way eval > function works? You know, it's just the answer to the ultimate question of Life, the universe, and everything. SCNR, nd From steve at REMOVEME.cybersource.com.au Thu Feb 1 21:43:09 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 02 Feb 2007 13:43:09 +1100 Subject: A* search implementation in Python References: <1170382917.837428.247930@s48g2000cws.googlegroups.com> Message-ID: On Thu, 01 Feb 2007 18:21:57 -0800, bearophileHUGS wrote: > Reid Priedhorsky: >> I'm looking for an open-source Python implementation of A* search for use >> in a mapping application. > > You can try this one: > http://aima.cs.berkeley.edu/python/search.html To paraphrase a wise saying: If you give a man a link, you satisfy his need for one day. But if you teach a man to search, you satisfy his need forever. Given that Reid had problems formulating a good search (because * is an operator in Google) what did you do? -- Steven D'Aprano From deets at nospam.web.de Fri Feb 23 06:55:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Feb 2007 12:55:10 +0100 Subject: Module trouble [newbie] References: Message-ID: <54830uF1ukj2kU1@mid.uni-berlin.de> Boris Ozegovic wrote: > Can somebody explaint this to me: > > I have module a.py > A = 100 > import b > print "A printing" > print "B is %s" % b.B > > and module b.py > B = 2000 > import a > print "B printing" > print "A is %s" % a.A > > I thought that output would be: > B printing > A is 100 > A printing > B is 2000 > > Because import b would execute b.py, and in b.py line "import a" would be > ignored, but my output is: > >>>> import a > 100 > A printing > B is 100 Are you sure the above is what you really used for your test? Because your output features a single 100, which the above lacks a print-statement for. Diez From horpner at yahoo.com Wed Feb 14 08:41:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 14 Feb 2007 14:41:53 +0100 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: On 2007-02-14, Gabriel Genellina wrote: > En Wed, 14 Feb 2007 03:09:37 -0300, jm.suresh at no.spam.gmail.com > escribi?: >> Is this way of implementation fill the stack space with the >> local variables inside each call. If this is not good, is >> there a better way to implement? Or python itself will >> understand that the calls happen in the last line, so local >> variables need not be pushed into the stack? > > I'm afraid not, the calls will be stacked until some object is > found. Python does not do "tail recursion optimization" (at > least, I'm not aware of that). To be just a little pedantic, it's "tail call optimization". Any tail call can be optimized, not just recursive ones. > But even if it could do that, in this case you have recursive > calls between two functions, and that's a bit harder. So the effect is that mutual recursion isn't actually any harder. Moreover, if his functions calls really are tail-calls, then translating them by hand into iteration might be fairly easy. A simple, silly example: def sum(seq): if len(seq) == 0: return 0 else: return seq[0] + sum(seq[1:]) Above, sum is not a tail call, since the + operation must be "defered" until after the call to sum returns. Below, sum is a tail call. def sum(seq, accum=0): if len(seq) == 0: return accum else: return sum(seq[1:], accum+s[0]) Since no state must be retained by sum when calling sum, it's a tail call. The last version translates more or less directly into a dumb while loop. I don't believe Python does tail call optimization; at least it isn't document that it does it. -- Neil Cerutti The audience is asked to remain seated until the end of the recession. --Church Bulletin Blooper From steve at holdenweb.com Wed Feb 7 15:46:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Feb 2007 20:46:19 +0000 Subject: Simple SVN/CVS-like library in Python? In-Reply-To: References: Message-ID: <45CA3A9B.4090908@holdenweb.com> Andrea Gavana wrote: > Hi All, > > in our office we work with quite complex input files for a > reservoir simulator. Those files have thousands of keywords, switches, > sub-keywords and whatever. Every time a modification is requested, we > modify the input file and re-run the simulator. Obviously, the > possible modifications are innumerable: so, after few months, we lose > the records of all the changes we made during time and we don't have > anymore a clear history of our work. This can be a problem, as > sometimes it happens that an old input file is requested by > collegues/sub-companies, and it is a pain to retrieve the correct file > and results. > So, I have written a GUI in wxPython that could help us in tracking > the history, but I was wondering if there exists a small and simple > SVN/CVS-like library in Python that may help us in a better way, > storing modifications/changes and showing which input file are the > "children" of (are derived from) another input file (older). > But I am open to all possible suggestions to improve/modify the > software, as this is an area in which my experience is about nothing > above zero. > > Thank you very much for every hint. > I should have thought that the best way to achieve this functionality would be to use the SVN or CVS commands using os.system or the subprocess module. There is at least one Python interface to Subversion, however. See http://pysvn.tigris.org/ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From bdesth.quelquechose at free.quelquepart.fr Fri Feb 16 16:44:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 16 Feb 2007 22:44:01 +0100 Subject: why I don't like range/xrange In-Reply-To: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: <45d61e34$0$29759$426a74cc@news.free.fr> stdazi a ?crit : > Hello! > > Many times I was suggested to use xrange and range instead of the > while constructs, and indeed, they are quite more elegant - but, after > calculating the overhead (and losen flexibility) when working with > range/xrange, and while loops, you get to the conclusion that it isn't > really worth using range/xrange loops. I've almost never had to use (x)range in a for loop. Usually, one just iterate over an iterable. (snip) > Next thing I miss is the flexibility as in C for loops : > > for (i = 0; some_function() /* or other condition */ ; i++) You may want to have a look at generators. The main idea here is to encapsulate the knowledge about how iteration is implemented, so the client code just have to iterate. > or, > > for (i = 0 ; i < 10 ; i++) > i = 10; for i in range(10): i = 10 What's your point, exactly ? > > I don't think range/xrange sucks, but I really think there should be > some other constructs to improve the looping flexibility. Have a look at generators then. From __peter__ at web.de Sat Feb 3 09:01:45 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 15:01:45 +0100 Subject: Python 2.5 Quick Reference References: <45C479EA.20908@jessikat.plus.net> Message-ID: Dick Moores wrote: > At 04:02 AM 2/3/2007, Robin Becker wrote: >>Dick Moores wrote: >> > >> > Is this reliable? (Looks good to me, but...) >> > >>..... >> >>I really like these for a good overview > > So it looks accurate? After perusing it, I dare say that not only is it accurate, Richard's comments seem both at the right places and spot-on. Peter From jura.grozni at gmail.com Sun Feb 11 08:36:28 2007 From: jura.grozni at gmail.com (azrael) Date: 11 Feb 2007 05:36:28 -0800 Subject: morpholgy toolbox Message-ID: <1171200988.103878.148320@j27g2000cwj.googlegroups.com> does any one have any expirience with mmorph module. At first i was unable to run it because some file was missing (instalation problem), but i managed it. but, did anyone manage to save the new mask, or anything created with it. From gagsl-py at yahoo.com.ar Tue Feb 13 10:53:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 12:53:32 -0300 Subject: Newbie question about Class References: Message-ID: En Tue, 13 Feb 2007 03:56:21 -0300, escribi?: > I'm reading the book of "Dive into Python" and got these code pieces: > class UserDict: > def __init__(self, dict=None): self.data = {} > if dict is not None: self.update(dict) > My question is,for the statement of: > if dict is not None: self.update(dict) > Why it's not this one below? > if dict is not None: self.data.update(dict) > Thanks. The idea behind that class is to act "as-if" it were a real dictionary. Dicts have an update method, and UserDict should too. But it's not listed in the book (should appear a few lines below that code); this is a possible implementation: def update(self, other): for key in other.keys(): self.data[key] = other[key] Given this method, __init__ works fine. Using self.data.update(dict) is OK if the dict argument is a real dictionary, but not if it's another UserDict. -- Gabriel Genellina From jan.m.danielsson at gmail.com Tue Feb 6 07:57:53 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 06 Feb 2007 13:57:53 +0100 Subject: Graphs, bar charts, etc Message-ID: <45c87a32@griseus.its.uu.se> Hello all, I have some data in a postgresql table which I view through a web interface (the web interface is written in python -- using mod_python under apache 2.2). Now I would like to represent this data as graphs, bar charts, etc. I know about matplotlib, and it seemed like exactly what I was looking for. I tried importing it in my script, but it gave me some error about a home directory not being writable. I'm not sure I like the idea of it require to be able to write somewhere. Am I using it wrong? Is there something else I can use which can produce graphs easily? -- Kind regards, Jan Danielsson From nogradi at gmail.com Tue Feb 13 12:35:26 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 13 Feb 2007 18:35:26 +0100 Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: <5f56302b0702130935p7678295ej6121cd3c56a69d5e@mail.gmail.com> > I use the thread module (not threading) for a client/server app where I > distribute large amounts of pickled data over ssh tunnels. > Now I get regular Segmentation Faults during high load episodes. I use a > semaphore to have pickle/unpickle run nonthreaded, but I still get > frequent nondeterministic segmentation faults. > Since there is no traceback after a sf, I have no clue what exactly > happened, and debugging a multithreaded app is no fun anyway :( > > Can someone recommend me how to get extra info during such a crash? > Or any other opinion on where the problem might lie? Hi, it would be helpful if you posted a minimalistic code snippet which showed the problem you describe. Daniel From jstroud at mbi.ucla.edu Fri Feb 16 05:56:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 16 Feb 2007 10:56:02 GMT Subject: Tkinter __call__ In-Reply-To: References: Message-ID: <65gBh.76610$qO4.45156@newssvr13.news.prodigy.net> Gigs_ wrote: > from Tkinter import * > from tkFileDialog import askopenfilename > from tkColorChooser import askcolor > from tkMessageBox import askquestion, showerror > from tkSimpleDialog import askfloat > > demos = { > 'Open': askopenfilename, > 'Color': askcolor, > 'Query': lambda: askquestion('Warning', 'You typed > "..."\nConfirm?'), > 'Error': lambda: showerror('Error!', "He's dead, Jim"), > 'Input': lambda: askfloat('Entry', 'Enter credit card number') > } > > > class Demo(Frame): > def __init__(self, parent=None): > Frame.__init__(self, parent) > self.pack() > Label(self, text="Basic demos").pack() > for (key, value) in demos.items(): > func = (lambda key=key: self.printit(key)) > Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) > def printit(self, name): > print name, 'returns =>', demos[name]() > > > I have tried but cant get it to work properly. > I want to instead printit method to put __call__ and call it like that > Can someone help me, please? The code you have should work. My guess is that you don't understand lambda and so you want to do it a "different" way, using a "callable"? Well, that's what lambda does, it makes a callable object: Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. py> key = 1 py> callable(lambda key=key: self.printit(key)) True py> '__call__' in dir(lambda key=key: self.printit(key)) True So the code you have already does what you want to do. Maybe understand what you are studying before you reinvent the wheel--you will save yourself a lot of frustration. James From ruan at jcmills.com Wed Feb 7 12:43:34 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Wed, 7 Feb 2007 12:43:34 -0500 Subject: what is wrong with my python code? Message-ID: I got feed back saying" list object is not callable". But I can't figure out what is wrong with my code. A=[3,5,4,9,6,7] l=len(A)-1 for i in range(l): print A(i) From kooch54 at gmail.com Wed Feb 7 09:22:23 2007 From: kooch54 at gmail.com (kooch54 at gmail.com) Date: 7 Feb 2007 06:22:23 -0800 Subject: Group Membership in Active Directory Query Message-ID: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> I am trying to write a script to simply query the group members in an active directory group. I need to use LDAP to make sure I capture any global > global group nestings that may occur. I already have a function that uses WinNT provider to capture this info from NT4 or AD domains and it works beautifully. It just doesn't capture global > global nestings. I am having great difficulties in getting this to work on AD though with ldap. I have a multiple domain tree environment and need to be able to query groups in different domains. I want to simply make an ldap connection, bind to it, search for the group and get it's members. I do the following for eDirectory and it works great but not in AD. import ldap l=ldap.open(1.2.3.4,trace_level = 1) l.simple_bind_s('cn=username,ou=company','password') UserRes = UserRes + l.search_s( o=company, ldap.SCOPE_SUBTREE, "(|'cn=groupname') If I do the same thing as above but to an AD source it doesn't work. I run the open and it seems successful, I run the bind using DN, UPN, or domain name and password and it seems to bind, I run the query and it says I must complete a successfull bind operation before doing a query. Any help is appreciated. From wolf_tracks at invalid.com Sat Feb 10 14:45:08 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 10 Feb 2007 11:45:08 -0800 Subject: Python 2.4 pdf Tutorial--Available Message-ID: <1hpzh.5885$4H1.5133@newssvr17.news.prodigy.net> I was able to download the 2.5 tutorial, but think I may need the 2.4 tutorial (Guido van Rossum) if it exists. Anyone know where to find it? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two billion years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From supervau at gmail.com Tue Feb 6 03:29:13 2007 From: supervau at gmail.com (Frank) Date: 6 Feb 2007 00:29:13 -0800 Subject: problems loading modules In-Reply-To: References: <1170654370.545302.277060@k78g2000cwa.googlegroups.com> Message-ID: <1170750552.731722.272410@v33g2000cwv.googlegroups.com> Thanks guys! From keir.robinson at gmail.com Thu Feb 22 12:48:51 2007 From: keir.robinson at gmail.com (keirr) Date: 22 Feb 2007 09:48:51 -0800 Subject: How to covert ASCII to integer in Python? In-Reply-To: References: Message-ID: <1172166531.625810.146340@k78g2000cwa.googlegroups.com> On Feb 22, 5:43 pm, "John" wrote: > Is there any built in function that converts ASCII to integer or vice versa > in Python? > > Thanks! Try int. ie. try: int_val = int(str_val) except ValueError: # conversion failed Keir. -- Keir Robinson Sometimes a scream is better than a thesis. (Emerson) From steve at holdenweb.com Fri Feb 16 11:34:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 11:34:19 -0500 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: <1171642551.277929.233540@l53g2000cwa.googlegroups.com> References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> <1171642551.277929.233540@l53g2000cwa.googlegroups.com> Message-ID: Endless Story wrote: > On Feb 16, 10:29 am, Tim Golden wrote: >> I would ask if you had *any* other Python installation >> -- say a cygwin one -- which might just be getting in the way? > > It's a cygwin problem, guddammit. I was wondering if this might be the > case - I should have mentioned in my initial post that I've got a > whole Cygwin setup, including Python. > > I know the conflict is the problem because just now I opened up a > command shell in XP (not the Cywgin bash window), and instead of > typing "python" and getting nothing, I tried "which python" - which > when you think about it, shouldn't even work in a XP shell. But > somehow Cygwin is mingling some of its capabilities with the XP shell, > because "which python" actually gets an answer - "/usr/bin/python," > which is Cygwin. > > Now the question is how to fix this - I don't want to uninstall the > Cygwin version. Instead I need some way of unknotting Cygwin's > intrusion into what should be an XP-only shell, or else a way of > giving priority when in that shell (and not the bash shell, which I > also use) to the Python executable residing at C:\Python25. > It sounds like you may have mistakenly added Cygwin binary directories to your Windows path. This isn't normally necessary, since the Cygwin shell makes all necessary path adjustments as it starts. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From cheekymonkey4_u at yahoo.com Thu Feb 15 00:09:44 2007 From: cheekymonkey4_u at yahoo.com (Virgin Mobile) Date: Thu, 15 Feb 2007 05:09:44 GMT Subject: Make 1.5 million in 10 minutes Message-ID: Find out how Roy . Made over 1 million in 10 minutes. http://alberta-oilsands.blogspot.com/2007/02/oil-and-gas.html From karoly.kiripolszky at gmail.com Mon Feb 5 08:55:33 2007 From: karoly.kiripolszky at gmail.com (=?iso-8859-1?q?K=E1roly_Kiripolszky?=) Date: 5 Feb 2007 05:55:33 -0800 Subject: C parsing fun In-Reply-To: References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> Message-ID: <1170683733.434435.171350@j27g2000cwj.googlegroups.com> You're right, thank you for the comment! I will look after how to avoid this. Marc 'BlackJack' Rintsch ?rta: > In <1170679559.272656.145660 at v33g2000cwv.googlegroups.com>, > karoly.kiripolszky wrote: > > > and the great thing is that the algorithm can be used with any > > language that structures the code with brackets, like PHP and many > > others. > > But it fails if brackets appear in comments or literal strings. > > Ciao, > Marc 'BlackJack' Rintsch From jgrzebyta at NO.gazeta.pl.SPAM Tue Feb 6 16:19:37 2007 From: jgrzebyta at NO.gazeta.pl.SPAM (Jacol) Date: Tue, 06 Feb 2007 21:19:37 +0000 Subject: Dlaczego ten destruktor nie dziala [_LONG_] References: <20070204170503.4dbb1b14.sulsa@gazeta.pl> Message-ID: Sulsa wrote: > Mam klase A po ktorej dziedziczy B i jesli w destruktorze klasy B > wywolam: > self.__class__.__bases__[0].__del__(self) > > to wszytkos jest ok, i destruktor klasy a jest wywolywany, jesli > natomiast napisze: A.__del__(self) to otrzymuje nastepujacy wyjatek: > Exception exceptions.AttributeError: "'NoneType' object has no > attribute '__del__'" in at 0x2b025d04a830>> ignored > > czemu tak sie dzieje? ?? Cze??, W?a?ciewie to nie rozumiem sensu pytania. :) Ja zrobi?em tak: class A: def __del__(self): print "Delete A" class B(A): def __del__(self): A.__del__(self) print "Delete B" potem sworzy?em instancj?: InstanceB=B() potem uruchomi?em destruktory: del(InstanceB) i moim oczom ukaza? si? komunikat: Delete A Delete B 1) Czy atrybut A.__del__(self) zosat? zdefiniowany przez Ciebie?? Domy?lny nie jest brany pod uwag?. Sprawdzi?em. class A: pass class B(A): def __del__(self): A.__del__(self) print "Co?tam" potem insta=B() del(insta) daje Exception exceptions.AttributeError: "class A has no attribute '__del__'" in > ignored PS.: Python 2.4.4c1 From nagle at animats.com Mon Feb 26 11:36:15 2007 From: nagle at animats.com (John Nagle) Date: Mon, 26 Feb 2007 16:36:15 GMT Subject: Python / Socket speed In-Reply-To: References: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> Message-ID: <30EEh.2082$BE2.1124@newssvr27.news.prodigy.net> Richard Brodie wrote: > wrote in message > news:1172501644.228475.57540 at a75g2000cwd.googlegroups.com... > >>Seems like sockets are about 6 times faster on OpenSUSE than on >>Windows XP in Python. >> >>http://pyfanatic.blogspot.com/2007/02/socket-performance.html >> >>Is this related to Python or the OS? > > > It's 6 times faster even when not using Python, so what do you think? > It's probably 'just' tuning though, the default window sizes are in the > same ratio. Sockets and pipes are a terrible way to do local interprocess communication, but it's what we've got. The problem is that what you want is a subroutine call, but what the OS gives you is an I/O operation. If you want to see it done right, take a look at QNX messaging. QNX does everything, including I/O and networking, via its interprocess communication message passing system. There's the cost of one extra copy for every I/O operation, but you don't notice it much in practice. I've run 640x480x15FPSx24bits video through QNX messaging and only used 2% of an 1.5GHZ x86 CPU doing it. John Nagle From Roka100 at gmail.com Sat Feb 10 22:48:57 2007 From: Roka100 at gmail.com (Jia Lu) Date: 10 Feb 2007 19:48:57 -0800 Subject: Can anyone explain a part of a telnet client code to me.. Message-ID: <1171165737.345518.281160@v45g2000cwv.googlegroups.com> Hello I have a program that can telnet to a host. But I cannot understand from [for c in data] part, can anyone explain it to me? Thank you very much. [CODE] import sys, posix, time from socket import * BUFSIZE = 1024 # Telnet protocol characters IAC = chr(255) # Interpret as command DONT = chr(254) DO = chr(253) WONT = chr(252) WILL = chr(251) def main(): # Get hostname from param host = sys.argv[1] try: # Get ip from hostname hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # Check param[2] as type of protocol if len(sys.argv) > 2: servname = sys.argv[2] else: # default use telnet servname = 'telnet' # If got servname as port num if '0' <= servname[:1] <= '9': # cast port num from str to int port = eval(servname) else: try: # Get port num by service name port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # Create a tcp socket s = socket(AF_INET, SOCK_STREAM) # Connect to server try: s.connect((host, port)) except error, msg: sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # Fork a proccess pid = posix.fork() # if pid == 0: # child -- read stdin, write socket while 1: line = sys.stdin.readline() s.send(line) else: # parent -- read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data = s.recv(BUFSIZE) # if recv nothing then Exit program if not data: # EOF; kill child and exit sys.stderr.write( '(Closed by remote host)\n') # Call posix function kill and send signal 9 to child posix.kill(pid, 9) sys.exit(1) cleandata = '' for c in data: if opt: print ord(c) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print '(DO)', else: print '(DONT)', opt = IAC + WONT elif c in (WILL, WONT): if c == WILL: print '(WILL)', else: print '(WONT)', opt = IAC + DONT else: print '(command)', ord(c) elif c == IAC: iac = 1 print '(IAC)', else: cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush() try: main() except KeyboardInterrupt: pass From faulkner891 at gmail.com Wed Feb 14 21:17:53 2007 From: faulkner891 at gmail.com (faulkner) Date: 14 Feb 2007 18:17:53 -0800 Subject: builtin set literal In-Reply-To: References: Message-ID: <1171505873.114289.226190@v33g2000cwv.googlegroups.com> On Feb 14, 11:55 am, Sch?le Daniel wrote: > Hello, > > lst = list((1,2,3)) > lst = [1,2,3] > > t = tupel((1,2,3)) > t = (1,2,3) > > s = set((1,2,3)) > s = ... > > it would be nice feature to have builtin literal for set type > maybe in P3 .. what about? > s = <1,2,3> > > Regards, Daniel sets aren't quite that useful or common. just use a list. and '<' and '>' already have syntactic meanings. and that would make python look more like C++, which nobody wants. From mahs at telcopartners.com Tue Feb 27 12:27:32 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 27 Feb 2007 09:27:32 -0800 Subject: Python Source Code Beautifier In-Reply-To: References: Message-ID: Franz Steinhaeusler wrote: > Use Spaces, size: 4 > detect mixed line ending > detect tabs mixed with space > trim trailing whitespaces. look at: tools/scripts/reindent.py > convert structs like: if (a > b): to if a > b: > fill in spaces, but not in functions between operators: > > a+=1 => a += 1 > p(t + 1) => p(t+1) > an ast pretty printer could do this sort of thing. I saw someone post about one on this list a couple of years ago, but can't quickly turn up the link. > > from "is" to "==" and "is not" to "!=" (ok a find replace could do that > easily also), but in a program that would be more comfortable. careful! >>> (1,2,3) == (1,2,3) True >>> (1,2,3) is (1,2,3) False >>> Michael From kristnjov at nospam.com Fri Feb 9 08:13:34 2007 From: kristnjov at nospam.com (Deniz Dogan) Date: Fri, 09 Feb 2007 14:13:34 +0100 Subject: UNIX shell in Python? In-Reply-To: <1171019415.764194.304470@q2g2000cwa.googlegroups.com> References: <1171019415.764194.304470@q2g2000cwa.googlegroups.com> Message-ID: Bart Ogryczak wrote: > On Feb 9, 8:49 am, Deniz Dogan wrote: >> Hello. >> >> I was thinking about writing a UNIX shell program using Python. Has >> anyone got any experience on this? Is it even possible? > > Use the Google, Luke. > http://sourceforge.net/projects/pyshell/ > Have patience, young padawan. From danielkleinad at gmail.com Thu Feb 1 09:41:02 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Thu, 01 Feb 2007 14:41:02 GMT Subject: Problem saving changes in MoinMoin pages Message-ID: <1cu3s21tl6lml00k991g20358mjh6m733r@4ax.com> [I'm having some difficulty contacting 'real' MoinMoin support channels so I am posting this question here. Hope that's ok.] I have a pressing need to get a wiki up and running in a fairly short timeframe. I did some investigations and the Python MoinMoin wiki seemed to be the best choice for me based on simplicity, the fact that I am already familiar with Python :-), it's free , and the installation was a snap! I'm having one initial problem however... When I edit a page and click 'Save', the next page that displays is an 'HTTP 500' error. I have to refresh the page to see the changes. I am missing something fundamental but I can't determin what it is as yet. I'm currently perusing the source code to see if I can figure it out, but any pre-help will be gladly accepted. Dan From 3dbernard at gmail.com Wed Feb 14 10:49:24 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 14 Feb 2007 10:49:24 -0500 Subject: How much memory used by a name Message-ID: <61d0e2b40702140749r20d187d6p9ab0d1874c4fa37a@mail.gmail.com> Hello, I would like to know if there is a way to know how much memory (bytes, kilobytes, megabytes, etc) a name is using. More specifically, I have this list of strings that I want to write to a file as lines. This list grows througout the script execution, and toward the end, the file is written. However I would like to know how much memory, before writing to the file, is this list using. Is it possible at all? Thanks Bernard From "greenbergj\" at NOSPAM wit.edu Wed Feb 21 04:59:05 2007 From: "greenbergj\" at NOSPAM wit.edu (Jordan Greenberg) Date: Wed, 21 Feb 2007 04:59:05 -0500 Subject: ipython shortcut to reload modules In-Reply-To: <1171883255.942996.270800@v33g2000cwv.googlegroups.com> References: <1171883255.942996.270800@v33g2000cwv.googlegroups.com> Message-ID: bernhard.voigt at gmail.com wrote: > Hey! > > I'm using ipython as my python shell and often run scripts with the > magic command %run: > > In [1]: %run script.py > > If modules are loaded within the script these are not reloaded when I > rerun the script. Hence, when I changed some of the modules loaded, I > have to call > > In [2]: reload(module1) > Out [2]: In [3]: reload(module2) > Out [3]: In [4]: %run script.py > > Is there a shortshut to reload the modules automatically before > rerunning the script? No. But if you're including them in the script, they won't be reloaded because they're already present in the namespace. If you do %reset before your %run, it'll clear up the namespace, so your script's import should work. Downside: its effectively the same as quitting out of ipython, and restarting it. Other then that, I don't think you have much choice. Oh, if you use the %edit command to edit these files, it should reload them when you're done editing. -Jordan From abubakerkiter2003 at yahoo.com Fri Feb 23 10:51:28 2007 From: abubakerkiter2003 at yahoo.com (abubakerkiter2003 at yahoo.com) Date: 23 Feb 2007 07:51:28 -0800 Subject: Apache Cgi (70007)The timeout specified has expired In-Reply-To: <1172245600.565599.225990@p10g2000cwp.googlegroups.com> References: <1172245600.565599.225990@p10g2000cwp.googlegroups.com> Message-ID: <1172245888.415034.125040@z35g2000cwz.googlegroups.com> naima.m... at gmail.com ?????: > Hello, > > When i run my python script, it works a moment and then stop with this > message in the log: > > (70007)The timeout specified has expired: ap_content_length_filter: > apr_bucket_read() failed refers to ...... > > I think my script is too long therefore the server stop it... > > how can i do to run all my python script? > > thanks for your help From gregturn at mindspring.com Fri Feb 16 15:44:28 2007 From: gregturn at mindspring.com (Goldfish) Date: 16 Feb 2007 12:44:28 -0800 Subject: Approaches of interprocess communication In-Reply-To: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <1171658668.526890.248240@m58g2000cwm.googlegroups.com> On Feb 16, 5:11 am, "exhuma.twn" wrote: > Hi all, > > Supposing you have two separate processes running on the same box, > what approach would you suggest to communicate between those two > processes. > Spring Python makes it easy to get processes talking to each other. You can write your code like you are talking locally, then when its time to separate it either into another thread, another python process, or on another node, it is just a reconfiguration issue. http://springpython.python-hosting.com/wiki/DistributedRemoting From vishal at veriwave.com Tue Feb 20 13:00:43 2007 From: vishal at veriwave.com (Vishal Bhargava) Date: Tue, 20 Feb 2007 10:00:43 -0800 Subject: Regd. converting seconds to hh:mm:ss format In-Reply-To: <7x3b50d8ri.fsf@ruckus.brouhaha.com> Message-ID: <200702201800.l1KI0j8h024251@nsa.veriwave.com> Is there an inbuilt library in Python which you can use to convert time in seconds to hh:mm:ss format? Thanks, Vishal From bignose+hates-spam at benfinney.id.au Thu Feb 1 17:00:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 09:00:09 +1100 Subject: Sorting a list References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c24563$0$31965$c3e8da3@news.astraweb.com> Message-ID: <87veilv8ra.fsf@benfinney.id.au> John Salerno writes: > Ah, so simply using sort() [on a list of tuples] will default to the > first element of each tuple? More precisely, list.sort will ask the elements of the list to compare themselves. Those elements are tuples; two tuples will compare based on comparison of their corresponding elements. -- \ "The cost of a thing is the amount of what I call life which is | `\ required to be exchanged for it, immediately or in the long | _o__) run." -- Henry David Thoreau | Ben Finney From beej at beej.us Thu Feb 8 06:15:53 2007 From: beej at beej.us (Beej) Date: 8 Feb 2007 03:15:53 -0800 Subject: Getting file line numbers from Nodes in a DOM? Message-ID: <1170933352.921631.301760@j27g2000cwj.googlegroups.com> I have a DOM parsed with xml.dom.mindom.parse()...for a particular Node, is there an easy way to get the line (and maybe even column) numbers that the element appeared in the original file? Thanks, -Beej From jm.suresh at gmail.com Wed Feb 7 06:04:19 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 7 Feb 2007 03:04:19 -0800 Subject: Vim search under cursor Message-ID: <1170846259.673825.26420@a34g2000cwb.googlegroups.com> Hi, I am using gvim to edit python source files. When I press "*" or "#", I would want to search for the attribute name under the cursor and not the entire string. For example, If I have os.error and pressing * on top of error searches for os.error rather than error. How to set this, any Idea? thanks. - Suresh From paul at boddie.org.uk Tue Feb 27 10:53:41 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Feb 2007 07:53:41 -0800 Subject: installing "pysqlite" In-Reply-To: <4670c$45e44f9d$9117fe9b$29410@news1.tudelft.nl> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <1172579710.514139.103170@s48g2000cws.googlegroups.com> <1172588999.749895.3310@j27g2000cwj.googlegroups.com> <4670c$45e44f9d$9117fe9b$29410@news1.tudelft.nl> Message-ID: <1172591621.694009.128620@a75g2000cwd.googlegroups.com> On 27 Feb, 16:34, Nader Emami wrote: > > I have first installed "sqlite" and then I have configure the > "setup.cfg" file of "pysqlite" package. I had to do two things in > 'pysqlite' directory: > 1- python setup.py build > 2- python setup.py install > > It has done without any error. I suppose that the installation is well > done, but I haven't yet test whether I can import the 'pysqlite' module > in python. But how you mean about "PYTHONPATH"? If I do "echo > $PYTHONPAT" i get an empty string. That meant that I don't have any > "PYTHONPATH". How can I assign a correct "path" to this variable? I was getting ahead of myself and forgot that you may have a version of Python that you installed yourself from source. If so, "python setup.py install" (without specifying --prefix) should put the package in the right place so that you don't have to worry about PYTHONPATH. Just try and "import pysqlite2", then see if it worked or not. Paul From phd at phd.pp.ru Thu Feb 8 11:04:57 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 8 Feb 2007 19:04:57 +0300 Subject: SQLObject 0.8.0b3 Message-ID: <20070208160457.GA24594@phd.pp.ru> Hello! I'm pleased to announce the 0.8.0b3 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.0b3 News and changes: http://sqlobject.org/devel/News.html What's New ========== News since 0.8.0b2 ------------------ * Separate "docs" subdirectory instead of the shared external one. For a more complete list, please see the news: http://sqlobject.org/devel/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From djbclark at gmail.com Fri Feb 9 09:12:01 2007 From: djbclark at gmail.com (Daniel Clark) Date: 9 Feb 2007 06:12:01 -0800 Subject: Sending CTRL-C event to console application In-Reply-To: References: <1170960845.457806.27260@p10g2000cwp.googlegroups.com> Message-ID: <1171030321.710838.187470@k78g2000cwa.googlegroups.com> On Feb 8, 9:12 pm, "Gabriel Genellina" wrote: > En Thu, 08 Feb 2007 15:54:05 -0300, Daniel Clark > escribi?: > > I have a Windows command line based application that only shuts down > > cleanly if it sees "CTRL-C" on the console. I need to automate the > > running of this application, but still allow the user sitting at the > > machine to cancel the process cleanly if he/she needs to. In Unix this > > would be a tiny shell script that used "kill -15", but under Windows > > there does not seem to be an easy way to do this, at least that I can > > find. > > > Below is a test program, based on CreateProcess.py from "Python > > Programming on Win32". The > > win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) lines > > don't seem to do anything. What they should do is nothing in the case > > of notepad, and exit out of the dir builtin process in the case of the > > cmd.exe process. > > > Any ideas on how to make this work? > > From your process creation code: > > > CreationFlags = win32process.CREATE_NEW_CONSOLE | \ > > win32process.CREATE_NEW_PROCESS_GROUP | \ > > win32process.NORMAL_PRIORITY_CLASS > > Fromhttp://msdn2.microsoft.com/en-us/library/ms683155.aspx > "Only those processes in the group that share the same console as the > calling process receive the signal. In other words, if a process in the > group creates a new console, that process does not receive the signal, nor > do its descendants." Thanks, although I'm 99% sure I've also tried it without CREATE_NEW_CONSOLE (with a process that should just die if sent CTRL- C, so it was monitorable via Task Manager) and it still didn't work. I'm going to try taking a different approach by using a GUI Automation tool like WATSUP [1] or pywinauto[2] next. > Maybe you have better luck on a Windows programming group, asking how to > send a Ctrl-C event (or a SIGINT signal) to another process attached to a > different console. >From what I've found via Google [3], Windows has no real concept of signals, and no equivalent to SIGINT. [1] WATSUP - Windows Application Test System Using Python http://www.tizmoi.net/watsup/intro.html [2] pywinauto - Python Win32 Automation http://www.openqa.org/pywinauto/ [3] how to send a SIGINT to a Python process? http://mail.python.org/pipermail/python-list/2005-October/343461.html From aisaac at american.edu Wed Feb 28 09:23:14 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 28 Feb 2007 14:23:14 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: "Steven D'Aprano" wrote in message news:pan.2007.02.28.02.39.13.562362 at REMOVEME.cybersource.com.au... > The easy, but inelegant, way is to set a flag. That is the approach I explored here: http://mail.python.org/pipermail/python-list/2007-February/428562.html Btw, I add some background comments about "why" here: http://mail.python.org/pipermail/python-list/2007-February/428651.html fwiw, Alan Isaac From S.Mientki-nospam at mailbox.kun.nl Wed Feb 7 15:04:14 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 07 Feb 2007 21:04:14 +0100 Subject: Python editor In-Reply-To: References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> <1170851197.656670.179590@a75g2000cwd.googlegroups.com> <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> Message-ID: <800d8$45ca30ae$d443bb3a$20806@news.speedlinq.nl> limodou wrote: > Maybe you can try ulipad. > thanks, although it doesn't look bad, and it certainly must have been a huge job doing this with Tcl/Tk, I don't think it can compete with PyScripter, except on Linux ;-) succes, cheers, Stef Mientki From gibo at gentlemail.com Mon Feb 19 21:07:04 2007 From: gibo at gentlemail.com (GiBo) Date: Tue, 20 Feb 2007 15:07:04 +1300 Subject: New-style classes (was Re: Checking for EOF in stream) In-Reply-To: References: <45DA39B0.7020403@gentlemail.com> <45DA4F53.90505@gentlemail.com> Message-ID: <45DA57C8.6090709@gentlemail.com> Gabriel Genellina wrote: > En Mon, 19 Feb 2007 22:30:59 -0300, GiBo escribi?: > >> Is there a reason why some classes distributed with Python 2.5 are not >> new-style classes? For instance StringIO is apparently "old-style" class >> i.e. not inherited from "object". Can I somehow turn an existing >> old-style class to a new-style one? I tried for example: >> class MyStreamIO(StreamIO, object): >> pass >> but got an error. > > Try again (and look carefully the error text) Ahhh, thanks! ;-) Just for the record: import StringIO class MyStringIO(StringIO, object): pass must of course be: class MyStringIO(StringIO.StringIO, object): pass One more question - is it likely that StringIO will be turned into new-style class in the future? The reason I ask is whether I should try to deal with detection of new-/old-style classes or take the old-styleness for granted and set in stone instead. GiBo From Laurent.LAFFONT-ST at adixen.fr Thu Feb 1 11:04:56 2007 From: Laurent.LAFFONT-ST at adixen.fr (Laurent.LAFFONT-ST at adixen.fr) Date: Thu, 1 Feb 2007 17:04:56 +0100 Subject: Python SECS-II module Message-ID: Hi, I searching for a python module which implements SEMI E-4 / E-5 SECS-II/HSMS communication protocol. Is anyone have informations about this ? Regards, Laurent Laffont < laurent.laffont-st at adixen.fr > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Peter.Mayne at hp.com Thu Feb 22 00:29:17 2007 From: Peter.Mayne at hp.com (Peter Mayne) Date: Thu, 22 Feb 2007 16:29:17 +1100 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 20 Feb 2007 00:44:24 +0000, Peter mayne wrote: > >> Steven D'Aprano wrote: >>> If Python 3 dropped the print >>> statement and replaced it with official_print_function(), how would that >>> help you in your goal to have a single code base that will run on both >>> Python 2.3 and Python 3, while still using print? >> Is there any reason why official_print_function isn't sys.stdout.write? > > Why would you want a convenience function like print to take one import, > three look-ups and 16 characters instead of always available, one look-up > and five characters? Because it's compatible between Python 2.x and Python 3.x? :-) Because without print as a keyword, I can say "print = sys.stdout.write" and still have (some) convenience? (Albeit still one import and one lookup, though given the probable time taken to do the I/O, why worry about the lookup?) Or, if your editor has an abbreviation facility like Eclipse, you can type sys.stdout.write with less than 5 keystrokes. >> I can't remember the last time I used print in actual code (apart from >> short-lived debugging lines), so I'm bewildered as to why print seems to >> be so important. > > print is important for the convenience, for short-lived debugging, and for > use in the interactive interpreter. Why use print in the interactive interpreter? Just type the expression. Hmm, I was expecting that that wouldn't always work, but: >>> x=3 >>> if x==3: x ... 3 >>> for i in range(x): ... i ... 0 1 2 PJDM From Anders+news at Arnholm.nu Wed Feb 14 04:15:13 2007 From: Anders+news at Arnholm.nu (Anders Arnholm) Date: Wed, 14 Feb 2007 10:15:13 +0100 Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: Sam skriver: > On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn > wrote: >> Well, C++ is a better language than C in many ways. So, if he needs to learn >> one of them, why does it have to be C? >> >> Another reason some people choose C++ over Python for some tasks is that >> they feel that larger programs benefit from strong, static type checking. >> I like both ways, but depending on the task, one or the other is better. > > C++ is -not- strongly typed. You can cast anything to void *, and > manipulate it in ways unimaginable. Plus there's the whole mess that > is pointer arithmetic and a weak typesystem... C++ can be both, The type systenm is as fragila as you like it to be. I mainlty use c++ when i the need stronger typing that Python och C can't give me. In some ways it's even stronger types than languanges as Java and ObjectiveC. C++ it however at least four different languanges, in one ball of soupe. And yes you can do it, that doesn't mean you have to dio it. As _functions in python or __, you can use them from anyware, you don't have to. / Balp -- http://anders.arnholm.nu/ Keep on Balping From roopesh.raj at gmail.com Wed Feb 28 08:29:20 2007 From: roopesh.raj at gmail.com (Roopesh) Date: 28 Feb 2007 05:29:20 -0800 Subject: cPickle EOF Error Message-ID: <1172669360.584964.323190@p10g2000cwp.googlegroups.com> I am trying to write xml files which are inside a zip file into the database. In the zipfile module the function read returns bytes. What I did was to make a blob out of the returned bytes and write it to the database(for this I used cPickle). I also used _mysql's escape_string which escapes some characters (without this the file content was not getting written). But once we try to unpickle the content, an EOF error is getting thrown. When I tried putting the content(xml in database) to a file without unpickling then the xml file with escape characters gets printed. My code is as follows : def import_cards(): try : conn = MySQLdb.connect(host="localhost",port=3306,user="roopesh",passwd="pass",db="mydbs") cursor = conn.cursor() cursor.execute("CREATE TABLE card (serial_no int(10), id varchar(50), data blob, used char(1), ip varchar(20), date_downloaded datetime)") z = zipfile.ZipFile('/home/roopesh/public_html/ cards.zip', 'r') sql = "INSERT INTO card (serial_no, id, data, used) values (%s, %s, %s, %s)" for filename in z.namelist() : bytes = z.read(filename) data = cPickle.dumps(bytes, 2) #print data cursor.execute(sql, (1, filename , _mysql.escape_string(data), 'n')) sql = "SELECT serial_no, id, data, used FROM card" cursor.execute(sql) for serial_no, id, data, used in cursor.fetchall() : print serial_no, id, cPickle.loads(data.tostring()) # f = open(id ,'wb') # f.write(data.tostring()) finally : cursor.execute("DROP TABLE card") conn.close() return True The output is : -------------------- roopesh at dg:~/public_html$ python cardManagement.py 1 cards/passcard1.xml Traceback (most recent call last): File "cardManagement.py", line 136, in ? import_cards() File "cardManagement.py", line 28, in import_cards print serial_no, id, cPickle.loads(data.tostring()) EOFError From horpner at yahoo.com Fri Feb 2 09:01:42 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 15:01:42 +0100 Subject: How do I print out in the standard output coloured lines References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> <1170419225.989358.311600@h3g2000cwc.googlegroups.com> Message-ID: On 2007-02-02, rzed wrote: > cniharral at gmail.com wrote in > news:1170419225.989358.311600 at h3g2000cwc.googlegroups.com: > >> On Feb 2, 1:16 pm, rzed wrote: >>> cnihar... at gmail.com wrote >>> innews:1170417631.268771.108090 at v45g2000cwv.googlegroups.com: >>> >>> > Hi, >>> >>> > I'm interested in printing out coloured lines of my >>> > application and >>> > I don't know what to use. Can anybody give me an idea?? >>> >>> You could speed up the process if you explain what your >>> application is and what you mean by colored lines. Does your >>> application emit output to a plotter, an ink-jet printer, or a >>> color laser printer? Is it a drawing program? An editor in >>> which you want lines colored to highlight context? It might be >>> useful to know what system you are running as well. Just a >>> little detail here. >>> >>> -- >>> rzed >> >> Well, yes, it's a program that prints out lines to the standard >> output with a print command, and I want to print them coloured. >> For example: >> >> print "Hello World!!" >> >> I want it in red colour. >> >> That's all. > > If you're on Linux, you could use the curses module. There may > be a precompiled Windows version compatible with your Python > version, or maybe not, but the Windows source is available, and > you may be able to get it to work with your Python with some > effort. Linux distros include curses, I think. For Windows > curses, take a look at . > You will understand why the phrase "Windows curses" is used, I > expect. On Windows, there's pdcurses for DOS or ncurses for the Cygwin platform, but I don't know how to get either to work with Python. Far simpler to get working in Windows is Fredrik Lundh's Console. http://www.effbot.org/downloads/#console If you're using Windowd 98 or earlier there are versions of a Python readline library that provide cursor addressing and color using the ANSI excape sequences. -- Neil Cerutti From bmaron2 at hotmail.com Tue Feb 27 06:45:24 2007 From: bmaron2 at hotmail.com (bmaron2 at hotmail.com) Date: 27 Feb 2007 03:45:24 -0800 Subject: Help on object scope? In-Reply-To: References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> Message-ID: <1172576724.580582.65890@z35g2000cwz.googlegroups.com> On Feb 26, 1:16 pm, Dennis Lee Bieber wrote: > On Mon, 26 Feb 2007 07:54:12 +0200, "Hendrik van Rooyen" > declaimed the following in comp.lang.python: > > > > > from param import * > > "from <> import *" (or any "from <> import ..." variant) is NOT the > best thing to use. > > Any rebinding to an imported name breaks the linkage to the import > module. > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Thank you all for the advice. The suggestion Dennis made about using a 3rd, "common" module to hold global names seemed to be the best idea. The only problem is now I have to type common.r.t instead of just r.t. If I put common in the / lib directory, it is even worse and I have to type lib.common.r.t. I like that it is explicit and perhaps this is the Python way, but it is annoying and produces ugly code to see all those fully-qualified names when all I'd really like to use is r.t throughout the program. Is there a way to import lib.common but then re-bind its attributes to the local space without breaking the linkage? From sturlamolden at yahoo.no Wed Feb 7 11:19:26 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 7 Feb 2007 08:19:26 -0800 Subject: multithreading concept In-Reply-To: References: Message-ID: <1170865166.423764.87050@s48g2000cws.googlegroups.com> On Feb 7, 2:53 am, "S.Mohideen" wrote: > Python is praised about - me too. But at one instance it fails. It fails to > behave as a true multi-threaded application. That means utilizing all the > CPUs parallely in the SMP efficiently stays as a dream for a Python > Programmer. This has been discussed to death before. Win32 threads and pthreads (which is what Python normally uses, depending on the platform) are designed to stay idle most of the time. They are therefore not a tool for utilizing the power of multiple CPUs, but rather make certain kind of programming tasks easier to program (i.e. non-blocking I/O, responsive UIs). The GIL is not a problem in this context. If threads stay idle most of the time, the GIL does not harm. If you want to utilize the computing power of multiple CPUs, you should use multiple processes instead of threads. On Python this is mandatory due to the GIL. In any other language it it highly recommended. The de-factor standard for parallel multiprocessing (MPI) uses multiple processes, even on SMPs. Anyone with serious intentions of using multiple processors for parallel computing should use multiple processes and fast IPC - not multiple threads, shared memory and synchronization objects - even if the language is plain C. With multiple threads, a lot of time is wasted doing context switches and book keeping for the thread synchronization. In addition, obscure and often very difficult to identify bugs are introduced. There are a Python binding for MPI (mpi4py) and a similar pure Python project (Parallel Python) that will take care of all these details for you. > Discussion threads say its due to GIL - global interpreter lock. But nobody > has mentioned any alternative to that apart from suggestions like "Code it > in C" and POSH (http://poshmodule.sf.net). Is there any other way we can > make Python programs really multithreaded in real sense. As mentioned, use MPI or Parallel Python. MPI is by far the more mature, but Parallel Python could be easier for a pythoneer. Multithreading has different use. From tubby at bandaheart.com Tue Feb 27 16:40:46 2007 From: tubby at bandaheart.com (tubby) Date: Tue, 27 Feb 2007 16:40:46 -0500 Subject: threading a thread In-Reply-To: <54jm2pF20dq64U2@mid.individual.net> References: <54jm2pF20dq64U2@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > tubby wrote: >> Right now I'm just prototyping and the threaded hosts portion >> works very well for my needs. I'd just like to add a threaded >> ports check and wanted to know if anyone had done something >> similar in Python. > > Taken the vast amount of threads you'll need, there will be a big > overhead. Using a different means of concurrency is advisable. > > BTW, why not use nmap? Have you tried it? Nmap is sequential. It takes about 5 hours to do web server checks (port 80 only) on a class B network... I think it does ports in parallel, but not hosts. Even when you use the insane time setting the wait is untimely. I can do the same thing in roughly 15 minutes with Python or Ruby using threads. Granted, Nmap is much more configurable and flexible, but it simply does not scale to address large networks...nessus is the same way. Also remember that we're dealing with IPv4 networks now. How will we deal with larger IPv6 address spaces. Besides clustering and distributed processing (mapreduce), it seems that threads may help deal with some of the scaling issues I face right now. From dubrovsky at physics.uq.edu.au Thu Feb 1 21:29:15 2007 From: dubrovsky at physics.uq.edu.au (Alejandro Dubrovsky) Date: Fri, 02 Feb 2007 12:29:15 +1000 Subject: "Correct" db adapter References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> <1170262532.590048.247580@a75g2000cwd.googlegroups.com> <45c0d078$0$435$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > king kikapu a ?crit : >> Thanks for the replies. >> >> I think i do not need something like ORM, but just a db-module that i >> can "work" the database with it. > > FWIW, SQLAlchemy is not an ORM, but an higher-level API for SQL > integration. The ORM part is an optional feature built on top of this > API. But I'm not sure SQLAlchemy supports SQL Server anyway !-) > >> I just want to know if pyodbc is the "correct" solution to do so or if >> it is another db-module that is more >> usefull for this job. > > AFAICT: > > * there's an experimental MS SQL Server db-module: > http://www.object-craft.com.au/projects/mssql/ > > * the Win32 extensions offers support for ADO, but then it's not db-api > compliant > > * unless you use adodbapi, but I don't know if it's still supported > (last release is 3+ years old): > http://adodbapi.sourceforge.net/ > > HTH There's also pymssql which works well enough most of the time. From mail at microcorp.co.za Fri Feb 23 01:40:33 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 23 Feb 2007 08:40:33 +0200 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <022501c75716$ab3c47e0$03000080@hendrik> "Steven D'Aprano" wrote: > On Thu, 22 Feb 2007 08:18:07 +0200, Hendrik van Rooyen wrote: > > > I would xor each char in it with 'U' as a mild form of obfuscation... > > I've often wished this would work. > > >>> 'a' ^ 'U' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for ^: 'str' and 'str' > > instead of the more verbose > > >>> chr(ord('a') ^ ord('U')) > '4' you are not alone in this - to do something simple like calculating a BCC on a string, or a checksum like at the end of a line in an Intel hex file is a bit of a pain in Python. > > > > Look at the array module to get things you can xor, or use ord() on > > each byte, and char() > > Arrays don't support XOR any more than strings do. What's the advantage to > using the array module if you still have to jump through hoops to get it > to work? I think you will have less function calls, but I may be wrong: s = 'some string that needs a bcc appended' ar = array.array('B',s) bcc = 0 for x in ar[:]: bcc ^= x ar.append(bcc) s=ar.tostring() > > ''.join([chr(ord(c) ^ 85) for c in text]) > > is probably about as simple as you can get. > This is nice and compact. It would be very nice if you could just use a single char string like an int and apply the operators to it - the Python way seems so left- handed - make it an int, do the work, make it back into a string - and all the time we are working on essentially a one byte value... - Hendrik From nogradi at gmail.com Wed Feb 28 12:33:35 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 28 Feb 2007 18:33:35 +0100 Subject: Curious UnboundLocalError Behavior In-Reply-To: <33acb3db0702280915s12c1df60j31961bca1fd75068@mail.gmail.com> References: <33acb3db0702280915s12c1df60j31961bca1fd75068@mail.gmail.com> Message-ID: <5f56302b0702280933m19386f2as8e481e8b51f7987@mail.gmail.com> > I'm probably fundamentally misunderstanding the way the interpreter > works with regard to scope, but is this the intended behavior... > [....] > SOMEGLOBAL: > Traceback (most recent call last): > File "unboundlocal.py", line 15, in ? > foo() > File "unboundlocal.py", line 11, in foo > print "SOMEGLOBAL:",SOMEGLOBAL > UnboundLocalError: local variable 'SOMEGLOBAL' referenced before assignment [......] > import os,sys > > SOMEGLOBAL=1 > > def foo(): > dome=False > if dome: > SOMEGLOBAL = 0 > > print globals() > print "SOMEGLOBAL:",SOMEGLOBAL > > print os.uname() > print sys.version > foo() > Try: import os,sys SOMEGLOBAL=1 def foo(): global SOMEGLOBAL dome=False if dome: SOMEGLOBAL = 0 print globals() print "SOMEGLOBAL:",SOMEGLOBAL print os.uname() print sys.version foo() HTH, Daniel From bbbart at inGen.be Mon Feb 5 06:08:17 2007 From: bbbart at inGen.be (Bart Van Loon) Date: Mon, 5 Feb 2007 16:08:17 +0500 Subject: in place-ness of list.append References: Message-ID: It was Mon, 05 Feb 2007 11:00:50 GMT, when Kent Johnson wrote: > Bart Van Loon wrote: >> Hi all, >> >> I would like to find out of a good way to append an element to a list >> without chaing that list in place, like the builtin list.append() does. >> >> currently, I am using the following (for a list of integers, but it >> could be anything, really) >> >> #-------------------------------------------------- >> def addnumber(alist, num): >> """ work around the inplace-ness of .append """ >> mylist = alist[:] >> mylist.append(num) >> return mylist >> #-------------------------------------------------- > > Use + : > > In [1]: a=[1,2] > > In [2]: b=a+[3] > > In [3]: a > Out[3]: [1, 2] > > In [4]: b > Out[4]: [1, 2, 3] should have known that... thanks for you fast response! -- regards, BBBart "Who can fathom the feminine mind?" -Calvin "I like `em anyway" -Hobbes From aboudouvas at panafonet.gr Tue Feb 27 11:04:45 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 27 Feb 2007 08:04:45 -0800 Subject: book for a starter In-Reply-To: <1172591557.825839.299470@m58g2000cwm.googlegroups.com> References: <1172591557.825839.299470@m58g2000cwm.googlegroups.com> Message-ID: <1172592285.415534.269320@q2g2000cwa.googlegroups.com> Me, i bought this http://www.amazon.com/Core-Python-Programming-2nd/dp/0132269937/sr=8-1/qid=1172592163/ref=pd_bbs_sr_1/105-9302229-1138834?ie=UTF8&s=books and i really think it is a great book for learning Python. It refers to the latest Python version (2.5) and covers a lot of things, besides the language. From scott.daniels at acm.org Tue Feb 13 21:46:29 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 13 Feb 2007 18:46:29 -0800 Subject: Testers please In-Reply-To: <45d2449e$1@clear.net.nz> References: <8cde9$45d179ba$83aef404$16072@news1.tudelft.nl> <45d2449e$1@clear.net.nz> Message-ID: <12t4tuel9uah410@corp.supernews.com> Martien Friedeman wrote: > The size of the 'recording' is a major drawback, it was clearly not meant > to record the processing of millions of records. > > I need to find a way to specify the area in the code that needs recording. Use something like zlib and write a compressed log -- especially with logs you are working with highly compressible data. The gzip module can be used to easily write to it on the fly (incrementally). You'll find with very little effort you'll get very good compression. Recently I saw a set of standard logs, not designed for any compression, showing a factor of 9 compression -- that is, I was seeing less than a single bit required per byte in the original. -- --Scott David Daniels scott.daniels at acm.org From paddy3118 at netscape.net Sat Feb 3 03:52:38 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 00:52:38 -0800 Subject: Regd. Regular expressions PyQt In-Reply-To: References: Message-ID: <1170492758.498303.55730@v33g2000cwv.googlegroups.com> On Feb 3, 8:24 am, vis... at veriwave.com wrote: > Hello All: > I am trying to work out a regular expression in a PyQt environment for > time in hh:mm:ss format. Any suggestions? > Thanks, > Vishal Yep, Use Kodos! http://kodos.sourceforge.net/ - It's Fab. - Paddy. From horpner at yahoo.com Fri Feb 9 09:52:37 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 9 Feb 2007 15:52:37 +0100 Subject: Is Python for me? References: Message-ID: On 2007-02-09, jiddu wrote: > Hi, > > I'm planning to create a poker calculator, I learned some basic > in highschool years ago and I was told for beginners Python is > a good language to start. Python *is* a good language to start. > What I wanted to do is to first write a program which will be > able to run through all the possible combinations of cards > dealt out and use some counters to calculate different > probabilities at different stages. Since that is a lot of data > I think I have to store it in some kind of database or > spreadsheet type thing? Unfortunately, that is a very *difficult* problem; no programming library (save a hypothetical poker probability library) can make it easy. > Then I wanted to write a simple user interface so I could use > my mouse to make selections of cards that I am dealt and that > come on the flop and how many opponents and have the program > find the calculated information and display it on the screen. > > I am wondering if I learn to use Python will I be able to write > something like this? My friend studied some C in college so I > thought I'd learn C++, turns out it is a very complicated > language so I thought maybe I should try something else before > I commit more time to the language. Python can help you with creating an user interface, and with several simple, powerful data structures. I think you ought to lower your ambition a bit, at first. Firts write a program to rank complete sets of poker hands. That should hold you for a while. -- Neil Cerutti The recording I listened to had Alfred Brendel doing the dirty work of performing this sonata (Liszt B minor) --Music Lit Essay From moin at blackhole.labs.rootshell.ws Tue Feb 6 19:14:17 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Tue, 6 Feb 2007 18:14:17 -0600 Subject: Threading in Python Message-ID: <000901c74a4c$e9a4a580$e9936540@cisco.com> Python is praised about - me too. But at one instance it fails. It fails to behave as a true multi-threaded application. That means utilizing all the CPUs parallely in the SMP efficiently stays as a dream for a Python Programmer. Discussion threads say its due to GIL - global interpreter lock. But nobody has mentioned any alternative to that apart from suggestions like "Code it in C" and POSH (http://poshmodule.sf.net). Is there any other way we can make Python programs really multithreaded in real sense. Moin From S.Mientki-nospam at mailbox.kun.nl Sun Feb 4 05:23:43 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 04 Feb 2007 11:23:43 +0100 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: <87tzy2utjl.fsf@smsnet.pl> References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> <87tzy2utjl.fsf@smsnet.pl> Message-ID: <6eb8$45c5b41a$d443bb3a$2475@news.speedlinq.nl> > Do you mean something like that? > >>>> import some_module > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named some_module >>>> import sys >>>> sys.path.append("..") >>>> import some_module Rob, thank you very much, that's exactly what I want. (Why is the obvious so often invisible to me ;-) cheers, Stef Mientki From andrew-news at andros.org.uk Sun Feb 18 14:48:09 2007 From: andrew-news at andros.org.uk (Andrew McLean) Date: Sun, 18 Feb 2007 19:48:09 +0000 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? In-Reply-To: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> References: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> Message-ID: Where you would use varargin and nargin in Matlab, you would use the *args mechanism in Python. Try calling def t1(*args): print args print len(args) with different argument lists Where you would use varargout and nargout in Matlab you would use tuple unpacking in Python. Play with this def t2(n): return tuple(range(n)) a, b = t2(2) x = t2(3) From deets at nospam.web.de Sun Feb 18 08:06:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Feb 2007 14:06:41 +0100 Subject: Complex HTML forms In-Reply-To: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> References: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> Message-ID: <53r1bgF1t3pg1U1@mid.uni-berlin.de> George Sakkis schrieb: > I'd like to gather advice and links to any existing solutions (e.g. > libraries, frameworks, design patterns) on general ways of writing > complex web forms, as opposed to the typical {name:value} flat model. > A particular case of what I mean by complex is hierarchical forms. For > instance, a form that consists of a select list widget, where each > item of the list activates a distinct set of other widgets. Think for > example of a web frontend to CSV or SVN options and commands, where > each command has its own suboptions. The suboptions are hidden (or > even inexistent) until the user selects the specific command, and only > then they appear (typically by Javascript). When the form is > submitted, the selected options are passed in the server in some form > that preserves the hierarchy, i.e. not as a flat dict. Is there > anything close to such a beast around ? formencode, which is heavily used in TurboGears. The dynamic parts though you have to code yourself - but using mochikit, this is easy as cake... Diez From nszabolcs at gmail.com Mon Feb 5 08:00:35 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 5 Feb 2007 05:00:35 -0800 Subject: C parsing fun In-Reply-To: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> Message-ID: <1170680435.129554.133030@a34g2000cwb.googlegroups.com> > based on concepts my boss had. To do this I needed to represent C++ > code structure in Python somehow. I read the docs for Yapps, pyparsing > and other stuff like those, then I came up with a very simple idea. I > realized that bracketed code is almost like a Python list, except I > have to replace curly brackets with squared ones and surround the > remaining stuff with quotes. This process invokes no recursion or node yes that's a nice solution sometimes it's not enough though (won't work on code obfuscated with macros) anyway if you need something more sophisticated then i'd recommend gccxml or it's python binding: http://www.language-binding.net/pygccxml/pygccxml.html From studiescircle at yahoo.com Sat Feb 10 12:47:14 2007 From: studiescircle at yahoo.com (studiescircle at yahoo.com) Date: 10 Feb 2007 09:47:14 -0800 Subject: How to Speed Up Internet Searches?? Message-ID: <1171129634.795533.325560@k78g2000cwa.googlegroups.com> How to Speed Up Internet Searches?? When you go to a web site, the first thing that happens is that......... and for networking tips see at http://www.studyandjobs.com/network_tip.html or http://www.studyandjobs.com/IT_study.htm thanx From Roka100 at gmail.com Thu Feb 1 01:51:38 2007 From: Roka100 at gmail.com (Jia Lu) Date: 31 Jan 2007 22:51:38 -0800 Subject: Can I import a file without file extension .py? In-Reply-To: References: <1170305999.001998.251390@m58g2000cwm.googlegroups.com> Message-ID: <1170312698.028776.111320@l53g2000cwa.googlegroups.com> > > def make_module_from_file(module_name, file_name): > """ Make a new module object from the code in specified file """ > > from types import ModuleType > module = ModuleType(module_name) > > module_file = open(file_name, 'r') > exec module_file in module.__dict__ Thank you very much. And can you tell me what does " exec module_file in module.__dict__ " mean? Thanx From giles_brown at hotmail.com Wed Feb 14 03:23:44 2007 From: giles_brown at hotmail.com (Giles Brown) Date: 14 Feb 2007 00:23:44 -0800 Subject: _ssl.pyd is buggy? In-Reply-To: <1171412279.368565.295060@v45g2000cwv.googlegroups.com> References: <45D1F804.8050609@designaproduct.biz> <1171412279.368565.295060@v45g2000cwv.googlegroups.com> Message-ID: <1171441424.713853.212150@v33g2000cwv.googlegroups.com> On 14 Feb, 00:17, "Giles Brown" wrote: > Something I always found useful is to use the win32traceutil to set up > the trace debugging tool. > You can then see the output in the pythonwin trace collector tool. > This is very useful for > Python services and COM servers. > > Best of luck, > Giles Eh? Wrong thread. Damn the new google groups interface! From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Feb 18 07:30:46 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 18 Feb 2007 13:30:46 +0100 Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: <53qv7nF1tm16nU1@mid.individual.net> Stef Mientki wrote: > Some examples: > - Creating a treeview (like in the M$ explorer), with full edit > capabilities and full drag & drop facilities: Delphi takes about > 40 lines of code (most of them even ^C ^V). - Creating a graphical > overview of relations between database tables, which can be > graphical manipulated by the user (like in M$ Access): Delphi 20 > lines of code. I wonder what this costs in Python ? My Chrysler 300C SRT8 takes someVeryLowNumber seconds to accelerate to 100 mph. I wonder how long this takes with a BMW? > I would love to see: > - a comparison between wx and gtk Best would be to try the introduction tutorials yourself. Also be aware that wxWidgets and GTK are C/C++ libraries and wxPython and wxGTK are "just" Python bindings with a few enhancements for it. > (QT doesn't have a very inviting license ;-) GNU GPL isn't inviting? Regards, Bj?rn -- BOFH excuse #352: The cables are not the same length. From usenet200701 at tobyinkster.co.uk Fri Feb 9 05:59:01 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Fri, 9 Feb 2007 10:59:01 +0000 Subject: Thanks for the help References: <1171015554.461467.178340@q2g2000cwa.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com wrote: > Reid wrote: > >> I do not need 3d stuff. Just a couple of buttons and menu's. > > That's not "3D", that's GUI (Graphical User Interface). "3D" usually > refers to "3D graphics"... Hence the original poster's clever use of the word "not" ;-) -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From jstroud at mbi.ucla.edu Mon Feb 5 18:36:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 05 Feb 2007 15:36:08 -0800 Subject: Coordinate Grid Points In-Reply-To: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> Message-ID: Eric.Gabrielson at gmail.com wrote: > Hello, > I am very knew to python and am attempting to write a program > in python that a friend of mine is having to write in java. I am doing > this for fun and would like some help as to how i can generate random > coordinate points (x,y) and compare them with user inputted coordinate > points. For example how will I be able to access the separate values, > the x from the x,y position. I think I understand everything except > 1)the random coordinate points 2) the getting the users inputted x and > y values in one line ("Please guess a coordinate point from (1,1) to > (20,20): ") as opposed to ("Please enter an x value:" and "Please > enter a y value") and finally 3) acessing the x value from the x,y > coordinate function. the assignment description is located here http:// > www.cs.washington.edu/education/courses/142/07wi/homework/ > homework.html if you would like to see a more in depth discription of > the game. > > Many Thanks, > Eric > For the game described, the input is of the form "20 20", so (1) eval won't work and (2) regex is not needed. So you should use a healthy combo of map(), inpt.split(), int(), and inpt.strip() (assuming inpt is the string input). But not necessarily in the order listed. From http Wed Feb 7 12:47:07 2007 From: http (Paul Rubin) Date: 07 Feb 2007 09:47:07 -0800 Subject: what is wrong with my python code? References: Message-ID: <7xzm7p2738.fsf@ruckus.brouhaha.com> "Dongsheng Ruan" writes: > for i in range(l): > print A(i) Use square brackets, A[i]. Usually we'd write such a loop like this: for x in A: print x From steve at holdenweb.com Tue Feb 20 13:11:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 20 Feb 2007 13:11:22 -0500 Subject: Regd. converting seconds to hh:mm:ss format In-Reply-To: <200702201800.l1KI0j8h024251@nsa.veriwave.com> References: <7x3b50d8ri.fsf@ruckus.brouhaha.com> <200702201800.l1KI0j8h024251@nsa.veriwave.com> Message-ID: <45DB39CA.8050505@holdenweb.com> Vishal Bhargava wrote: > Is there an inbuilt library in Python which you can use to convert time in > seconds to hh:mm:ss format? > Thanks, > Vishal > Please don't ask a question by editing a reply to an existing thread: your question is now filed on many people's computers under "How to test if one dict us a subset of another". Look at the strftime() function in the time module. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gigs at hi.t-com.hr Fri Feb 16 07:09:27 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 16 Feb 2007 13:09:27 +0100 Subject: Tkinter __call__ In-Reply-To: <65gBh.76610$qO4.45156@newssvr13.news.prodigy.net> References: <65gBh.76610$qO4.45156@newssvr13.news.prodigy.net> Message-ID: James Stroud wrote: > Gigs_ wrote: >> from Tkinter import * >> from tkFileDialog import askopenfilename >> from tkColorChooser import askcolor >> from tkMessageBox import askquestion, showerror >> from tkSimpleDialog import askfloat >> >> demos = { >> 'Open': askopenfilename, >> 'Color': askcolor, >> 'Query': lambda: askquestion('Warning', 'You typed >> "..."\nConfirm?'), >> 'Error': lambda: showerror('Error!', "He's dead, Jim"), >> 'Input': lambda: askfloat('Entry', 'Enter credit card number') >> } >> >> >> class Demo(Frame): >> def __init__(self, parent=None): >> Frame.__init__(self, parent) >> self.pack() >> Label(self, text="Basic demos").pack() >> for (key, value) in demos.items(): >> func = (lambda key=key: self.printit(key)) >> Button(self, text=key, command=func).pack(side=TOP, >> fill=BOTH) >> def printit(self, name): >> print name, 'returns =>', demos[name]() >> >> >> I have tried but cant get it to work properly. >> I want to instead printit method to put __call__ and call it like that >> Can someone help me, please? > > The code you have should work. My guess is that you don't understand > lambda and so you want to do it a "different" way, using a "callable"? > Well, that's what lambda does, it makes a callable object: > > > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> key = 1 > py> callable(lambda key=key: self.printit(key)) > True > py> '__call__' in dir(lambda key=key: self.printit(key)) > True > > > > So the code you have already does what you want to do. Maybe understand > what you are studying before you reinvent the wheel--you will save > yourself a lot of frustration. > > James I understand lambda, and I know that code is working. But want to do for exercise with __call__. This coed is from programming python 2ed boo From a.schmolck at gmail.com Mon Feb 5 10:55:18 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 15:55:18 +0000 Subject: in place-ness of list.append References: Message-ID: skip at pobox.com writes: > >>>>> "Bart" == Bart Van Loon writes: > > >> Such an operation will be O(N**2), > > Bart> why is that? > > The a[:] operation makes a copy of a (as will the x = a + [n] idiom). I'm pretty confident append itself (and a+[n]) are linear in N=len(a) since the copying is linear and appending a single item in-place is constant time (OTOH calling append N times to construct a list or tree of length N from scratch is quadratic; I assume that is what you meant and also what the OP seems to want to use it for, so not doing it this way is sound advice). > Bart> I am building a binary tree where each node is a list. the two > Bart> children are the parent list + 1 and the parent list + 2. > > You might consider creating each node as > > left = [parent, 1] > right = [parent, 2] Or, if you don't need to mutate the tree ``left = (parent, 1)``. Tuples ought to have a little less memory overhead. 'as From tleeuwenburg at gmail.com Thu Feb 8 21:27:06 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 8 Feb 2007 18:27:06 -0800 Subject: Python Papers second issue now available! Message-ID: <1170988026.204547.97250@m58g2000cwm.googlegroups.com> G'day Pythonistas! Welcome to Issue Two of The Python Papers. It has been an exciting time and we are pleased to have reached this milestone. I'd like to say a big hello to all the people who have provided their input in making this a reality: the python-advocacy list, comp.lang.python, the Python User Groups that responded to the call to participate and also many individuals. This is also the first issue where we have attempted to publish both a PDF and an HTML edition. Please note the new volume number commences with the calendar year, so the volume number has increased while the issue number is the same as the last issue. The choice of format was clearly an issue for many people on both sides. Going forward, we will continue to use PDF as our primary 'authorative' version for the purposes of page numbering and referencing, however the HTML edition will be made public in a day or two after further editing to cope with conversion effects. Table of Contents: Editorial | Page 1 Python 411 Interview | Page 2 Coding Idioms pt 2 -- Design Patterns | Page 5 Python User Group Highlights | Page 7 Firebird Database Backup by Serialized Database Table Dump | Page 10 Python Events | P15 Cheers, -Tennessee Leeuwenburg (Editor-In-Chief) From gnewsg at gmail.com Thu Feb 1 14:18:33 2007 From: gnewsg at gmail.com (billie) Date: 1 Feb 2007 11:18:33 -0800 Subject: asyncore DoS vulnerability Message-ID: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> Hi all. I've just terminated a server application using asyncore / asynchat frameworks. I wrote a test script that performs a lot of connections to the server app and I discovered that asyncore (or better, select()) can manage only a limited number of file descriptors (aka simultaneous connections). When this number is reached select() raises an error but asyncore doesn't handle this exception (a crash occurs). If you want to try this I pasted two scripts below: a server and a client. On my Windows XP system server.py the crash occurs when 512 simultaneous connections are reached. Here's the traceback: Traceback (most recent call last): File "C:\Documents and Settings\root\Desktop\test.py", line 31, in ? asyncore.loop(timeout=1) File "C:\Python24\lib\asyncore.py", line 192, in loop poll_fun(timeout, map) File "C:\Python24\lib\asyncore.py", line 122, in poll r, w, e = select.select(r, w, e, timeout) ValueError: too many file descriptors in select() Why does this exception isn't handled inside asyncore.py? ---------------------------------------------------- # server.py import asyncore, socket class server(asyncore.dispatcher): """The base class for the backend.""" def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind(('', 8080)) self.listen(5) def handle_accept(self): sock_obj, addr = self.accept() handler(sock_obj) class handler(asyncore.dispatcher): def __init__(self, sock_obj): asyncore.dispatcher.__init__(self, sock=sock_obj) def handle_write(self): pass def handle_read(self): pass server() asyncore.loop(timeout=1) ----------------------------------------------------- # client.py import socket, threading, os def client(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(("127.0.0.1", 8080)) except: print x os._exit(0) while 1: s.recv(1024) x = 0 while 1: x +=1 threading.Thread(target=client).start() print x From paddy3118 at googlemail.com Mon Feb 26 03:20:14 2007 From: paddy3118 at googlemail.com (Paddy) Date: 26 Feb 2007 00:20:14 -0800 Subject: Nested Parameter Definitions In-Reply-To: References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> Message-ID: <1172478014.454785.319940@8g2000cwh.googlegroups.com> On Feb 25, 11:41 pm, Dennis Lee Bieber wrote: > Just looks like an extension of the normal tuple unpacking feature > of the language. > Yep, it looks like good Python to me too. Maybe the tutorial could be extended to cover this form of parameter too? It would be good if Brett Cannon could add some comments on why he asked for a show of hands on the features use? I'd hate for the feature to be removed because it is not often used, when the reason it is not often used is because it is hard to find examples of its use, because its buried in the language reference manual. Do any Python books mention nested parameters? - Paddy. From __peter__ at web.de Tue Feb 27 05:05:35 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Feb 2007 11:05:35 +0100 Subject: Interactive os.environ vs. os.environ in script References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> <1172562212.691747.150310@m58g2000cwm.googlegroups.com> <1172566324.278334.284760@s48g2000cws.googlegroups.com> <1172569620.033838.315920@p10g2000cwp.googlegroups.com> Message-ID: boris.smirnov at gmail.com wrote: > Probably I understood it not correctly. What did you mean was to put > that code into my python script "shrink_bs_070226.py" and then calls > script itself? Yes. > So I took my script "shrink_bs_070226.py" and it starts with: > ********************************** > #!/usr/bin/env python > import sys, re, glob, shutil > import os > > then I put your code in that script > > if os.environ["LD_LIBRARY_PATH"].count('/path/Linux/rh_linux') !=1: > os.environ["LD_LIBRARY_PATH"]=os.environ["LD_LIBRARY_PATH"]+':'+'/ > path/Linux/rh_linux' > os.system("shrink_bs_070226.py") > raise SystemExit > > and here continues my script: > > from qt import * > > ..... > *********************** > > Is it correct? Yes. > BTW: On lines 3:18 I have comments, script description and > modifications, therefore is "from qt import *" on the line 29 The problem must be something else, then. Peter From steve at REMOVE.THIS.cybersource.com.au Mon Feb 19 07:47:05 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 19 Feb 2007 23:47:05 +1100 Subject: How do I create an array of functions? References: <1171872999.751809.256880@p10g2000cwp.googlegroups.com> Message-ID: On Mon, 19 Feb 2007 00:16:39 -0800, Rob Wolfe wrote: > > Steven W. Orr wrote: >> I have a table of integers and each time I look up a value from the table >> I want to call a function using the table entry as an index into an array >> whose values are the different functions. I haven't seen anything on how >> to do this in python. > > Do you mean something like that? > > # test.py > > def fun1(): return "fun1" > def fun2(): return "fun2" > def fun3(): return "fun3" > > # list of functions > dsp = [f for fname, f in sorted(globals().items()) if callable(f)] Hmmm... when I try that, I get dozens of other functions, not just fun1, fun2 and fun3. And not just functions either; I also get classes. Does Python have a function that will read my mind and only return the objects I'm thinking of? -- Steven. From alan.franzoni_invalid at geemail.invalid Wed Feb 28 11:27:03 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 28 Feb 2007 17:27:03 +0100 Subject: Eric on XP for Newbie References: <1172679222.026525.248430@a75g2000cwd.googlegroups.com> Message-ID: <1d9au31u0gabx$.bmnr6jzorw6m.dlg@40tude.net> Il 28 Feb 2007 08:13:42 -0800, jeffwatkins2000 at gmail.com ha scritto: [cut] Forget the tars. http://www.quadgames.com/download/pythonqt/ Get the two EXEs here. BTW, I don't think Eric3 is a really good IDE on Windows (yet). Try something like SPE, or Scite, or any other editor like UltraEdit32. N.B: you need first to install python, then pyqtgpl, then eric. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From inq1ltd at verizon.net Sun Feb 18 16:09:23 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Sun, 18 Feb 2007 16:09:23 -0500 Subject: window opens with os.system() In-Reply-To: References: <1171757251.224765.171800@s48g2000cws.googlegroups.com> Message-ID: <200702181609.23862.inq1ltd@verizon.net> python help, I'm testing on xpPro I have a simple module that sends text files to a printer. Then, it moves the file to the 'Fprtd' directory. The module contains the following code; ##### for n in PrtList: os.system('type '+n+ ' > prn' os.system('move '+n+ ' Fprtd') ##### os.system opens and closes a window for each file it sends to the printer and again for each time it moves a file to the Fprtd directory. If there were only a few files, this wouldn't be so bad. But, when the files number 300 to 400 it becomes objectionable. Is there any way to supress the flashing window. xp no longer allows the 'ctty' command. jim-on-linux From fccoelho at gmail.com Thu Feb 22 08:02:36 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 05:02:36 -0800 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? In-Reply-To: <1172144943.794384.73270@s48g2000cws.googlegroups.com> References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> Message-ID: <1172149355.710034.224770@v45g2000cwv.googlegroups.com> On Feb 22, 9:49 am, open... at ukr.net wrote: > I don't know to which forum should I post the message > I hope someone related to the Python kernel development will read & > consider the idea > I'm (a former? meanwhile not sure) MATLAB user & it's very annoing > typing each time for example > while i: > print i > ... > instead of > while i > print i > ... > of course if all is written in a single line ':' I guess should not be > omited > > Thank you for you suggestions. > Sorry my bad English. > > WBR, Dmitrey Think on the bright side: you have to type ":" at the beginning of loop and conditional blocks, but you don't have to type "end" at the end... you are still saving two strokes... ;-)) From bearophileHUGS at lycos.com Mon Feb 26 18:44:20 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Feb 2007 15:44:20 -0800 Subject: Preallocate? -- potentially brain dead question about performance In-Reply-To: <45e368ea$1@griseus.its.uu.se> References: <45e368ea$1@griseus.its.uu.se> Message-ID: <1172533460.309061.255590@h3g2000cwc.googlegroups.com> Jan Danielsson: > newlist = [ None ] * len(mylist) > for i in range(len(mylist)): > newlist.append(int(e[0])) Note that this appends after the Nones, not over them. And note that here the name 'e' is undefined. The most used idiom for that is: newlist = [int(e[0]) for e in mylist] Or better lazily if you want to create a set, avoiding the list creation: newlist = set(int(e[0]) for e in mylist) Bye, bearophile From alan.franzoni_invalid at geemail.invalid Thu Feb 1 18:12:45 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Fri, 2 Feb 2007 00:12:45 +0100 Subject: Ubunu - Linux - Unicode - encoding References: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> <1m4tymklxmhra.1lcm42759ok57.dlg@40tude.net> <39h4s2h1eck0agttvgl95ntp3oj5smrt0k@4ax.com> Message-ID: Il Thu, 01 Feb 2007 20:57:53 +0100, Franz Steinh?usler ha scritto: > If I copy files with german umlauts (??? and strong 's' ?), these > filenames are not copied properly, and that characters are replaces > by little square symbols. Yes... I, myself, am italian, and I found no problem in using accented letter (?????). Since you say there's a problem as well in Nautilus and other Ubuntu software, I suppose there's something wrong with your linux setup, not with Python. Or, at least: you should try solving that problem first, then check what happens with python. Try appending this options in your fstab as hda1 mount options: iocharset=iso8859-15 unmount & remount and check what does happen. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From petercable at gmail.com Wed Feb 7 02:13:30 2007 From: petercable at gmail.com (petercable at gmail.com) Date: 6 Feb 2007 23:13:30 -0800 Subject: Running long script in the background In-Reply-To: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> Message-ID: <1170832410.532362.90160@p10g2000cwp.googlegroups.com> On Feb 6, 5:26 am, "watter... at gmail.com" wrote: > Hello, > > I am trying to write a python cgi that calls a script over ssh, the > problem is the script takes a very long time to execute so Apache > makes the CGI time out and I never see any output. The script is set > to print a progress report to stdout every 3 seconds but I never see > any output until the child process is killed. > > > Does anybody know a way to make output show in real time? Try this: # test.py import os import sys import time def command(): for x in range(5): print x sys.stdout.flush() time.sleep(1) def main(): command = 'python -c "import test; test.command()"' print 'running: %s' % command output = os.popen(command, 'r', 1) while True: line = output.readline() if line == '': break sys.stdout.write(line) sys.stdout.flush() if __name__ == '__main__': main() The problem is with using the file-like object returned by popen as an iterator. It will block until the child process is killed, so just iterate across it manually. Pete From NikitaTheSpider at gmail.com Tue Feb 27 12:41:24 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Tue, 27 Feb 2007 12:41:24 -0500 Subject: HTML to dictionary References: Message-ID: In article , Tina I wrote: > Hi everyone, > > I have a small, probably trivial even, problem. I have the following HTML: > > > > METAR: > > > > ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 NOSIG > >
> > > > short-TAF: > > > > ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040 > >
> > > > long-TAF: > > > > ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 SNRA VV010 BECMG > > 2124 15012KT > >
> > I need to make this into a dictionary like this: > > dictionary = {"METAR:" : "ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 > NOSIG" , "short-TAF:" : "ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040" > , "long-Taf:" : "ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 > SNRA VV010 BECMG 2124 15012KT"} Tina, In addition to Beautiful Soup which others have mentioned, Connelly Barnes' HTMLData module will take (X)HTML and convert it into a dictionary for you: http://oregonstate.edu/~barnesc/htmldata/ THe dictionary won't have the exact format you want, but I think it would be fairly easy for you to convert to what you're looking for. I use HTMLData a lot. Beautiful Soup is great for parsing iteratively, but if I just want to throw some HTML at a function and get data back, HTMLData is my tool of choice. Good luck with whatever you choose -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From mail at timgolden.me.uk Wed Feb 14 08:30:42 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 14 Feb 2007 13:30:42 +0000 Subject: WindowsNT user authentication In-Reply-To: <45D30C5D.7040207@timgolden.me.uk> References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> <1171294708.261232.18290@p10g2000cwp.googlegroups.com> <1171357845.968797.229580@m58g2000cwm.googlegroups.com> <1171458314.065280.164360@v33g2000cwv.googlegroups.com> <45D30C5D.7040207@timgolden.me.uk> Message-ID: <45D30F02.8050002@timgolden.me.uk> Tim Golden wrote: > billie wrote: >> Another question, I'm sorry. >> Do you got any idea about how to get permissions of a file/directory >> given the username? >> For example: I would like to know if C:\my_file.ext is readable/ >> writable by user 'x' or not. > > This is an unfortunately messy question. I'm sorry; that probably came out wrong. What I meant was that, although the question was perfectly intelligible, the answer is going to be more complex than you probably expected ;) TJG From http Fri Feb 16 19:06:42 2007 From: http (Paul Rubin) Date: 16 Feb 2007 16:06:42 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> <7xfy956gq8.fsf@ruckus.brouhaha.com> Message-ID: <7xk5yhbqb1.fsf@ruckus.brouhaha.com> Donn Cave writes: > What this proves is that you can implement > an argument list at run time, but it by no means changes the > nature of the argument list as a sequence. Right, it's treated as a sequence rather than a record structure. So is that consistent with the "tuples are record structures" view, as opposed to the "tuples are immutable lists" view? From skip at pobox.com Sun Feb 25 07:13:12 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 25 Feb 2007 06:13:12 -0600 Subject: Python 3.0 unfit for serious work? In-Reply-To: <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> Message-ID: <17889.32088.818717.794524@montanaro.dyndns.org> Jeff> My post was entitled "Python 3.0 unfit for serious work", you just Jeff> indicated that the Linux distros will agree with me, in order to Jeff> be taken seriously, the distros will have to include 2.x python Jeff> for a very long time. If 3.0 and 2.x have any serious degree of Jeff> incompatibility, python will be a favorite subject for religious Jeff> rants and heated arguments for many people. The notion that Python 3.0 was going to fix design/implementation issues in earlier versions of Python and thus cause some breakage has been known for a long time, at least since Guido's UK Python talk in March 2003. Python 2.x released will continue to be created for some time after Python 3.0 is released. From PEP-3000: I expect that there will be parallel Python 2.x and 3.x releases for some time; the Python 2.x releases will continue for a longer time than the traditional 2.x.y bugfix releases. Typically, we stop releasing bugfix versions for 2.x once version 2.(x+1) has been released. But I expect there to be at least one or two new 2.x releases even after 3.0 (final) has been released, probably well into 3.1 or 3.2. This will to some extend depend on community demand for continued 2.x support, acceptance and stability of 3.0, and volunteer stamina. The whole intention is to give authors a long period of time to port to Python 3.x. I believe your fear is just a knee jerk reaction to the notion that there will be some stated incompatibilities between 2.x and 3.x without having done any investigation of the transition process. Nobody is forcing you to do anything right now or completely abandon your code base. Python 2.x still has a long shelf life. Hell, 3.0a1 isn't even out yet. If you hang on for a few days I'm sure Guido's keynote about Python 3 from the PyCon just wrapping up in Dallas will be available online. There might be something in there of interest to you. If you poke around a bit you will probably find nearly live blogs from the conference as well. Skip From rschroev_nospam_ml at fastmail.fm Sat Feb 3 17:41:31 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 03 Feb 2007 22:41:31 GMT Subject: confused about resizing array in Python In-Reply-To: References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: Ruan schreef: > "Roel Schroeven" wrote: >> Ruan schreef: >>> My confusion comes from the following piece of code: >>> >>> memo = {1:1, 2:1} >>> def fib_memo(n): >>> global memo >>> if not n in memo: >>> memo[n] = fib_memo(n-1) + fib_memo(n-2) >>> return memo[n] >>> >>> I used to think that the time complexity for this code is O(n) due to >>> its use of memoization. >>> >>> However, I was told recently that in Python, dictionary is a special >>> kind of array and to append new element to it or to resize it, it is in fact >>> internally inplemented by creating another array and copying the old one to >>> it and append a new one. >> That's not correct. Python dictionaries are highly optimized and I >> believe the time complexity is amortized constant (i.e. O(1)) for both >> insertions and lookups. > Then how about Python's list? > > What is done exactly when list.append is executed? > > For list, is there another larger list initialized and the contents from the > old list is copied to it together with the new appended list? I'm not sure, but I think each time the list needs to grow, it doubles in size. That leaves room to add a number of elements before the allocated space needs to grow again. It's a frequently used approach, since it is quite efficient and the memory needed is never double the amount of memory strictly needed for the elements of the list. You can always study the source code for all gory details of course. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mail at microcorp.co.za Sat Feb 17 04:54:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 17 Feb 2007 11:54:31 +0200 Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com><1171592265.316602.234820@s48g2000cws.googlegroups.com><1171612923.145381.220960@p10g2000cwp.googlegroups.com> <7xd54a6jof.fsf@ruckus.brouhaha.com> Message-ID: <026b01c7527c$bfb549e0$03000080@hendrik> "Paul Rubin" wrote: > Steven Bethard writes: > > Yes, a lot of people liked this approach, but it was rejected due to > > gratuitous breakage. While Python 3.0 is not afraid to break backwards > > compatibility, it tries to do so only when there's a very substantial > > advantage. I guess enough people felt that having a shortcut for set() > > was less important than keeping the current spelling of dict() the same. > > There's even a sentiment in some pythonistas to get rid of the [] and {} > notations for lists and dicts, using list((1,2,3)) and dict((1,2),(3,4)) > for [1,2,3] and {1:2, 3:4} respectively. YUK! Moving in the wrong direction to bracketmania! If you are going to use only one kind of brackets, use [] - on most keyboards, you don't have to press the shift key - think of the numberless hours of total time saved by this simple reform... It will also give Python a very distinctive "look" - unlike any other language. - Hendrik From gagsl-py at yahoo.com.ar Mon Feb 5 18:46:10 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:46:10 -0300 Subject: wave References: Message-ID: En Sat, 03 Feb 2007 17:00:39 -0300, Silver Rock escribi?: > supose i?ve opened a sound with the wave module: > >>>> import wave >>>> sound=wave.open(filename,'rb') > > now this is strange: > >>>> sound.getnframes() != len(sound.readframes(sound.getnframes()) > True > > Why so? readframes returns the bytes read, as a string, not a list of frames. (It's not like "readlines") -- Gabriel Genellina From deets at nospam.web.de Sun Feb 25 17:10:47 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 Feb 2007 23:10:47 +0100 Subject: convert strings to utf-8 In-Reply-To: References: <54doljF20aq9hU1@mid.uni-berlin.de> Message-ID: <54efruF20lajvU1@mid.uni-berlin.de> Niclas schrieb: > Thank you! > > solved it with this: > unicode( data.decode('latin_1') ) The unicode around this is superfluous. Either do unicode(bytestring, encoding) or bytestring.decode(encoding) > and when I write it to the file... > f = codecs.open(path, encoding='utf-8', mode='w+') > f.write(self.__rssDoc.toxml()) Looks good, yes. Diez From ptmcg at austin.rr.com Wed Feb 14 09:26:41 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 Feb 2007 06:26:41 -0800 Subject: How to print the variable? In-Reply-To: References: <345345.69488.qm@web39715.mail.mud.yahoo.com> Message-ID: <1171463201.760331.150160@l53g2000cwa.googlegroups.com> On Feb 14, 8:00 am, Jean-Paul Calderone wrote: > On Wed, 14 Feb 2007 05:47:31 -0800 (PST), Hans Schwaebli wrote: > >Hi, > > > am am a Python beginner with Java knowledge background. Infact I need to use Jython. > > > My first beginner question is how to determine of what type a variable is? > > > In program which supports Jython there is a variable called "rc" available. I can use the methods on that variable like rc.logMessage("hello"). But if I try to execute "print "${rc}" it tells me "Invalid variable syntax for attribute 'code' with value 'print "${rc}".' > > print rc > print dir(rc) > print type(rc) > help(rc) > > http://python.org/doc/tut/ > > Jean-Paul print "The variable rc has the value %s" % rc print "The variable rc has the value %(rc)s" % locals() -- Paul From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 15:18:49 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 21:18:49 +0100 Subject: Calling J from Python In-Reply-To: <1170692852.549730.81030@v33g2000cwv.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: <45c78a18$0$29725$426a74cc@news.free.fr> Gosi a ?crit : > On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: > >>Gosi wrote: >> >>>It is quite easy to call J from Python >> >>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... >> >>What is J, and why should we care? >> >>Diez > > > J is in many ways similar to Python. > > J has very many advanced operations. > > http://www.jsoftware.com/ > """ Our policy on source for our binaries is between the extremes of Microsoft proprietary source and Linux open source. You can have the benefits of open source for J binaries, but under a license and a fee. """ Good bye J. From bg_ie at yahoo.com Mon Feb 19 03:57:20 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 19 Feb 2007 00:57:20 -0800 Subject: Building Python Pagage for Newer Python Version Message-ID: <1171875440.938807.165340@l53g2000cwa.googlegroups.com> Hi, I have just downloaded the source for PyXML-0.8.4, which I would like to build for Python 2.5. How exactly do I go about doing this? Thanks for your help, Barry. From johnjsal at NOSPAMgmail.com Thu Feb 1 14:35:05 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Feb 2007 14:35:05 -0500 Subject: Sorting a list Message-ID: <45c240cf$0$10895$c3e8da3@news.astraweb.com> Hi everyone. If I have a list of tuples, and each tuple is in the form: (year, text) as in ('1995', 'This is a citation.') How can I sort the list so that they are in chronological order based on the year? Is there a better way to do this than making a list of tuples? (So far I have a text file and on each line is a citation. I use an RE to search for the year, then put this year and the entire citation in a tuple, and add this tuple to a list. Perhaps this step can be changed to be more efficient when I then need to sort them by date and write a new file with the citations in order.) Thanks. From edreamleo at charter.net Thu Feb 15 16:13:20 2007 From: edreamleo at charter.net (Edward K Ream) Date: Thu, 15 Feb 2007 15:13:20 -0600 Subject: Pep 3105: the end of print? Message-ID: The pros and cons of making 'print' a function in Python 3.x are well discussed at: http://mail.python.org/pipermail/python-dev/2005-September/056154.html Alas, it appears that the effect of this pep would be to make it impossible to use the name 'print' in a backward compatible manner. Indeed, if a program is to compile in both Python 2.x and Python 3.x, the print function (or the print statement with parentheses) can not use the 'sep', 'end' and 'file' keywords. This in turn makes it impossible to support the effect of print with trailing comma in Python 2.x programs while retaining the name 'print'. The only workaround would be to define yet another function, with a name *other* than 'print'. This function, say print2, can support whatever features the implementer wants because it does not collide with the Python 2.x print statement. In short, pep 3105 will *discourage* rather than encourage the use of the name 'print'. Rather than invalidating most Python 2.x programs, it would seem more graceful for Python 3.x to define a [your name here] function that can be used in addition to, rather than to the exclusion of, print. Edward P.S. The existence of an automated translation script does not change the situation described above in any way. At best, such a script could change print statements to [your name here] functions, but the effect would still be the elimination of the name 'print' in all programs that aim to support Python 2.x and Python 3.x. EKR -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From kavithapython at yahoo.co.in Thu Feb 15 10:19:43 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Thu, 15 Feb 2007 15:19:43 +0000 (GMT) Subject: list of strings-newline Message-ID: <875421.30543.qm@web7802.mail.in.yahoo.com> Hi i have a list as follows list="a1,b1,c1,d1,a2,b2,c2,d2,a3,b3,c3,d3, I would like to print as a1,b1,c1,d1, a2,b2,c2,d2, a3,b3,c3,d3, and then i would like to delete the comma at the end,,say like,, a1,b1,c1,d1 a2,b2,c2,d2 a3,b3,c3,d3 (its always after the length is 4 i would like to write as the next line) if any one has any suggestions pls write to me,, --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From jonc at icicled.net Thu Feb 1 15:17:27 2007 From: jonc at icicled.net (Jonathan Curran) Date: Thu, 1 Feb 2007 14:17:27 -0600 Subject: xml.dom.minidom memory usage In-Reply-To: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> References: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> Message-ID: <200702011417.27863.jonc@icicled.net> Dan, I jumped the gun and didn't read your entire post. I ended up skipping a lot of parts, especially where you say that you are creating a document (for some reason I thought you were reading it). I looked at the setAttribute function and thought: ah he's writing it out. Sorry about all that. I'd still ask you to look into SAX though :) Especially when dealing with really large XML documents, whether it be reading or writing them. - Jonathan Curran From rkmr.em at gmail.com Wed Feb 21 20:08:01 2007 From: rkmr.em at gmail.com (mark) Date: Wed, 21 Feb 2007 17:08:01 -0800 Subject: getting a thread out of sleep In-Reply-To: <1172103051.070952.182060@q2g2000cwa.googlegroups.com> References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> <1172098070.913952.20730@h3g2000cwc.googlegroups.com> <1172103051.070952.182060@q2g2000cwa.googlegroups.com> Message-ID: On 21 Feb 2007 16:10:51 -0800, placid wrote: > On Feb 22, 10:20 am, mark wrote: > > On 21 Feb 2007 14:47:50 -0800, placid wrote: > > > > > > > > > On Feb 22, 3:23 am, mark wrote: > > > > On 20 Feb 2007 21:26:18 -0800, placid wrote: > > > > > > > On Feb 21, 4:21 pm, "placid" wrote: > > > > > > On Feb 21, 4:12 pm, mark wrote: > > > > > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > > > > > On Feb 21, 3:08 pm, mark wrote: > > > > > > > > > Right now I have a thread that sleeps for sometime and check if an > > > > > > > > > event has happened and go back to sleep. Now instead I want the thread > > > > > > > > > to sleep until the event has occured process the event and go back to sleep > > > > > > > > > > > class eventhndler(threading.Thread): > > > > > > > > > def __init__(self): > > > > > > > > > threading.Thread.__init__(self) > > > > > > > > > def run(self): > > > > > > > > > while True: > > > > > > > > > time.sleep(SLEEPTIME) > > > > > > > > > ''''do event stuff''' > > > > > > > > > > The way i would do this is by using an threading.Event ( > > > > > > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > > > > > > > > > > > > > class eventhandler(threading.Thread): > > > > > > > > def __init__(self): > > > > > > > > threading.Thread.__init__(self) > > > > > > > > self.event = threading.Event() > > > > > > > > def run: > > > > > > > > while True: > > > > > > > > # block until some event happens > > > > > > > > self.event.wait() > > > > > > > > """ do stuff here """ > > > > > > > > self.event.clear() > > > > > > > > > > > > > > > > > > the way to use this is to get the main/separate thread to set() the > > > > > > > > event object. > > > > > > > > > Can you give an example of how to get the main threead to set teh event object? > > > > > > > this is exactly what i wanted to do! > > > > > > > thanks a lot! > > > > > > > mark> > > > > > oops I've miss-typed the thread variable name the following should > > > > > work > > > > > > > > > > > > if __name__ == "__main__": > > > > > evtHandlerThread = eventhandler() > > > > > evtHandlerThread.start() > > > > > > > # do something here # > > > > > evtHandlerThread.event.set() > > > > > > > # do more stuff here # > > > > > evtHandlerThread.event.set() > > > > > > > > > > > > > Can I have the same thread process two or more events? Can you tell > > > > how to do this? The code you gave is waiting on one event right. How > > > > can I do it for more events? > > > > thanks a lot! > > > > mark > > > > > I don't think a thread can block on more than one event at a time. But > > > you can make it block on more then one event one at a time. > > > > > > > > > > class eventhandler(threading.Thread): > > > def __init__(self): > > > threading.Thread.__init__(self) > > > self.events = [threading.Event(), threading.Event()] > > > self.currentEvent = None > > > def run: > > > while True: > > > for event in self.events: > > > self.currentEvent = event > > > # block until some event happens > > > self.currentEvent.wait() > > > """ do stuff here """ > > > self.currentEvent.clear() > > > > > if __name__ == "__main__": > > > evtHandlerThread = eventhandler() > > > evtHandlerThread.start() > > > > > # do something here # > > > evtHandlerThread.currentEvent.set() > > > > > # do more stuff here # > > > evtHandlerThread.currentEvent.set() > > > > > > > > > > what the thread does is sequentially waits for two events to happen > > > and then execute the same code. You could change this code to perform > > > different functions for different event objects. > > > > Once the thread starts it is going to wait on the event that is the > > first element of the list right? This would mean : > > This is correct. > > > evtHandlerThread.currentEvent.set(): that I have only one event right? > > this means that the current event occurred. > > > Can you explain how I can have different event objects. I dont see how > > I can do different functinos for same event. > > > > Thanks a lot! > > > > mark > > To run different functions for the same event is easy, just write a > wrapper class around threading.event() and include some method that > you will run and assign this to different functions for each > EventWrapper. > > > > class EventWrapper(): > def __init__(self,work ): > self.event = threading.Event() > self.eventWork = work > > def wait(self): > self.event.wait() > > def clear(self) > self.event.clear() > > def eventWork(self): > print "no work" > > class eventhandler(threading.Thread): > def __init__(self, events = None): > threading.Thread.__init__(self) > self.events = events > self.currentEvent = None > def run: > while True: > if self.events: > for event in self.events: > self.currentEvent = event > # block until the current event happens > self.currentEvent.wait() > self.currentEvent.eventWork() > self.currentEvent.clear() > > def eventOneWork(): > # do some event 1 specific work here > > def eventTwoWork(): > # do some event 2 specific work here > > if __name__ == "__main__": > events = [EventWrapper(eventOneWork),EventWrapper(eventTwoWork)] > > evtHandlerThread = eventhandler(events) > evtHandlerThread.start() > > # do something here # > evtHandlerThread.currentEvent.set() > # do more stuff here # > evtHandlerThread.currentEvent.set() > > > > So you have a EventWrapper class that now contains the Event object > and a workEvent() method which is assigned to a function you create. > THanks a lot! Does this have to have event1 and event2 occur in sequence? Will this still work even if only event2 occurs and event1 never occurs? thanks mark From duncan.booth at invalid.invalid Sat Feb 10 08:34:41 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Feb 2007 13:34:41 GMT Subject: A little more advanced for loop References: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> <1171019473.527988.206610@l53g2000cwa.googlegroups.com> <45CCF734.3080306@websafe.com> Message-ID: Larry Bates wrote: > Note: if lists are long take a look at itertools izip. zip creates > a list of lists which could take lots of memory/time if they are VERY > large. itertools izip iterates over them in place. That's interesting. I was going to quibble with the assertion that zip could take lots of time, since on the face of it a loop using izip packs and unpacks just as many tuples. Fortunately I tried it out before claiming that zip would be just as fast :) It would appear that even for short sequences the izip solution is faster. My guess would be it is because the same tuple objects are being reused in the izip version. C:\Python25\Lib>timeit.py -s "a, b, c = [range(1000)]*3" -s "from itertools import izip" "for p,q,r in izip(a,b,c): pass" 10000 loops, best of 3: 131 usec per loop C:\Python25\Lib>timeit.py -s "a, b, c = [range(1000)]*3" "for p,q,r in zip(a,b,c): pass" 1000 loops, best of 3: 212 usec per loop C:\Python25\Lib>timeit.py -s "a, b, c = [range(100)]*3" -s "from itertools import izip" "for p,q,r in izip(a,b,c): pass" 100000 loops, best of 3: 13.9 usec per loop C:\Python25\Lib>timeit.py -s "a, b, c = [range(100)]*3" "for p,q,r in zip(a,b,c): pass" 10000 loops, best of 3: 22.6 usec per loop C:\Python25\Lib>timeit.py -s "a, b, c = [range(10)]*3" -s "from itertools import izip" "for p,q,r in izip(a,b,c): pass" 100000 loops, best of 3: 2.21 usec per loop C:\Python25\Lib>timeit.py -s "a, b, c = [range(10)]*3" "for p,q,r in zip(a,b,c): pass" 100000 loops, best of 3: 3.52 usec per loop From duncan.booth at invalid.invalid Tue Feb 6 03:26:44 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Feb 2007 08:26:44 GMT Subject: Count nb call of a function, without global var or decorator References: <45c75b0f$0$5090$ba4acef3@news.orange.fr> Message-ID: "M?ta-MCI" wrote: > Example, with meta-data (attributs of function) : > > def ff(this): > try: > this.count=this.count+1 > except: > this.count=1 > a=1 > b=2 > c=a+b > > ff(ff) > fa=ff > ff(ff) > fa(fa) > print ff.count > > > > How to improve that? If I've managed to guess what you are asking, you want to use a class: >>> class Ff: def __init__(self): self.count = 0 def __call__(self, notused): self.count += 1 a, b = 1, 2 c = a+b return c >>> ff = Ff() >>> fa = Ff() >>> ff(ff) 3 >>> ff.count 1 >>> fa.count 0 From bdesth.quelquechose at free.quelquepart.fr Tue Feb 6 17:10:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 23:10:23 +0100 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170795607.938431.144340@p10g2000cwp.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> <1170795607.938431.144340@p10g2000cwp.googlegroups.com> Message-ID: <45c8f5b5$0$19714$426a74cc@news.free.fr> jeremito a ?crit : > On Feb 6, 2:36 pm, Bruno Desthuilliers > wrote: > (snip) >>Here's an alternative implementation, so you get the idea. >> >>class Xs(dict): oops ! I meant: class Xs(object): of course... (snip) > I guess I just > need more experience. Possibly - but not only. You may want to have a look at the FineManual(tm) for all this kind of "magic", starting with : http://docs.python.org/ref/specialnames.html http://docs.python.org/ref/sequence-types.html HTH From paul at boddie.org.uk Mon Feb 5 13:15:12 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Feb 2007 10:15:12 -0800 Subject: Python does not play well with others In-Reply-To: <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> References: <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> Message-ID: <1170699312.374636.317570@q2g2000cwa.googlegroups.com> On 5 Feb, 18:52, John Nagle wrote: > > Pre-forking doesn't reduce load; it just improves responsiveness. > You still pay for loading all the modules on every request. For > many AJAX apps, the loading cost tends to dominate the transaction. According to the Apache prefork documentation, you can configure how often the child processes stick around... http://httpd.apache.org/docs/2.2/mod/mpm_common.html#maxrequestsperchild ...and I suppose mod_python retains its state in a child process as long as that process is running: "Once created, a subinterpreter will be reused for subsequent requests. It is never destroyed and exists until the Apache process dies." - http://www.modpython.org/live/current/doc-html/pyapi-interps.html "Depending on the use of various PythonInter* directives, a single python interpreter (and list of imported modules, and per-module global variables, etc) might be shared between multiple mod_python applications." - http://www.modpython.org/FAQ/faqw.py?req=show&file=faq03.005.htp The FAQ entry (3.1) about module reloading would appear to be pertinent here, too: http://www.modpython.org/FAQ/faqw.py?req=show&file=faq03.001.htp Paul From ptmcg at austin.rr.com Fri Feb 9 19:53:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 9 Feb 2007 16:53:27 -0800 Subject: resolve environment variables in string - regular expression In-Reply-To: <1171025240.340881.49130@a34g2000cwb.googlegroups.com> References: <1171020642.655125.164880@p10g2000cwp.googlegroups.com> <1171025240.340881.49130@a34g2000cwb.googlegroups.com> Message-ID: <1171068807.874491.30300@q2g2000cwa.googlegroups.com> On Feb 9, 6:47 am, "bruno.desthuilli... at gmail.com" wrote: > On 9 f?v, 12:30, "Kai Rosenthal" wrote: > > > Hello, > > > how can I resolve envionment variables in a string. > > e.g. > > > strVar = /myVar > > resolve in > > nothing. This raises a SyntaxError. Python is *not* a shell script > language. > > > str1 = /mytest02/$MYVAR/mytest02 --> /mytest02//myVar/mytest02 > > (unix) > > str2 =$MYVAR/mytest03 --> /myVar/mytest03 (unix) > > str3 =%MYVAR%/mytest03 --> /myVar/mytest03 (windows) > > I would not set the variables in this time. > > > I think I need a little regular expression code snippet, > > Nope. > > my_var = "/myVar" > str1 = "/mytest02/%s/mytest02" % my_var > str2 = "%(my_var)s/mytest03" % {'my_var': my_var} > import os > str3=os.path.join(my_var, "mytest03") > > hth Here's a pyparsing snippet to maybe do what you want. -- Paul from pyparsing import Word,alphas import os substitutionVar = Word("$",alphas+"_") substitutionVar.setParseAction( lambda t: os.getenv(t[0][1:],t[0]) ) envsub = lambda s : substitutionVar.transformString(s) test = "$TEMP/mytest03" print envsub(test) prints: C:\DOCUME~1\Paul\LOCALS~1\Temp/mytest03 From superspamcollector.bla at gmail.com Thu Feb 15 21:00:02 2007 From: superspamcollector.bla at gmail.com (a a) Date: Fri, 16 Feb 2007 02:00:02 +0000 Subject: spam magnet Message-ID: <5f06d9230702151800n7085c707l75b16b35764599aa@mail.gmail.com> Hello, I hear (from google) that people get a lot of spam after posting to this list. That's nice, because I, superspamcollector.bla at gmail.com , happen to want a lot of spam :) Anyone who would like to send me their spam is welcome to as well (full headers please, I'm trying to track & corellate those wascally bots :)) SuperSpamCollector superspamcollector.bla at gmail.com :D From Eric_Dexter at msn.com Fri Feb 2 20:02:28 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 2 Feb 2007 17:02:28 -0800 Subject: Is Python Right for Me? In-Reply-To: References: Message-ID: <1170464548.058540.248600@h3g2000cwc.googlegroups.com> On Feb 2, 2:26 pm, Mister Newbie wrote: > "Terry Reedy" wrote innews:mailman.3475.1170447779.32031.python-list at python.org: > > > > > > > > > "Mister Newbie" wrote in message > >news:Xns98CB9A2CC9C3Bn00b at 208.49.80.253... > >|I want to make small, 2D games. I have no programming experience. Is > > Python > >| a good choice? > > > Possibly. There is an add-on package called pygame that is, I > > believe, 2d oriented. Seewww.pygame.org > > There is also an associated mailing list, which you can also read via > > news.gmane.org as newsgroup gmane.comp.python.pygame. > > > tjr > > Thanks for the reply. I'll check it out.- Hide quoted text - > > - Show quoted text - It may be good to check out other packages even if it is more trouble. My laptop (windows) doesn't like pygame, and has some trouble with directpy (island won't show up in the demo). More info can be found about this trouble in the documentation for panda3d. I would also suggest that opengl isn't a good choice because of complexity of the install and updated version of the .dll that you end up with when you try to install gimp.. For 2d stuff it is all 2d array stuff so all you realy need is point and 2d arrays although that is better handeled by the ui.. From aahz at pythoncraft.com Sat Feb 10 16:07:50 2007 From: aahz at pythoncraft.com (Aahz) Date: 10 Feb 2007 13:07:50 -0800 Subject: A little more advanced for loop References: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> <1171019473.527988.206610@l53g2000cwa.googlegroups.com> <45CCF734.3080306@websafe.com> Message-ID: In article <45CCF734.3080306 at websafe.com>, Larry Bates wrote: > >Note: if lists are long take a look at itertools izip. zip creates >a list of lists which could take lots of memory/time if they are VERY >large. itertools izip iterates over them in place. That's half-true -- while izip is faster, it's not enough faster to make a significant difference unless the lists are "huge" rather than "large". Remember that the data elements themselves are not copied. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From bignose+hates-spam at benfinney.id.au Wed Feb 28 17:13:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Mar 2007 09:13:40 +1100 Subject: Extract String From Enclosing Tuple References: Message-ID: <87slcqvskr.fsf@benfinney.id.au> rshepard at nospam.appl-ecosys.com writes: > Data are assembled for writing to a database table. A > representative tuple looks like this: > > ('eco', "(u'Roads',)", 0.073969887301348305) You refer to the second item as "a tuple" later, but it's not; it's now just a string (not even a unicode string). Whatever has assembled these has effectively lost the structure of the data and you are now left with three items in a tuple: string, string, float. Some RDBMSs can store a structure of multiple values in one value; SQLite cannot. The usual solution for this limitation is to take these structural values and store the component values as separate rows of a different table, and have each of those rows refer back to the identifying key of the original table so they can be joined easily. E.g., I might conceptually think of order records as the following tuples, with further tuples-of-tuples for the items on each order: orders = ( # fields: id, cust_code, date, order_items (1, "cust1234", "2007-02-15", (("item002", 1), ("item005", 3), ("item007", 1))), (2, "cust4567", "2007-02-19", (("item001", 5), ("item005", 2))), ) Since I can't store those as-is in SQLite, I would need to restructure the tables: separate the "order items" to separate rows in a dedicated table, and refer to the "order" table key in each "order item" row. orders = ( # fields: id, cust_code, date (1, "cust1234", "2007-02-15"), (2, "cust4567", "2007-02-19"), ) order_items = ( # fields: id, order_id, item_code, quantity (1, 1, "item002", 1), (2, 1, "item005", 3), (3, 1, "item007", 1), (4, 2, "item001", 5), (5, 2, "item005", 2), ) Then you can use SQL JOIN clauses as necessary, with the order_item.order_id field a foreign key into the order table. -- \ "I moved into an all-electric house. I forgot and left the | `\ porch light on all day. When I got home the front door wouldn't | _o__) open." -- Steven Wright | Ben Finney From cbc at unc.edu Mon Feb 12 13:33:57 2007 From: cbc at unc.edu (Chris Calloway) Date: Mon, 12 Feb 2007 13:33:57 -0500 Subject: Zope 3 Boot Camp early bird registration deadline near Message-ID: <45d0b315$1_1@news.unc.edu> The early bird registration deadline for Camp 5 and the BBQ Sprint is Wednesday, February 14: http://trizpug.org/boot-camp/camp5/ You can save $50 by registering early. Registration ends Friday March 2. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From robert.kern at gmail.com Wed Feb 28 12:55:11 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 28 Feb 2007 11:55:11 -0600 Subject: f2py and Fortran90 gfortran_filename error In-Reply-To: <1172670915.478334.48510@j27g2000cwj.googlegroups.com> References: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> <1172670915.478334.48510@j27g2000cwj.googlegroups.com> Message-ID: Beliavsky wrote: > On Feb 28, 12:40 am, Robert Kern wrote: >> Tyler wrote: >>> Hello All: >>> Since my last post I have attempted to use the f2py program which >>> comes with numpy. >> It's better to ask these questions on numpy-discussion, instead. There are more >> f2py users per capita there. >> >> http://www.scipy.org/Mailing_Lists > > I wish the Google Groups interface to the list http://groups.google.com/group/Numpy-discussion > worked. When I use it to post my messages bounce, but messages from > the list do show up on Google Groups. The "bounces" say > > "This mailing list is now defunct. Please use > numpy-discussion at scipy.org to discuss NumPy, Numeric, and numarray. > > http://projects.scipy.org/mailman/listinfo/numpy-discussion" > > Yes, I know I could follow these instructions, but I prefer to use > Google Groups. Well, you'll have to find out who set up that interface or whoever at Google is in charge of maintaining such gatewayed groups to let them know that the mailing list has migrated. I used the "Send email to the owner" link, but I have no idea who that is supposed to go to. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From JStoneGT at aol.com Fri Feb 16 03:27:46 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Fri, 16 Feb 2007 03:27:46 EST Subject: I'm faint why this can't work Message-ID: > Hello, > I got this similar sample script from books: > $ cat sampdict.py > #!/usr/bin/python > class SampDict(dict): > def __init__(self, filename=None): > self["name"] = filename > Are you sure you copied it exactly as it appears? Where did you find it? Thank you for the help,Gabriel. The codes got by me from the book of "Dive into Python".The original codes are below: class FileInfo(dict): "store file metadata" def __init__(self, filename=None): self["name"] = filename It's in the chapter 5.5. -------------- next part -------------- An HTML attachment was scrubbed... URL: From B.Ogryczak at gmail.com Tue Feb 27 11:27:14 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 27 Feb 2007 08:27:14 -0800 Subject: Help on object scope? In-Reply-To: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> Message-ID: <1172593634.531758.174060@h3g2000cwc.googlegroups.com> On Feb 25, 10:25 pm, bmar... at hotmail.com wrote: > Hello everybody, > > I have a (hopefully) simple question about scoping in python. I have a > program written as a package, with two files of interest. The two > files are /p.py and /lib/q.py > > My file p.py looks like this: > > --- > > from lib import q > > def main(): > global r > r = q.object1() > s = q.object2() > > if __name__ == "__main__": > main() > > --- > > My file q.py in the subdirectory lib looks like this: > > class object1: > t = 3 > > class object2: > print r.t "Globals" are only global within the module they are defined in. Change "global r" to "import __main__; __main__.r = r", and in q.py add "from __main__ import r". From mfmdevine at gmail.com Wed Feb 14 09:09:51 2007 From: mfmdevine at gmail.com (amadain) Date: 14 Feb 2007 06:09:51 -0800 Subject: replacing substrings within strings In-Reply-To: <1171461100.321811.96180@h3g2000cwc.googlegroups.com> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> <53gcsbF1sbe8oU1@mid.uni-berlin.de> <1171456059.848396.42270@m58g2000cwm.googlegroups.com> <53ghdgF1slkirU1@mid.uni-berlin.de> <1171461100.321811.96180@h3g2000cwc.googlegroups.com> Message-ID: <1171462191.228653.152240@k78g2000cwa.googlegroups.com> Thanks all. I usually turn strings into arrays for processing. I was looking to see if that was the best way to do it from others that use python. No one else uses python in my company so its nice to get different points of view from other python users from lists like this. A From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 16:54:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 22:54:20 +0100 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> <52pc34F1oqe5fU1@mid.individual.net> Message-ID: <45c7a075$0$1029$426a34cc@news.free.fr> Alexander Schmolck a ?crit : > Bjoern Schliessmann writes: > > >>Alexander Schmolck wrote: >> >> >>>Apart from being less to type >> >>Cool. Less to type. > > > Yes. Readability is more important in many context, but for something designed > for interactive experimentation and exploration little typing is absolutely > essential. Would you use a calculator that would require Java-style > boilerplate to add two numbers? No, thanks. But hopefully we have Python : Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 3 + 4 7 >>> !-) From incarniac at gmail.com Sun Feb 4 07:28:11 2007 From: incarniac at gmail.com (Inca) Date: 4 Feb 2007 04:28:11 -0800 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Message-ID: <1170592091.240194.174070@a34g2000cwb.googlegroups.com> > Through "My computer" | properties | advanced | Environment Variables" > you have to reboot. The best overall solution is the one where you modify sys.path to add your own custom paths, however Jussi is right in that you do not need to reboot. You have to restart any applications that relies on using the updated environment variables (in your case the Delphi program): http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/environment_variables.mspx?mfr=true From h at realh.co.uk Sat Feb 3 14:46:20 2007 From: h at realh.co.uk (Tony Houghton) Date: Sat, 3 Feb 2007 19:46:20 +0000 (UTC) Subject: Determining encoding of a file Message-ID: In Linux it's possible for filesystems to have a different encoding from the system's setting. Given a filename, is there a (preferably) portable way to determine its encoding? -- TH * http://www.realh.co.uk From bignose+hates-spam at benfinney.id.au Tue Feb 27 20:04:22 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 12:04:22 +1100 Subject: Tuples from List References: Message-ID: <87tzx7xfc9.fsf@benfinney.id.au> rshepard at nospam.appl-ecosys.com writes: > While it should be easy for me to get what I need from a list, it's > proving to be more difficult than I expected. > > I start with this list: > > [ 6.24249034e-01+0.j 5.11335982e-01+0.j 3.67333773e-01+0.j > 3.01189122e-01+0.j 2.43449050e-01+0.j 1.82948476e-01+0.j > 1.43655139e-01+0.j 9.91225725e-02+0.j] That's not correct syntax for a list. I assume, then, that it's not actual code from your program. > and I want a list of floats of only the first 6 digits for each value. You don't get to choose how many digits are represented in a float value; that's a property of the underlying floating-point implementation, and indeed will change depending on the actual value (since a float is a *binary* representation of a number, not decimal). Perhaps you are looking for the Decimal type: > for i in listname: > print i > > I get this: > [each item printed separately] > > I know it's embarrassingly simple, but the correct syntax eludes > my inexperienced mind. What I want is a list [0.62424, 0.51133, ...] > so that I can normalize those values. You can create a new list from any sequence value by using the constructor for the list type: >>> old_sequence = [12, 34, 56] >>> new_list = list(old_sequence) >>> new_list[0] 12 As for making a list containing different values (e.g. Decimal values), you might want a list comprehension: >>> from decimal import Decimal >>> old_sequence = [12, 34, 56] >>> new_list = [Decimal(value) for value in old_sequence] >>> new_list[0] Decimal("12") -- \ "I may disagree with what you say, but I will defend to the | `\ death your right to mis-attribute this quote to Voltaire." -- | _o__) Avram Grumer, rec.arts.sf.written, May 2000 | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Sun Feb 25 16:25:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 25 Feb 2007 22:25:34 +0100 Subject: Referencing Items in a List of Tuples In-Reply-To: References: Message-ID: <45e1f716$0$12835$426a74cc@news.free.fr> rshepard at nospam.appl-ecosys.com a ?crit : > While working with lists of tuples is probably very common, none of my > five Python books or a Google search tell me how to refer to specific items > in each tuple. t = "a", "b", "c" assert t[0] == "a" assert t[1] == "b" assert t[2] == "c" > I find references to sorting a list of tuples, but not > extracting tuples based on their content. loft = [(1, 2, 3), (1, 2, 4), (2, 3, 4)] starting_with_one = [t for t in loft if t[0] == 1] > In my case, I have a list of 9 tuples. Each tuple has 30 items. The first > two items are 3-character strings, the remaining 28 itmes are floats. > > I want to create a new list from each tuple. But, I want the selection of > tuples, and their assignment to the new list, to be based on the values of > the first two items in each tuple. > > If I try, for example, writing: > > for item in mainlist: > if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': > ec.Append(mainlist[item][2:]) > > python doesn't like a non-numeric index. Hem... I'm afraid you don't understand Python's for loops. The above should be: ec = [] for item in mainlist: if [item][0] == 'eco' and item[1] == 'con': ec.append(item[2:]) which can also be written: ec = [item[2:] for item in mainList \ if item[0] == 'eco' and item[1] == 'con'] > I would really appreciate a pointer so I can learn how to manipulate lists > of tuples by referencing specific items in each tuple (string or float). Did you actually tried reading some Python 101 material ? From MonkeeSage at gmail.com Wed Feb 28 16:10:24 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 28 Feb 2007 13:10:24 -0800 Subject: Yet another unique() function... In-Reply-To: <7x7iu2niif.fsf@ruckus.brouhaha.com> References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <1172647505.784091.193710@q2g2000cwa.googlegroups.com> <7x7iu2niif.fsf@ruckus.brouhaha.com> Message-ID: <1172697024.754286.325450@m58g2000cwm.googlegroups.com> On Feb 28, 2:18 pm, Paul Rubin wrote: > Unicode fix (untested): > > def unique(seq, keepstr=True): > t = type(seq) > if t in (unicode, str): > t = (list, t('').join)[bool(keepstr)] > seen = [] > return t(c for c in seq if not (c in seen or seen.append(c))) This definitely works. I tried to post a message about this a few hours ago, but I guess it didn't go through. I've already updated the recipe and comments. > I think these iterator approaches get more readable as one becomes > used to them. I agree. I understood your code in a matter of seconds. From gagsl-py at yahoo.com.ar Sat Feb 17 19:38:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 21:38:52 -0300 Subject: How do I save the contents of a text buffer References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> Message-ID: En Sat, 17 Feb 2007 20:47:20 -0300, escribi?: > I'm using Python with pygtk and have this problem - I have read the > contents of a file into the text buffer with this code, > > infile = open("mytextfile", "r") > if infile: > string = infile.read() > infile.close() > textbuffer.set_text(string) Note that "if infile" does nothing: either the open succeeds and you get a file object which is *always* True, or the open fails and raises an exception and the code below never executes. > As a test, I tried to write the buffer back to a file with this code > but did not work, "did not work" means... -- Gabriel Genellina From andrzej.s at gazeta.pl Wed Feb 28 03:35:14 2007 From: andrzej.s at gazeta.pl (Andrzej S.) Date: Wed, 28 Feb 2007 09:35:14 +0100 Subject: database without installation again In-Reply-To: <1172648929.821762.294820@t69g2000cwt.googlegroups.com> References: <1172648929.821762.294820@t69g2000cwt.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com wrote: > MySQL is a server software. You cannot just drop some files and expect > the whole thing to work. Yes, sure. There is mySQL server installed. I can access it from php. >> I think, the >> best solution would be db stored in binary file with interface in based on >> standard Python library, but is there anything like that?? > > SQLite ? Gadfly ? How can I install them? Is it so simple as uploading module files to cgi-bin directory? Metakit (http://www.equi4.com/metakit/python.html) database works this way, but i haven't tested it yet. -- Andrew S From michiel at thingmajig.org Thu Feb 15 16:21:34 2007 From: michiel at thingmajig.org (Michiel Sikma) Date: Thu, 15 Feb 2007 22:21:34 +0100 Subject: Automated resizing of JPEG image + making slices? Message-ID: <11493D4C-C9E0-46DC-A9F9-B664416460FA@thingmajig.org> Hello everybody. I'm currently involved in a site building project in which we're going to use the Google Maps API. The user will be able to browse the site by looking over a really large image, similar to how Google Maps itself works, except with the design of the site on the background rather than a map of the world. I initially hired someone to do it in PHP (don't bite, please :-) but it seems that I forgot about one thing: the people updating the site would have been able to upload a huge 30 MB JPEG image, which PHP would then resize to various sizes and cut them into 200x200 pieces, which would be fed to the Google Maps API. However, this costs a lot of memory, and PHP by default only has 8 MB. The programmer offered to do a C++ image manipulator, but he uses Windows and the people who update the site use Mac OS X. It would be tedious. Then I thought that Python might solve me the head-ache. I know some Python (but not much since I've never actually written that many things in it), and with some effort I could probably make a simple image manipulator frontend in it, but only if I can find a good library for doing the actual manipulation. Do any of you know such libraries? Many thanks, Michiel Sikma michiel at thingmajig.org From bob at work.org Tue Feb 13 15:53:30 2007 From: bob at work.org (Martien Friedeman) Date: 14 Feb 2007 09:53:30 +1300 Subject: Testers please References: <1171362346.133027.42210@l53g2000cwa.googlegroups.com> Message-ID: <45d2254a$1@clear.net.nz> Thanks for getting involved. And kind remarks. The labeling of 'false' and 'true' is just for shortness sake. The condition itself could be quite a mess and span several lines. You mentioned that. The only reason I like to display it, is to show whether a block of coding, the colored bit, is performed or not. Without that you would find out anyway; nothing becomes underlined when you move your mouse in that area: Nothing in that area is interactive. Because nothing happened there. Even when the condition itself shows on the tab, not just the outcome, the user would still need to scroll up to that tab if it was not visible. The user interface is in HTML, maybe a tooltip when one moves the cursor over a colored condition block could show up that shows the condition and its value. I hate them tooltips though. They make the whole interface so jumpy. More work in that area needed then. From bdesth.quelquechose at free.quelquepart.fr Wed Feb 14 15:51:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 14 Feb 2007 21:51:19 +0100 Subject: How much memory used by a name In-Reply-To: References: Message-ID: <45d36eea$0$24957$426a74cc@news.free.fr> Bernard Lebel a ?crit : > Hello, > > I would like to know if there is a way to know how much memory (bytes, > kilobytes, megabytes, etc) a name is using. > > More specifically, I have this list of strings that I want to write to > a file as lines. > This list grows througout the script execution, and toward the end, > the file is written. Do you really need to first grow the list then write it ? From __peter__ at web.de Thu Feb 1 14:08:15 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Feb 2007 20:08:15 +0100 Subject: Overloading the tilde operator? References: Message-ID: Chris wrote: > I am trying to overload the __invert__ operator (~) such that > it can take a second argument, other than > self, so that I can express: > > x ~ y > > by using: > > def __invert__(self, other): > > for example. Is this possible? No, you will get a syntax error before python even look up the names: >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> x ~ x File "", line 1 x ~ x ^ SyntaxError: invalid syntax Peter From andrewfelch at gmail.com Tue Feb 27 18:36:35 2007 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 27 Feb 2007 15:36:35 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172618605.121435.247300@t69g2000cwt.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> <1172615426.752353.25610@8g2000cwh.googlegroups.com> <1172616850.962166.27480@k78g2000cwa.googlegroups.com> <1172618605.121435.247300@t69g2000cwt.googlegroups.com> Message-ID: <1172619395.282157.187030@a75g2000cwd.googlegroups.com> On Feb 27, 3:23 pm, "Ziga Seilnacht" wrote: > Andrew Felch wrote: > > I pasted the code into mine and replaced the old. It seems not to > > work for either unpickled objects or new objects. I add methods to a > > class that inherits from AutoReloader and reload the module, but the > > new methods are not callable on the old objects. Man! It seems we're > > so close, it will be huge if this ends up working. This stuff is so > > over my head, I wish I could help in some additional way. > > > -Andrew > > Did you copy and paste the entire module? I fiddled almost all parts > of > the original code. I did some base testing and it worked for me. Could > you post the traceback? Note that Google Groups messed up indentation; > in MetaAutoReloader.__init__, the line starting with > cls.__instance_refs__ should be at the same level as previous line. > > Did you restart Python? InstanceTracker, MetaInstanceTracker and > MetaAutoReloader are not auto reloaded :). > > Ziga Thanks for checking. I think I narrowed the problem down to inheritance. I inherit from list or some other container first: class PointList( list, AutoReloader ): def PrintHi1(self): print "Hi2" class MyPrintingClass( AutoReloader ): def PrintHi2(self): print "Hi2v2" Automatic reloading works for MyPrintingClass but not for PointList. Any ideas? -Andrew From stuart at bmsi.com Sat Feb 3 18:21:38 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sat, 03 Feb 2007 18:21:38 -0500 Subject: Vim scripting with python References: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Message-ID: On Sat, 03 Feb 2007 05:02:54 -0800, Tool69 wrote: > Does anyone have any advice, and more genraly how to script Vim with > Python ? :py import sys :py print sys.version :help :py > I know I can put some python functions inside my vimrc file like > this : > > function! My_function() > python << EOF > import vim, string > ...blablabla > EOF > endfunction > > but I would like to use external ".py" files. :py import myfile Use :py inside your vimrc - don't run python externally. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From mail at timgolden.me.uk Mon Feb 26 11:36:26 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Feb 2007 16:36:26 +0000 Subject: ez_setup.py In-Reply-To: <45E30AE9.40900@knmi.nl> References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> <45E305D0.4010806@timgolden.me.uk> <45E3075E.2090308@knmi.nl> <45E3083F.2020303@timgolden.me.uk> <45E30AE9.40900@knmi.nl> Message-ID: <45E30C8A.1020307@timgolden.me.uk> Nader Emami wrote: > Tim Golden wrote: >> Nader Emami wrote: >> >>>>> How can do the second solution, (take off the home from Python path)? >>>> >>>> Depends on your setup. Since you're on *nix, I can't >>>> test whether $HOME is automatically on sys.path (it >>>> isn't on Win32). Are you running *in* /usr/people/emami? >>>> If so, go somewhere else before you run ez_setup. Check >>>> your PYTHONPATH env var; perhaps reset it before >>>> running ez_setup. There are other more obscure possibilities >>>> to do with things set in site.py but they're less likely. >>>> >>>> TJG >>> I have a Linux and I don't have any PYTHONPTH variable, because if I >>> run the next command it returns nothig: >>> >>> %env | grep -i pythonpath or >>> %env | grep -i python >> >> I'm no expert here, but I believe that Linux is >> case-sensitive, so you'd need to do: >> >> env | grep PYTHONPATH >> >> TJG > 'grep' with 'i' option can catch both of them. I have done with capital > letters also and the answer stays the same: > %env | grep PYTHONPATH of %env | grep PTYTHON OK. Keep copying to the list, please. As I said, I'm not a *nix person (and I'm running here on Windows) so you'll get a more informed and wider audience from c.l.py. If there's no PYTHONPATH that means it's just down to your system setup what goes on the path. Try (from within the python interpreter): import sys for i in sys.path: print i Do you see your home directory there? TJG From horpner at yahoo.com Mon Feb 26 07:16:24 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 26 Feb 2007 13:16:24 +0100 Subject: Pep 3105: the end of print? References: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> Message-ID: On 2007-02-23, I V wrote: > On Tue, 20 Feb 2007 10:46:31 -0800, Beliavsky wrote: >> I think the C and C++ committees also take backwards >> compatibility seriously, in part because they know that >> working programmers will ignore them if they break too much >> old code. > > While that's true, C++ compiler vendors, for example, take > backwards compatibility significantly less seriously, it seems > to me. Compiler vendors usually take care of their customers with compiler switches that enable backwards compatibility. -- Neil Cerutti From robert.kern at gmail.com Sun Feb 25 15:28:19 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 25 Feb 2007 14:28:19 -0600 Subject: finding out the precision of floats In-Reply-To: <1172410271.154309.49700@j27g2000cwj.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> Message-ID: John Machin wrote: > Evidently not; here's some documentation we both need(ed) to read: > > http://docs.python.org/tut/node16.html > """ > Almost all machines today (November 2000) use IEEE-754 floating point > arithmetic, and almost all platforms map Python floats to IEEE-754 > "double precision". > """ > I'm very curious to know what the exceptions were in November 2000 and > if they still exist. All Python interpreters use whatever is the C double type on its platform to represent floats. Not all of the platforms use *IEEE-754* floating point types. The most notable and still relevant example that I know of is Cray. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From http Mon Feb 5 17:11:23 2007 From: http (Paul Rubin) Date: 05 Feb 2007 14:11:23 -0800 Subject: Python does not play well with others References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <7xodo85tzi.fsf@ruckus.brouhaha.com> <1170711750.776012.126850@h3g2000cwc.googlegroups.com> Message-ID: <7x7iuw8dbo.fsf@ruckus.brouhaha.com> "Graham Dumpleton" writes: > No such limitation exists with mod_python as it does all the > interpreter creation and management at the Python C API level. The one > interpreter per process limitation is only when using the standard > 'python' runtime executable and you are doing everything in Python code. Oh cool, I thought CPython used global and/or static variables or had other obstacles to supporting multiple interpreters. Is there a separate memory pool for each interpreter when you have multiple ones? So each one has its own copies of 0,1,2,None,..., etc? How big is the memory footprint per interpreter? I guess there's no way to timeshare (i.e. with microthreads) between interpreters but that's o.k. From kibleur.christophe at gmail.com Tue Feb 20 15:55:57 2007 From: kibleur.christophe at gmail.com (Tool69) Date: 20 Feb 2007 12:55:57 -0800 Subject: question with inspect module In-Reply-To: <1172003524.934883.237070@v45g2000cwv.googlegroups.com> References: <1171998273.748507.14070@h3g2000cwc.googlegroups.com> <1172003524.934883.237070@v45g2000cwv.googlegroups.com> Message-ID: <1172004957.444091.251780@a75g2000cwd.googlegroups.com> Thanks Miki, that's exactly what I need :) From Bulkan at gmail.com Sun Feb 18 22:32:59 2007 From: Bulkan at gmail.com (placid) Date: 18 Feb 2007 19:32:59 -0800 Subject: What is more efficient? In-Reply-To: References: Message-ID: <1171855979.592379.303410@q2g2000cwa.googlegroups.com> On Feb 19, 2:17 pm, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Let's say I have a class with few string properties and few integers, and > a lot of methods defined for that class. > > Now if I have hundreds of thousands (or even more) of instances of that > class - is it more efficient to remove those methods and make them > separate functions, or it doesn't matter? What do you mean by efficient. Memory efficient? I would assume that making them separate functions would use less memory but would you sacrifice code readability for that (small?) of a memory saving? Good coding practice suggests that the methods should be bound to classes. > > Thanks... > > -- > _______ Karlo Lozovina - Mosor > | | |.-----.-----. web:http://www.mosor.net|| ICQ#: 10667163 > | || _ | _ | Parce mihi domine quia Dalmata sum. > |__|_|__||_____|_____| Cheers From tiedon_jano at hotmail.com Thu Feb 22 06:55:22 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 22 Feb 2007 11:55:22 GMT Subject: Convert to binary and convert back to strings In-Reply-To: References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172105179.708565.201600@v33g2000cwv.googlegroups.com> Message-ID: Steven D'Aprano kirjoitti: > On Wed, 21 Feb 2007 16:46:19 -0800, Harlin Seritt wrote: > >>> WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM. It is just a >>> nuisance for someone that really wants to decrypt the string. But >>> it might work for your application. >>> >>> -Larry >> Thanks Larry! I was looking for something more beautiful but what the >> hey, it works! > > > Is this beautiful enough? > > >>>> s = "Python" >>>> u = unicode(s, "ascii") >>>> u > u'Python' >>>> u.encode('rot13') > 'Clguba' > > > For extra security, you can encode the string with rot13 twice. > > > Like this? ;) >>> s = "Python" ; u = unicode(s, "ascii") ; u u'Python' >>> u.encode('rot13') 'Clguba' >>> u.encode('rot13').encode('rot13') 'Python' Cheers, Jussi From Barry.Carroll at psc.com Thu Feb 1 15:03:28 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 1 Feb 2007 12:03:28 -0800 Subject: Sorting a list Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AD2@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: John Salerno [mailto:johnjsal at NOSPAMgmail.com] > Sent: Thursday, February 01, 2007 11:54 AM > To: python-list at python.org > Subject: Re: Sorting a list > > Bruno Desthuilliers wrote: > > John Salerno a ?crit : > >> Hi everyone. If I have a list of tuples, and each tuple is in the form: > >> > >> (year, text) as in ('1995', 'This is a citation.') > >> > >> How can I sort the list so that they are in chronological order based > >> on the year? > > > > Calling sort() on the list should just work. > > Amazing, it was that easy. :) Hello, John. Yeah. That's one of the things that drew me to Python: so many things you want to do are just so *easy* in Python. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From skip at pobox.com Mon Feb 12 23:27:00 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 12 Feb 2007 22:27:00 -0600 Subject: MacPython wiki "moved" to Python wiki - now it's your turn... Message-ID: <17873.15892.286360.853505@montanaro.dyndns.org> After much wailing and gnashing of teeth the past couple of days, I managed to move (most of?) the content from the MacPython wiki to the main Python wiki (*). All pages were created as subpages of http://wiki.python.or/moin/MacPython The motivation for this rather hasty move was that the MacPython wiki was running an ancient version of MoinMoin and got spammed heavily. Because of its age and vulnerability it was simply too hard to keep up with all the wiki spammers. So I moved everything. I did very little to try and fix up link references. Moin's subpage references have always befuddled me, and many of the page references were weirded out to begin with, so there you have it: royal link spaghetti. This is where you come in. You can do any number of things to try to identify and fix problems: * Visit http://wiki.python.org/moin/OrphanedPages and see if there are any MacPython/... pages which are orphaned (hint: there are quite a few). Then see if you can find an incorrect link which should refer to the orphaned page. * Visit the MacPython pages. Just do a title search for "MacPython" to locate them. Visit and clean up as appropriate. * Everything got pushed down, even home pages. One of three things can reasonably be done: 1. Move a home page up if there isn't one at the top level. 2. Replace an uplevel home page with the MacPython version if the latter is "better". 3. Merge the content from the MacPython version into the uplevel home page. Instead of performing #2 and #3 yourself, you might send an email to the person and ask them to do the merge/replace. In any case, this operation is likely to require some link fiddling. * There may also be non-homepage pages at the top level which should be merged with or replaced by (or replace) the MacPython version. VisualPython comes to mind. Use your judgement * There are lots of unprotected path references in the content, e.g. /System/Library sitting there looking like a link when it should probably be {{{/System/Library}}}. * There may still be a bit of spam lurking in the pages. I tried to eliminate all the crap, but I might have missed some. * Many pages could use Category references. There are lots of pages referring to scripting specific Mac applications, home pages and many code samples. Adding CategoryMac or CategoryAppScript might be reasonable as well. * Use your WikiImagination. There are probably lots of other things that can be done. I think the MacPython wiki had fallen into a bit of disrepair, even if you ignore the spam problem, so a little general TLC would probably help. Skip (*) Thank goodness for Emacs and Mozex... From frodo at theshire.org Tue Feb 13 08:33:37 2007 From: frodo at theshire.org (Cristiano Paris) Date: Tue, 13 Feb 2007 14:33:37 +0100 Subject: Lazy container In-Reply-To: References: Message-ID: <45D1BE31.6050702@theshire.org> Duncan Booth wrote: > ... > Yes. Try using weak references. Specifically a weakref.WeakValueDictionary > should meet your needs. :D Thank you. Cristiano From nicola.musatti at gmail.com Wed Feb 14 10:45:33 2007 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 14 Feb 2007 07:45:33 -0800 Subject: c++ for python programmers In-Reply-To: References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <1171467933.663222.297490@v45g2000cwv.googlegroups.com> On Feb 14, 2:41 pm, Neil Cerutti wrote: [...] > Don't forget the lack of standard garbage collection. Optional garbage collection is highly likely to be included in the next C++ standard, due out in a couple of years. > Also there's the hell known as exception safety. > > Python conceptually has many of the same issues with exception > safety, but at least memory leaks aren't one of the consequences. > I imagine most Python programmers don't even think about > exception safety, but probably should be. We just happily raise > exceptions willy-nilly, without worrying about our objects > remaining in a reasonable state. Or do we? Maybe it's better not > to think about it. ;-) On the other hand having everything dynamically allocated prevents the adoption of deterministic destruction, which is a far better clean up mechanism than try/finally clauses. In modern C++ standard containers and smart pointers help solve most memory related problems. I'm aware that most is not the same as all, but on the other hand garbage collection has it's problems too: depending on the algorithm it may not be able to reclaim all the unreachable memory and forgetting to explicitly reset variables may lead to hanging to memory that is really not needed anymore. Cheers, Nicola Musatti From duncan.booth at invalid.invalid Tue Feb 27 13:53:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Feb 2007 18:53:08 GMT Subject: Lists: Converting Double to Single References: <%6QEh.6362$_73.1862@newsread2.news.pas.earthlink.net> Message-ID: Steven D'Aprano wrote: > If the values vary greatly in magnitude, you probably want to add them > from smallest to biggest; other than that, how else can you calculate the > mean? > It doesn't have to be smallest to largest, but the important thing is not to be adding the millionth element to the sum of the preceding 999999 values. So if I remember correctly one option is to add pairs of numbers, then sum the pairs and so on. I think my point really is that nobody is going to bother doing this when they just want to sum a few numbers, and I'm not really surprised that the builtin sum doesn't do it either, but I was slightly surprised that numpy doesn't try to minimise loss of precision. Here's a quick attempt at implementing it which demonstrates how the builtin sum loses precision somewhat faster than a pairwise sum (and is rather dependant on the input order). sumpair is of course a lot slower than the builtin sum, but it might be interesting to see how a C coded version compared. I can't see that it would necessarily be much slower: it just adds some counters, bit twiddling and a short temporary array to the calculation. C:\temp>sumpairs.py builtin sum 500000.00000083662 pairwise sum 500000.00000499998 sorted builtin sum 500000.00000499998 pairwise sum 500000.00000499998 reverse sorted builtin sum 500000.0 pairwise sum 500000.00000500004 all the same builtin sum 1000000.0000016732 pairwise sum 1000000.00001 ------------ sumpairs.py ------------------------------------------ # Sum implemented so that intermediate results sum a similar number # of the input values. def sumpairs(seq): tmp = [] for i,v in enumerate(seq): if i&1: tmp[-1] += v i = i + 1 n = i & -i while n > 2: t = tmp.pop(-1) tmp[-1] = tmp[-1] + t n >>= 1 else: tmp.append(v) tmp.reverse() return sum(tmp) v = [1000000, 0.00001] * 1000000 print "builtin sum ", repr(sum(v)/len(v)) print "pairwise sum", repr(sumpairs(v)/len(v)) print "sorted" v.sort() print "builtin sum ", repr(sum(v)/len(v)) print "pairwise sum", repr(sumpairs(v)/len(v)) print "reverse sorted" v.reverse() print "builtin sum ", repr(sum(v)/len(v)) print "pairwise sum", repr(sumpairs(v)/len(v)) print "all the same" v = [1000000.00001] * 1000000 print "builtin sum ", repr(sum(v)/len(v)) print "pairwise sum", repr(sumpairs(v)/len(v))----------------------------- ---------------------------------- In case the code is a bit hard to follow this version makes it clearer what is happening: ------------- sumpair2.py --------------- def sumpairs(seq): tmp = [] for i,v in enumerate(seq): if i&1: tmp[-1] += v print "add ", tmp i = i + 1 n = i & -i while n > 2: t = tmp.pop(-1) tmp[-1] = tmp[-1] + t n >>= 1 print "reduce", tmp else: tmp.append(v) print "append", tmp tmp.reverse() return sum(tmp) print sumpairs([1]*40) ----------------------------------------- which gives the output: append [1] add [2] append [2, 1] add [2, 2] reduce [4] append [4, 1] add [4, 2] append [4, 2, 1] add [4, 2, 2] reduce [4, 4] reduce [8] append [8, 1] add [8, 2] append [8, 2, 1] add [8, 2, 2] reduce [8, 4] append [8, 4, 1] add [8, 4, 2] append [8, 4, 2, 1] add [8, 4, 2, 2] reduce [8, 4, 4] reduce [8, 8] reduce [16] append [16, 1] add [16, 2] append [16, 2, 1] add [16, 2, 2] reduce [16, 4] append [16, 4, 1] add [16, 4, 2] append [16, 4, 2, 1] add [16, 4, 2, 2] reduce [16, 4, 4] reduce [16, 8] append [16, 8, 1] add [16, 8, 2] append [16, 8, 2, 1] add [16, 8, 2, 2] reduce [16, 8, 4] append [16, 8, 4, 1] add [16, 8, 4, 2] append [16, 8, 4, 2, 1] add [16, 8, 4, 2, 2] reduce [16, 8, 4, 4] reduce [16, 8, 8] reduce [16, 16] reduce [32] append [32, 1] add [32, 2] append [32, 2, 1] add [32, 2, 2] reduce [32, 4] append [32, 4, 1] add [32, 4, 2] append [32, 4, 2, 1] add [32, 4, 2, 2] reduce [32, 4, 4] reduce [32, 8] 40 From __peter__ at web.de Fri Feb 9 04:52:29 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Feb 2007 10:52:29 +0100 Subject: Latest approach to controlling non-printable / multi-byte characters References: <1170966028.403341.252770@p10g2000cwp.googlegroups.com> Message-ID: metaperl wrote: > There is no end to the number of frantic pleas for help with > characters in the realm beyond ASCII. And the answer is "first decode to unicode, then modify" in nine out of ten cases. > However, in searching thru them, I do not see a workable approach to > changing them into other things. > > I am dealing with a file and in my Emacs editor, I see "MASSACHUSETTS- > AMHERST" ... in other words, there is a dash between MASSACHUSETTS and > AMHERST. > > However, if I do a grep for the text the shell returns this: > > MASSACHUSETTS?€“AMHERST > > and od -tc returns this: > > 0000540 O F M A S S A C H U S E T > T > 0000560 S 342 200 223 A M H E R S T ; U N > I > > > So, the conclusion is the "dash" is actually 3 octal characters. My > goal is to take those 3 octal characters and convert them to an ascii > dash. Any idea how I might write such a filter? The closest I have got > it: > > unicodedata.normalize('NFKD', s).encode('ASCII', 'replace') > > but that puts a question mark there. No idea where the character references come from but the dump suggests that your text is in UTF-8. >>> "MASSACHUSETS\342\200\223AMHERST".decode("utf8") u'MASSACHUSETS\u2013AMHERST' >>> "MASSACHUSETS\342\200\223AMHERST".decode("utf8").replace(u"\u2013", "-") u'MASSACHUSETS-AMHERST' u"\2013" is indeed a dash, by the way: >>> import unicodedata >>> unicodedata.name(u"\u2013") 'EN DASH' Peter From cityhunter007 at gmail.com Fri Feb 9 15:57:08 2007 From: cityhunter007 at gmail.com (James) Date: 9 Feb 2007 12:57:08 -0800 Subject: interacting with shell - another newbie question Message-ID: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> Hello, I work in this annoying company where I have to autheticate myself to the company firewall every 30-50 minutes in order to access the internet. (I think it's a checkpoint fw). I have to run "telnet what.ever.ip.address 259" then it prompts me with userid, then password, then I have to select "1". Then the program closes itself and the internet is enabled. I would like to automate this process with Python and run it every 30 miniutes so I don't have to keep typing in these userid/password everytime. How can this be done? Is there a module I can use to interact with the shell? (I'm running linux) Thank you. James From jfine at pytex.org Thu Feb 8 16:58:33 2007 From: jfine at pytex.org (Jonathan Fine) Date: Thu, 08 Feb 2007 21:58:33 +0000 Subject: struct.pack bug? Message-ID: <45CB9D09.3030604@pytex.org> Hello I find the following inconsistent: === >>> sys.version '2.4.1a0 (#2, Feb 9 2005, 12:50:04) \n[GCC 3.3.5 (Debian 1:3.3.5-8)]' >>> pack('>B', 256) '\x00' >>> pack('>> pack('B', 256) Traceback (most recent call last): File "", line 1, in ? struct.error: ubyte format requires 0<=number<=255 >>> === I was hoping that '>B' and ' <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> <1171636975.653884.122850@p10g2000cwp.googlegroups.com> Message-ID: On Fri, 16 Feb 2007 06:42:55 -0800, Fuzzyman wrote: > I mentioned the 2to3 translator- the goal of which is *precisely* to > allow you to write code that will run on Python 2.X and when > translated run under Python 3.0. Unfortunately, that is not a realistic goal for the 2to3 translator. The goal is to accurately translate 80% of Python code that needs changing, and issue warnings for the other 20%. > You then repeated the problem with the 'print' statement. > > It may be true that you won't be able to write code that runs > untranslated on 2 and 3. That doesn't stop you writing code for Python > 2.X, then translating a version for Python 3. (Uhm... indeed that's > the point of 2to3.) > > So you only have one codebase to maintain and you can still use > print... No, you have TWO sets of code. You have the code you write, and the code you have run through 2to3. Even if 2to3 gives you 100% coverage, which it won't, you still have two codebases. -- Steven. From rzantow at gmail.com Fri Feb 2 00:09:41 2007 From: rzantow at gmail.com (rzed) Date: Fri, 02 Feb 2007 00:09:41 -0500 Subject: win32com.client References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170379374.589869.158610@p10g2000cwp.googlegroups.com> <1170379682.386807.99880@a34g2000cwb.googlegroups.com> Message-ID: "vithi" wrote in news:1170379682.386807.99880 at a34g2000cwb.googlegroups.com: > Hi, > I use python for window. If you are saying win32com in part of the > python then you are wrong. That is not what I or anyone else is saying. What we have said, perhaps not in words you understand, is this: 1) In your browser, enter this URL: http://sourceforge.net/projects/pywin32/ 2) When the page comes up, find the big green box that says "Download Python for Windows extensions" and click on it 3) In the next page that comes up, find the big green box that says "Download" and click on that. That will bring up a page with a list of installers, each with a name that indicates what Python release the module goes with. If you have the 2.4 release, for instance, click on pywin32-210.win32-py2.4.exe to download the matching pywin32 installer. 4) When you have downloaded the installer, click on it in your Windows Explorer. This will execute the installer, and the entire pywin32 package will be installed, including win32com. Try those steps, then try importing win32com again. -- rzed From duncan.booth at invalid.invalid Wed Feb 7 16:06:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Feb 2007 21:06:08 GMT Subject: string.find for case insensitive search References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: "Johny" wrote: > Is there a good way how to use string.find function to find a > substring if I need to you case insensitive substring? s.lower().find(substring.lower()) From gagsl-py2 at yahoo.com.ar Wed Feb 28 19:16:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Feb 2007 21:16:45 -0300 Subject: difference between string and list References: <45E45599020000C50000702F@gw.osc.edu> Message-ID: En Tue, 27 Feb 2007 18:00:25 -0300, lincoln rutledge escribi?: > Okay, I actually have those pages up in my browser. I found the string > methods: > http://docs.python.org/lib/string-methods.html > > But I am having trouble finding the same information for lists... On that page, click on "TOC - Table of Contents". You were exactly at section 3.6.1 "String methods"; now go to section 3.6.4 "Mutable Sequence Types" Another way to find that, is using the "Index" page - under "L" you find "list: type, operations on" It's very useful, at least, overview the two chapters on builtin functions and builtin types. -- Gabriel Genellina From hg at nospam.org Sat Feb 10 10:47:56 2007 From: hg at nospam.org (hg) Date: Sat, 10 Feb 2007 16:47:56 +0100 Subject: wxPython libraries never detected References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> <1171143155.537545.9530@j27g2000cwj.googlegroups.com> Message-ID: d.lidell at gmail.com wrote: > On Feb 10, 1:07 pm, hg wrote: >> By default, you need to have wx installed in the python site-package path >> / under Mandriva, I have wx 2.8 installed >> here: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-ansi/ >> >> hg > > Ah, now I see. But I have a new problem: > > "ls /usr/lib/python2.4/site-packages | grep wx-2.8" returns "wx-2.8- > gtk2-unicode" > > I copied wx-2.8-gtk2-unicode to /usr/lib/python2.5/site-packages/, > which I assume the programs I am attempting to compile and run are > using by default, but they still do not find the libraries. How can I > tell where the programs are searching for the libraries? > > Thanks. If you're going to try the copy technique (never tried it) , you also need to copy wx.pth and wxversion.py. hg From no at spam.com Wed Feb 14 16:44:16 2007 From: no at spam.com (Farshid Lashkari) Date: Wed, 14 Feb 2007 13:44:16 -0800 Subject: f---ing typechecking In-Reply-To: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> References: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Message-ID: Szabolcs Nagy wrote: >>>> L=[1] >>>> L.extend((1,)) >>>> L > [1, 1] Are list.extend() and list concatenation supposed to behave differently? I always thought concatenation was just shorthand for calling extend(). However the following seems to work: >>> L = [1] >>> L += (2,) >>> L [1, 2] It seems like the '+' operator for lists should accept any iterable for the right side argument to be consistent with extend() and the '+=' operator. -Farshid From mail at microcorp.co.za Thu Feb 22 01:18:07 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 22 Feb 2007 08:18:07 +0200 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <01af01c7564a$4e227c40$03000080@hendrik> "Harlin Seritt" wrote: > Hi... > > I would like to take a string like 'supercalifragilisticexpialidocius' > and write it to a file in binary forms -- this way a user cannot read > the string in case they were try to open in something like ascii text > editor. I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is there any > way to do this in Python? > I would xor each char in it with 'U' as a mild form of obfuscation... Look at the array module to get things you can xor, or use ord() on each byte, and char() Note that char(ord('U')) is 'U', and ord('U') is the equivalent of 0x55, or five sixteens plus five - 85. If its ascii just writing it out as binary is useless for what you want to do. This will invert every alternate bit, producing apparent gibberish. HTH - Hendrik From aahz at pythoncraft.com Sat Feb 17 16:25:28 2007 From: aahz at pythoncraft.com (Aahz) Date: 17 Feb 2007 13:25:28 -0800 Subject: message processing/threads References: Message-ID: In article , Jonathan Curran wrote: > >I need a program running in the background to process messages (FIFO order) >which I would send using soap/xmlrpc/pyro (haven't decided yet). According to >my thinking I would need to make this a threaded application. One thread to >process the messages and the other thread(s) would be used to listen for >messages and insert it into the message queue. > >Is my thinking correct? Is there a better way to do such a thing? Well, that's one option. Your other two options are to implent your program with multiple processes or to use event-loop programming. Your basic design looks reasonably sound, though you might consider multiple threads to process messages (which probably won't provide any performance boost but could enhance response if you're using callbacks at all). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From broek at cc.umanitoba.ca Fri Feb 9 19:50:58 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Fri, 09 Feb 2007 18:50:58 -0600 Subject: doctests for interactive functions In-Reply-To: References: <45CB77E3.3040108@cc.umanitoba.ca> <87veic9xb2.fsf@benfinney.id.au> Message-ID: <45CD16F2.8070502@cc.umanitoba.ca> Neil Cerutti said unto the world upon 02/09/2007 08:52 AM: > On 2007-02-08, Brian van den Broek wrote: >> Can I run the rough structure of my code past you to see if it >> is in the vicinity of what you mean? (I have removed some >> details for sake of a short(er :-)) post.) > > Yes, this is a good way to think about it. Separate input from > validation. The downside is that control flow grows warts. > >> My .get method looks like: > Your scheme may run into trouble with unexpected end of file when > input_function is not raw_input. File methods don't raise an > exception for EOF, they just return "", the empty string. So you > may need to check of that return value, and raise IOError for > that case. > >> ._process_invalid_input is implemented to provide useful >> Is this the sort of thing you mean, or is this the sort of >> coupling you suggest I avoid? > > It has to be coupled somewhere. This seems like a good place to > do it. The private methods can all be tested individually, so the > doctests for get can be quite simple, or even absent. > > Note that sequestering the test input in a file doesn't allow for > good examples, unfortunately. Hi Neil and all, It is unfortunate. It looks like either way, I'm stuck with a choice between runnable examples and realistic looking examples. I'll go for runnability, to ensure that the examples are up to date. Your feedback on my design is much appreciated, Neil. Best, Brian vdB From andrea.gavana at gmail.com Thu Feb 8 12:49:21 2007 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Thu, 8 Feb 2007 17:49:21 +0000 Subject: Simple SVN/CVS-like library in Python? In-Reply-To: <45CA3BA9.9030703@islandtraining.com> References: <45CA3BA9.9030703@islandtraining.com> Message-ID: > Andrea Gavana wrote: > > Hi All, > > > > in our office we work with quite complex input files for a > > reservoir simulator. Those files have thousands of keywords, switches, > > sub-keywords and whatever. Every time a modification is requested, we > > modify the input file and re-run the simulator. Obviously, the > > possible modifications are innumerable: so, after few months, we lose > > the records of all the changes we made during time and we don't have > > anymore a clear history of our work. This can be a problem, as > > sometimes it happens that an old input file is requested by > > collegues/sub-companies, and it is a pain to retrieve the correct file > > and results. > > So, I have written a GUI in wxPython that could help us in tracking > > the history, but I was wondering if there exists a small and simple > > SVN/CVS-like library in Python that may help us in a better way, > > storing modifications/changes and showing which input file are the > > "children" of (are derived from) another input file (older). > > But I am open to all possible suggestions to improve/modify the > > software, as this is an area in which my experience is about nothing > > above zero. > > Thank you guys for all your useful suggestions. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ From malaclypse2 at gmail.com Wed Feb 28 17:08:34 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 28 Feb 2007 17:08:34 -0500 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: <45E5F12C.4030200@timgolden.me.uk> References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> <45E5F12C.4030200@timgolden.me.uk> Message-ID: <16651e80702281408v6e51f654o17c31e1c9288e1eb@mail.gmail.com> On 2/28/07, Tim Golden wrote: > Well it's not often someone beats me to a WMI > solution :) Just to be different, you can also > look at the GetDiskFreeSpace function in the > win32api module of the pywin32 extensions. The MSDN page for that function warns: "The GetDiskFreeSpace function cannot report volume sizes that are greater than 2 gigabytes (GB). To ensure that your application works with large capacity hard drives, use the GetDiskFreeSpaceEx function." Make sure to keep that in mind if you're recording free disk space someplace, rather than just checking for enough space to do an install or something. -- Jerry From fredrik at pythonware.com Tue Feb 6 06:12:16 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 6 Feb 2007 12:12:16 +0100 Subject: Repr or Str ? References: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> Message-ID: "Johny" wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences roughly, repr() is for programmers, str() is for end-users. From bignose+hates-spam at benfinney.id.au Tue Feb 27 21:05:53 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 13:05:53 +1100 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> <1172561344.290126.191530@h3g2000cwc.googlegroups.com> <3c5Fh.3664$Tg7.2156@trnddc03> Message-ID: <87bqjfxchq.fsf@benfinney.id.au> "Alan Isaac" writes: > OK, let me approach this from a new direction. Suppose I define a > class that behaves I think as I stipulated:: > > class NothingNew: > a = 0 > def __init__(self): > self.b = 1 > self.initialized = True > def __setattr__(self, attr, val): > if not hasattr(self,'initialized') or hasattr(self, attr): > self.__dict__[attr] = val > else: > raise ValueError > > After adding some documentation, what are the downsides? The biggest downside I see is that you're going through contortions to solve a problem you haven't demonstrated actually exists. A smaller problem is that the ValueError should describe what's going wrong: raise ValueError("The author of this class thinks you're up to no good") Really, though, adding attributes to an instance is a normal thing to do in Python, and you've not yet shown why you want that normal functionality to be special-cased here. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__) Jones | Ben Finney From GatlingGun at gmail.com Thu Feb 1 08:46:36 2007 From: GatlingGun at gmail.com (TOXiC) Date: 1 Feb 2007 05:46:36 -0800 Subject: Help me with this!!! In-Reply-To: References: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> Message-ID: <1170337596.369951.12310@m58g2000cwm.googlegroups.com> Peter Otten ha scritto: > TOXiC wrote: > > > Hi all, I've this code: > > No you don't. > !???????? > > regex = re.compile(r"(?si)(\x8B\xF0\x85\xF6)(?P.*) > > (\xC6\x44\x24)",re.IGNORECASE) > > file = open(fileName, "rb") > > for line in file: > > if (match): > > print line > > file.close() > > > > It search a text inside that hex value. > > It works perfecly on a txt file but if I open a binary file (.exe,.bin > > ecc...) with the same value it wont work, why? > > Please help! > > Because the pattern isn't in the file, perhaps. > This pattern IS in the file (I made it and I double check with an hex editor). It display the file correcltly (print line) but... From christian.convey at gmail.com Thu Feb 15 19:40:51 2007 From: christian.convey at gmail.com (Christian Convey) Date: Thu, 15 Feb 2007 19:40:51 -0500 Subject: numpy, numarray, or numeric? Message-ID: <6addebae0702151640p4128d333necdd7cfce4be2f4@mail.gmail.com> I need to bang out an image processing library (it's schoolwork, so I can't just use an existing one). But I see three libraries competing for my love: numpy, numarray, and numeric. Can anyone recommend which one I should use? If one is considered the officially blessed one going forward, that would be my ideal. Thanks, Christian From nisimura at gmail.com Wed Feb 28 11:45:29 2007 From: nisimura at gmail.com (nisimura at gmail.com) Date: 28 Feb 2007 08:45:29 -0800 Subject: SocketServer.ForkingMixIn and zombie processes Message-ID: <1172681128.820118.135610@k78g2000cwa.googlegroups.com> Hi, I noticed that when I used SocketServer.ForkingMixIn (ForkingTCPServer), there were always zombie processes around. I searched for where waitpid() is called in ForkingMixIn and found it in SocketServer.py: def process_request(self, request, client_address): """Fork a new subprocess to process the request.""" self.collect_children() pid = os.fork() if pid: # Parent process if self.active_children is None: self.active_children = [] self.active_children.append(pid) self.close_request(request) return else: # Child process. # This must never return, hence os._exit()! try: self.finish_request(request, client_address) os._exit(0) except: try: self.handle_error(request, client_address) finally: os._exit(1) So waitpid() is called just before fork(). This means that if next request does not come in, zombie processes are not reclaimed forever! Is this an intentional behavior? Is there any workaround? -- Kazu Nisimura From paul at boddie.org.uk Tue Feb 27 06:44:45 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Feb 2007 03:44:45 -0800 Subject: installing "pysqlite" In-Reply-To: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> Message-ID: <1172576685.560386.306740@m58g2000cwm.googlegroups.com> On 27 Feb, 10:31, Nader Emami wrote: > I have installed "TurboGears" and I would install 'pysqlite' also. I am > a user on a Linux machine. If I try to install the 'pysqlite' with > 'easy_install' tool I get the next error message. The error message is > longer than what I send here. [...] > src/connection.h:33:21: sqlite3.h: No such file or directory [...] > Could somebody tell me what I have to do to install 'pysqlite'? Install SQLite, perhaps? If the pysqlite build process can't find sqlite3.h then you either don't have SQLite installed, or you don't have the headers for SQLite installed. I'd recommend that you check your installed packages for the SQLite libraries (eg. libsqlite3-0 on Ubuntu) and/or the user interface (eg. sqlite3) and for the development package (eg. libsqlite3-dev). If you can't install the packages, install SQLite from source (see http://www.sqlite.org/) and try and persuade pysqlite to use your own SQLite installation - there's a setup.cfg file in the pysqlite distribution which may need to be changed to achieve this, but I don't know how that interacts with setuptools. Paul From usenet1 at ingfamily.net Thu Feb 15 15:27:09 2007 From: usenet1 at ingfamily.net (usenet1 at ingfamily.net) Date: 15 Feb 2007 12:27:09 -0800 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded In-Reply-To: References: <1171305876.030471.59470@s48g2000cws.googlegroups.com> <1171564971.279097.151370@p10g2000cwp.googlegroups.com> Message-ID: <1171571229.141330.250700@m58g2000cwm.googlegroups.com> > "works" in the sense that it prints something; but sys.path is incomplete, > it lacks site-packages and others (they are added by site.py). > It appears that you have installed Python on C:\Python25 and you build > your application executable into c:\temp\pytest\Debug - is that true? > Hmmm, you will need a debug build of Python too, python25_d.lib/.dll. > Perhaps at this stage it's easier to use the Release build, because you > already have python25.lib/dll. > > You have to fix the "import site" error. Use the following command on a > console window before launching your executable: > set PYTHONVERBOSE=1 > You'll see a lot of lines showing the initial imports; you should be able > to detect what's the problem at "import site"; usually it's trying to load > a missing DLL. > > -- > Gabriel Genellina Thank you for your quick reply and your interest. I had a debug python25_d.lib/dll which i was even using to step into the code to see why it was failing but it will take me more time to understand the python code. The other interesting thing I discovered when trying to build my debug python dll with vs2005 usig the build8 solution was that I was even getting the exact same error: Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\ctypes\__init__.py", line 6, in import os as _os, sys as _sys File "C:\Python25\lib\os.py", line 690, in import copy_reg as _copy_reg File "C:\Python25\lib\copy_reg.py", line 7, in from types import ClassType as _ClassType File "C:\Python25\lib\types.py", line 93, in import _types SystemError: _PyImport_FixupExtension: module _types not loaded that I was getting when when trying to run the script. I decided at that point to go back to python2.4, actually activestate python2.4 and then add the ctype module. I will update this thread on my success or failure. Thanks, Steve From mail at microcorp.co.za Thu Feb 8 03:55:17 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 8 Feb 2007 10:55:17 +0200 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com><1170731096.976076.173270@h3g2000cwc.googlegroups.com><1170749117.582426.151770@p10g2000cwp.googlegroups.com><1170796103.766866.18320@a34g2000cwb.googlegroups.com><1170861935.779969.52980@v33g2000cwv.googlegroups.com><1170874782.600836.210670@a34g2000cwb.googlegroups.com> <2ZKdnYNMboxxS1fYRVnzvA@telenor.com> Message-ID: <000201c74c0a$14fa9960$03000080@hendrik> "Tina I" wrote: Gosi wrote: > On Feb 7, 3:46 pm, Marc 'BlackJack' Rintsch wrote: >> In <1170861935.779969.52... at v33g2000cwv.googlegroups.com>, Gosi wrote: >>> I like to use J for many things and I think that combining Python and >>> J is a hell of a good mixture. >> I was able to follow this sentence up to and including the word "hell"... :-) >> >> Ciao, >> Marc 'BlackJack' Rintsch > > > That is a start. > > "Hell" is also what most example start with as in "Hello something" > Hell in northern countries is very cold. > Hell in middle east is very hot. > I do not know which is your Hell hot or cold. > Hell o ver?ld > It's also a village in Norway: http://en.wikipedia.org/wiki/Hell,_Norway :D I am under the impression that Loki had a daughter called Hel ... - Hendrik From jandre_balt at yahoo.co.uk Thu Feb 1 15:13:14 2007 From: jandre_balt at yahoo.co.uk (Jandre) Date: 1 Feb 2007 12:13:14 -0800 Subject: Recursive zipping of Directories in Windows Message-ID: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> Hi I am a python novice and I am trying to write a python script (most of the code is borrowed) to Zip a directory containing some other directories and files. The script zips all the files fine but when it tries to zip one of the directories it fails with the following error: "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" The script I am using is: import zipfile, os def toZip( directory, zipFile ): """Sample for storing directory to a ZipFile""" z = zipfile.ZipFile( zipFile, 'w', compression=zipfile.ZIP_DEFLATED ) def walker( zip, directory, files, root=directory ): for file in files: file = os.path.join( directory, file ) # yes, the +1 is hacky... archiveName = file[len(os.path.commonprefix( (root, file) ))+1:] zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) print file os.path.walk( directory, walker, z ) z.close() return zipFile if __name__ == "__main__": toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) I have tried to set the permissions on the folder, but when I check the directory permissions it is set back to "Read Only" Any suggestions? Thanks Johan Balt From danb_83 at yahoo.com Sun Feb 18 15:10:04 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Feb 2007 12:10:04 -0800 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? In-Reply-To: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> References: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> Message-ID: <1171829404.817278.59010@v33g2000cwv.googlegroups.com> On Feb 18, 12:58 pm, open... at ukr.net wrote: > Thank you in advance for your response. > Dmitrey The Python equivalent to "varargin" is "*args". def printf(format, *args): sys.stdout.write(format % args) There's no direct equivalent to "varargout". In Python, functions only have one return value. However, you can simulate the effect of multiple return values by returning a tuple. "nargin" has no direct equivalent either, but you can define a function with optional arguments by giving them default values. For example, the MATLAB function function [x0, y0] = myplot(x, y, npts, angle, subdiv) % MYPLOT Plot a function. % MYPLOT(x, y, npts, angle, subdiv) % The first two input arguments are % required; the other three have default values. ... if nargin < 5, subdiv = 20; end if nargin < 4, angle = 10; end if nargin < 3, npts = 25; end ... would be written in Python as: def myplot(x, y, npts=25, angle=10, subdiv=20): ... From google at mrabarnett.plus.com Thu Feb 22 16:13:52 2007 From: google at mrabarnett.plus.com (MRAB) Date: 22 Feb 2007 13:13:52 -0800 Subject: How to covert ASCII to integer in Python? In-Reply-To: References: Message-ID: <1172178832.425502.174650@h3g2000cwc.googlegroups.com> On Feb 22, 6:35 pm, Lloyd Zusman wrote: > "John" writes: > > I just found ord(c), which convert ascii to integer. > > > Anybody know what the reverse is? > > The inverse of "ord" is "chr": > > % python > Python 2.5 (r25:51908, Jan 5 2007, 00:12:45) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> ord('i') > 105 > >>> chr(105) > 'i' > >>> > > IIRC, the first use of the names "ord" and "chr" for these functions > appeared in the Basic language in the 1960's ... in case anyone is > interested in this bit of historical trivia. > In the versions of Basic that I've seen they were ASC (clearly ASCII) and CHR$. I first saw ord in Pascal. From steveo at syslang.net Wed Feb 28 13:48:54 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 28 Feb 2007 13:48:54 -0500 (EST) Subject: Question about raise and exceptions. Message-ID: In my class I have class Error(Exception): """Base class for exceptions in this module.""" pass class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """ def __init__(self, previous, next, message): self.previous = previous self.next = next self.message = message Also in my class I check to see if a transition is legal or not: newstate = self.fsm[self.curr_state][self._ev] if newstate == self.error_state: raise TransitionError, self.curr_state, newstate, \ "Going to error state %d from state %d" % (self.curr_state, newstate) self.curr_state = self.fsm[newstate][self._ev] When I run it I get this: 884 > ./t_fsm.py Traceback (most recent call last): File "./t_fsm.py", line 3, in ? from fsm import * File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76 raise TransitionError, self.curr_state, newstate, "Going to error state %d from state %d" % (self.curr_state, newstate) ^ SyntaxError: invalid syntax (The carat is really under the comma before "Going.) I hate to bother people with syntax problems, but I have no idea what to do. Sorry. TIA :-( -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From kleiner at hora-obscura.de Mon Feb 19 05:38:35 2007 From: kleiner at hora-obscura.de (Stefan Palme) Date: Mon, 19 Feb 2007 11:38:35 +0100 Subject: timeout in urllib.open() References: Message-ID: Uuuh this is no solution for me, because the website-checking tool is part of a very very big application running in an application server, so globally setting the timeout may break a lot of other things... But when there is a "default timeout" (as indicated by the method name) - isn't there a "per-socket timeout" too? -stefan- > I believe this can only be set globally: > > import socket > socket.setdefaulttimeout(seconds) > > Peter From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Feb 27 12:58:42 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Feb 2007 18:58:42 +0100 Subject: book for a starter References: Message-ID: <54j9qfF20cqgnU1@mid.individual.net> Wensui Liu wrote: > I just start learning python and have a question regarding books > for a newbie like me. http://wiki.python.org/moin/IntroductoryBooks > If you are only allowed to buy 1 python book, which one will you > pick? ^_^. I'd pick a reference. YMMV. Regards, Bj?rn (having been allowed to buy more than one Python book) -- BOFH excuse #314: You need to upgrade your VESA local bus to a MasterCard local bus. From rrr at ronadam.com Fri Feb 2 15:16:59 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 02 Feb 2007 14:16:59 -0600 Subject: from __future__ import absolute_import ? In-Reply-To: References: Message-ID: Peter Otten wrote: > Ron Adam wrote: > >> from __future__ import absolute_import >> >> Is there a way to check if this is working? I get the same results with >> or without it. >> >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) >> [MSC v.1310 32 bit (Intel)] on win 32 > > If there are two modules 'foo', one at the toplevel and the other inside a > package 'bar', > > from __future__ import absolute_import > import foo > > will import the toplevel module whereas > > import foo > > will import bar.foo. A messy demonstration: > > $ ls bar > absolute.py foo.py __init__.py relative.py > $ cat bar/absolute.py > from __future__ import absolute_import > import foo > $ cat bar/relative.py > import foo > $ cat foo.py > print "toplevel" > $ cat bar/foo.py > print "in bar" > $ python2.5 -c 'import bar.absolute' > toplevel > $ python2.5 -c 'import bar.relative' > in bar > > > Another example is here: > > http://mail.python.org/pipermail/python-list/2007-January/422889.html > > Peter Thanks, that helped, I see why I was having trouble. work | |- foo.py # print "foo not in bar" | `- bar | |- __init__.py | |- foo.py # print "foo in bar" | |- absolute.py # from __futer__ import absolute_import | # import foo | `- relative.py # import foo * Where "work" is in the path. (1) C:\work>python -c "import bar.absolute" foo not in bar C:\work>python -c "import bar.relative" foo in bar (2) C:\work>python -m "bar.absolute" foo not in bar C:\work>python -m "bar.relative" foo not in bar (3) C:\work>python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import bar.absolute foo not in bar >>> import bar.relative foo in bar (4) C:\work>cd bar C:\work\bar>python -c "import bar.absolute" foo in bar C:\work\bar>python -c "import bar.relative" foo in bar (5) C:\work\bar>python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import bar.absolute foo in bar >>> import bar.relative foo in bar >>> Case (2) seems like it is a bug. Why not also have (4), and (5) do the same as cases (1) and (3)? in cases (4) and (5), that is the result I would expect if I did: import absolute # with no 'bar.' prefix. import relative From what I understand, in 2.6 relative imports will be depreciated, and in 2.7 they will raise an error. (providing plans don't change) Would that mean the absolute imports in (4) and (5) would either find the 'foo not in bar' or raise an error? If so, is there any way to force (warning/error) behavior now? Cheers, Ron From nogradi at gmail.com Sun Feb 18 03:32:28 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 18 Feb 2007 09:32:28 +0100 Subject: conver string to dictionary In-Reply-To: <849825.29475.qm@web53614.mail.yahoo.com> References: <849825.29475.qm@web53614.mail.yahoo.com> Message-ID: <5f56302b0702180032t34c1c150o6fcf814f27da5e0c@mail.gmail.com> > I want to convert string to dictionary .what is the best solution for this? > for example string is like this: > > > '{"SalutationID":["primarykey",8388607,0,None],"CompanyID":[0,8388607,0,"index"], > "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]}' > > and I want to convert this string to this dictionary: > > > {"SalutationID":["primarykey",8388607,0,None],"CompanyID":[0,8388607,0,"index"], > "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]} > > please help me what is the best solution(faster solution) for this? If you have simplejson ( http://cheeseshop.python.org/pypi/simplejson ) installed you can do mydict = simplejson.loads( mystring ) but in this case all occurances of 'None' in your string should be 'null'. Or if you absolutely trust the string to contain nothing dangerous: exec( 'mydict = %s' % mystring ) HTH, Daniel From charleshixsn at earthlink.net Fri Feb 23 19:46:44 2007 From: charleshixsn at earthlink.net (Charles D Hixson) Date: Fri, 23 Feb 2007 16:46:44 -0800 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) In-Reply-To: References: Message-ID: <45DF8AF4.9060002@earthlink.net> Larry Bates wrote: > Charles D Hixson wrote: > >> I'm sure I've read before about how to construct prototypes in Python, >> but I haven't been able to track it down (or figure it out). >> >> What I basically want is a kind of class that has both class and >> instance level dict variables, such that descendant classes >> automatically create their own class and instance level dict variables. >> The idea is that if a member of this hierarchy looks up something in >> it's local dict, and doesn't find it, it then looks in the class dict, >> and if not there it looks in its ancestral dict's. This is rather like >> what Python does at compile time, but I want to do it at run time. >> >> I'm sure I've seen how to do it...but have no idea where, or what it was >> called, or when (probably around the time Prothon was being discussed, >> as I have the idea of prototype associated with it for no clear reason). >> > > What you describe is exactly how Zope works so you might want to spend > some time looking at it. > > http://www.zope.org > > -Larry > Thanks for the suggestion, and I'll do that if I must, but Zope is pretty heavy to drag into something for just one function, and I don't really see any use for most parts of it in what I'm doing. And that's a LOT of code to wade through for one technique. From horpner at yahoo.com Tue Feb 13 10:07:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 13 Feb 2007 16:07:33 +0100 Subject: float print formatting References: Message-ID: On 2007-02-13, hg wrote: > Neil Cerutti wrote: > >> On 2007-02-13, hg wrote: >>> Hi, >>> >>> Considering the float 0.0, I would like to print 00.00. >>> >>> I tried '%02.02f' % 0.0 ... but I get 0.00 >>> >>> Any clue ? >> >> Yes. How wide (total) is "0.00", compared to "00.00"? >> >> -- >> Neil Cerutti > > I do not get it > > s = '%02.02f' % 0.0 The first number after the percent is the minimum width specifier for the ENTIRE field. > s >>> '0.00' > len(s) >>> 4 It is the MINIMUM width specifier for the entire field. -- Neil Cerutti The eighth-graders will be presenting Shakespeare's Hamlet in the church basement on Friday at 7 p.m. The congregation is invited to attend this tragedy. --Church Bulletin Blooper From systemguards at gmail.com Thu Feb 22 07:27:59 2007 From: systemguards at gmail.com (Jaime Casanova) Date: Thu, 22 Feb 2007 07:27:59 -0500 Subject: outlook bar like widget In-Reply-To: <829253.83406.qm@web31107.mail.mud.yahoo.com> References: <829253.83406.qm@web31107.mail.mud.yahoo.com> Message-ID: On 2/21/07, Mohammad Tayseer wrote: > I implemented this module using Tkinter > wow! i will try this, thanks -- regards, Jaime Casanova "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs and the universe trying to produce bigger and better idiots. So far, the universe is winning." Richard Cook From *firstname*nlsnews at georgea*lastname*.com Fri Feb 23 22:18:44 2007 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Sat, 24 Feb 2007 03:18:44 GMT Subject: Possible to set cpython heap size? References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <1172172532.503432.223650@v33g2000cwv.googlegroups.com> Message-ID: <*firstname*nlsnews-C58191.22190623022007@news.verizon.net> In article <1172172532.503432.223650 at v33g2000cwv.googlegroups.com>, "Andy Watson" wrote: ... > If I could have a heap that is larger and does not need to be > dynamically extended, then the Python GC could work more efficiently. ... GC! If you're allocating lots of objects and holding on to them, GC will run frequently, but won't find anything to free. Maybe you want to turn off GC, at least some of the time? See the GC module, esp. set_threshold(). Note that the cyclic GC is only really a sort of safety net for reference loops, as normally objects are free'd when their last reference is lost. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From moin at blackhole.labs.rootshell.ws Fri Feb 9 10:00:36 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Fri, 9 Feb 2007 09:00:36 -0600 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com><1170872694.018720.301410@m58g2000cwm.googlegroups.com> <52vdp2F1qp2n6U2@mid.individual.net> <45CB99DB.1080102@mvista.com> Message-ID: <000801c74c5b$0f436b40$0202a8c0@cisco.com> I am sorry if I sound foolish. Suppose I split my Net application code using parallel python into several processes based upon the number of CPU available. That means a single socket descriptor is distributed across all processes. Is parallelity can be acheived using the processes send/recv on the single socket multiplexed across all the processes.. I haven't tried it yet - would like to have any past experience related to this. ----- Original Message ----- From: "Carl J. Van Arsdall" To: Sent: Thursday, February 08, 2007 3:44 PM Subject: Re: multithreading concept > Bjoern Schliessmann wrote: >> [snip] >> What makes you think that'll be faster? >> >> Remember: >> - If you have one CPU, there is no parallelity at all. >> - If you do have multiple CPUs but only one network device, there is >> no parallel networking. >> >> > Not necessarily, if he's on a full duplex ethernet connection, then > there is some parallelity he can take advantage of. He has upstream and > downstream. > > -c > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software > > -- > http://mail.python.org/mailman/listinfo/python-list From usenet at nicko.org Thu Feb 1 08:00:32 2007 From: usenet at nicko.org (Nicko) Date: 1 Feb 2007 05:00:32 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170299594.491478.310430@a34g2000cwb.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> Message-ID: <1170334830.137876.248230@h3g2000cwc.googlegroups.com> On Feb 1, 3:13 am, krypto.wiz... at gmail.com wrote: > Its not an homework. I appeared for EA sports interview last month. I > was asked this question and I got it wrong. I have already fidlled > around with the answer but I don't know the correct reasoning behind > it. In that case, observer that a/b == a * (1/b), and if b is constant you can compute (1/b) in advance. Since the problem was set by game programmers I'd hazard that they are OK with relatively limited precision and the answer that they were looking for was: a = (b * 04444444445L) >> 32 Note that the constant there is in octal. Nicko From loic at spam.me Tue Feb 13 19:18:00 2007 From: loic at spam.me (Loic) Date: Wed, 14 Feb 2007 01:18:00 +0100 Subject: Comparing lists ... Message-ID: <45d253e8$0$449$426a74cc@news.free.fr> I would like to know if it is possible, and how to do this with Python: I want to design a function to compare lists and return True only if both lists are equal considering memory location of the list. I suppose it would be the equivalent of comparing 2 pointers in c++ lets call this function check(a, b) and define a few lists: >>> l0 = [1, 2, 3, 4] >>> l1 = [1, 2, 3, 4] >>> l2 = l0 I want it to have the following behaviour: >>> check(l1, l0) False >>> check(l2, l0) True >>> check(l1, l2) False Any idea how to do this with Python? From martien.friedeman at gmail.com Mon Feb 12 20:38:27 2007 From: martien.friedeman at gmail.com (martien friedeman) Date: Tue, 13 Feb 2007 14:38:27 +1300 Subject: Testers please Message-ID: I have written this tool that allows you to look at runtime data and code at the same time. And now I need people to test it. The easiest way to see what I mean is to look at some videos: http://codeinvestigator.googlepages.com/codeinvestigator_videos It requires Apache and Sqlite. It works for me with a Firefox browser on Linux. From pydev at rscorp.ab.ca Wed Feb 21 23:51:19 2007 From: pydev at rscorp.ab.ca (Scott SA) Date: Wed, 21 Feb 2007 21:51:19 -0700 Subject: Looking for contract developer(s) - where can I find them? Message-ID: Hi, I've just sent a job listing to python.org and posted this message on comp.lang.python, but am also trying to proactively find python developers through other means. python.org and guru.com notwithstanding, most job-sites to seem only support people/organizations looking for full/part-time employment or with full-time/part-time positions instead of work-for-hire. I require the latter, and in the very near future (days). I'm not looking for an employee as I cannot guarantee long-term work, though much of what is available is fairly consistent (on the board is a 4-week job, followed by another 6-week one). If anyone has ideas where I might find talented individuals and small companies offering (reasonably-priced i.e. not $125/hr like a local firm charges) python services, I'd be most appreciative. We are developing and extending a couple of projects previously developed for clients and replacing a 5-year-old Zope site, all with django, PostgreSQL etc. The work is immediately available for an experienced, self-motivated python web-application programmer. For those on this list that might be interested, I'm looking for self-motivated developers with excellent python skills and if possible experience with django (along with CVS/Subversion, PostgreSQL, SSH, vi/emacs and other open-source projects & tools). Zope experience would be handy too as one job is to replace an old site with a spanky-new django one. Good communication and organizational skills are important. Documentation & commenting are also very important along with the ability to work alone and with others. Meeting deadlines, consistent development pace and accurate reporting are also key. Finally, having a sense of humor is valuable... as you might find yourself being called Bruce (especially if your name is Ryan, Shawn or Mike... as the other guys workin' for me already have those names. Then again if your name is really Bruce... 8-) I'd prefer someone from Western Canada (the other half of the country would be okay too, I guess), but if necessary will consider talented individuals from North America. Due to time-zone and possible language/communication issues, off-shore developers are not attractive _at_this_time_ (sorry). Please submit a resume or other description of qualifications along with availability, desired rate and examples of work (i.e. URLs of projects and what you did on them and/or sample code showing _typical_ style of work). Thanks for any assitance, greatly appreciated. Scott From tinaweb at bestemselv.com Tue Feb 27 05:13:58 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 27 Feb 2007 11:13:58 +0100 Subject: HTML to dictionary In-Reply-To: References: Message-ID: Tina I wrote: > Hi everyone, > > I have a small, probably trivial even, problem. I have the following HTML: >> >> METAR: >> >> ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 NOSIG >>
>> >> short-TAF: >> >> ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040 >>
>> >> long-TAF: >> >> ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 SNRA VV010 >> BECMG 2124 15012KT >>
> > I need to make this into a dictionary like this: > > dictionary = {"METAR:" : "ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 > NOSIG" , "short-TAF:" : "ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040" > , "long-Taf:" : "ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 > SNRA VV010 BECMG 2124 15012KT"} > > I have played around with BeautifulSoup but I'm stuck at stripping off > the tags and chop it up to what I need to put in the dict. If someone > can offer some hints or example to get me going I would greatly > appreciate it. > > Thanks! > Tina Forgot to mention that the "METAR:", "short-TAF", and "long-TAF" is always named as such wheras the line of data ("ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 SNRA VV010 ") is dynamic and can be anything... Tina From lbates at websafe.com Thu Feb 22 12:50:45 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 22 Feb 2007 11:50:45 -0600 Subject: export an array of floats to python In-Reply-To: References: Message-ID: <0tadnaDf9NqbRUDYnZ2dnUVZ_sTinZ2d@comcast.com> Peter Wuertz wrote: > Hi, > > I'm writing a C module for python, that accesses a special usb camera. > This module is supposed to provide python with data (alot of data). Then > SciPy is used to fit the data. > > My question is, how to make python read from a C array? By reading the > documentation, one could get the impression that PyBufferObjects do that > job. > > http://docs.python.org/api/bufferObjects.html > > It says: > "Two examples of objects that support the buffer interface are strings > and arrays." > > Where this function looks promising: > "PyBuffer_FromMemory - Return a new read-only buffer object that reads > from a specified location in memory, with a specified size." > > All right, lets imagine I created a PyBufferObject from my float array > in the C module, and passed it to python. > > I dont know what to do with a BufferObject in python, I would like to > "cast" it to a Array of the type float, but Arrays do not have that kind > of function... they can only be constructed from files or lists. > > Apart from creating these BufferObjects, there is no documentation about > what to do with them :( > > Thanks for your help! I've always used the struct module to unpack the C array into the floats (or ints or strings or ...) that I wanted. -Larry Bates From silverfrequent at gmail.com Sat Feb 3 14:57:00 2007 From: silverfrequent at gmail.com (Silver Rock) Date: Sat, 3 Feb 2007 17:57:00 -0200 Subject: SndObj-Pysonic-omde-MusicKit-Jack-Alsa Message-ID: Greetings, I've been studiyng python and some things are not that clear: 1- Is python too slow to efectivelly communicate with Jack? PyJack did not seem to work right, so i tried PySndObj's JackIO object. It did not behave as good as with connection with ALSA. (btw, I could not acess lots of objects in the SndObj library (like Ocil, Rand, while acessing normally Oscilli and Randh...) Does anyone know why?) 2- Python comes with the ossaudiodev module for communication with OSS; Alsa is compatible so it works. Shuld one use this module or use the pyalsasound? 3- pySonic - pySonic the wrapper for the FMOD sound library. but it is not opensource... is there a standard library for sound processing in projects like ardour. 4- Are any differences between 'r' and 'rb'; 'w' and 'wb' in: wave.open('file', 'r') wave.open('file', 'rb') wave.open('file', 'w') wave.open('file', 'wb') ?? 5- I found pySonic, that seems good but it is not open. MusicKit and PySndObj and omde. Ow yeah, and Pygame. Can anyone expose ihre personal experience and explain why? Please be nice, Claire -------------- next part -------------- An HTML attachment was scrubbed... URL: From enleverlesX.XmcX at XmclaveauX.com Mon Feb 19 15:34:05 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 19 Feb 2007 21:34:05 +0100 Subject: bluetooth on windows....... References: <1171865073.564109.240970@q2g2000cwa.googlegroups.com> Message-ID: <45da09ca$0$5087$ba4acef3@news.orange.fr> Hi! >> try to find a PyBluez version already built for your Python 2.5 On the site : http://org.csail.mit.edu/pybluez/release/PyBluez-0.9.1.win32-py2.5.exe From mkobrien at gmail.com Sat Feb 3 02:20:29 2007 From: mkobrien at gmail.com (Michael O'Brien) Date: 2 Feb 2007 23:20:29 -0800 Subject: using numpy to do linear algebra Message-ID: <1170487229.700734.80930@k78g2000cwa.googlegroups.com> Hola~ I have a large array of points (over a million). I would like to multiply each point in the array by a 4x4 matrix. I keep thinking there should be an easy way to do this using numpy, but I can't figure out the mojo to do it. Is that possible? MO From operagasten at gmail.com Mon Feb 12 11:25:18 2007 From: operagasten at gmail.com (Gasten) Date: 12 Feb 2007 08:25:18 -0800 Subject: Hacking in python In-Reply-To: <1171239487.440891.254860@a34g2000cwb.googlegroups.com> References: <1171239487.440891.254860@a34g2000cwb.googlegroups.com> Message-ID: <1171297517.922354.300640@k78g2000cwa.googlegroups.com> On Feb 12, 1:18 am, Marshill... at gmail.com wrote: > On Feb 10, 5:25 pm, "Geoff Hill" wrote: > > > The word "hack" can be known as a "smart/quick fix" to a problem. > > Giving the benefit of the doubt here, perhaps Enes Naci saw this > article:http://www.hetland.org/python/instant-hacking.phpand got > some strange idea about confusing programming with breaking into > computer systems. Maybe. It's probably more likely that he have stumbled upon this: http://wwwu.edu.uni-klu.ac.at/epirker/unix/hacker-howto.html , or any other version (That's my favourite, by the way). It says that Python is a good program to start with on the journey to become a hacker. Gasten From gagsl-py at yahoo.com.ar Mon Feb 12 13:11:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 15:11:30 -0300 Subject: string.replace non-ascii characters References: Message-ID: En Mon, 12 Feb 2007 07:44:14 -0300, Duncan Booth escribi?: > "Gabriel Genellina" wrote in triplicate: > >> If I were paid for the number of lines *written* that would not be a >> great deal :) > > You don't by any chance get paid by the number of posts to c.l.python? I post a few messages but certainly I'm not the most prolific poster here! -- Gabriel Genellina From bearophileHUGS at lycos.com Fri Feb 2 17:34:24 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Feb 2007 14:34:24 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170429433.258613.320600@a75g2000cwd.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> <1170429433.258613.320600@a75g2000cwd.googlegroups.com> Message-ID: <1170455664.825637.267280@h3g2000cwc.googlegroups.com> Paddy: >>> _ = [d[x0].append(x1) for x0,x1 in data] I think that you probably want: for text, num in data: d[text].append(num) ardief: > thanks to everyone for the help, and the speed of it! It's really > useful and I will spend some time working on understanding the code > you posted. I'd be so lost without this group... If you have Python 2.5, and if you don't have particular requirements, I think the best solution is Paddy's. Bye, bearophile From http Mon Feb 5 15:11:14 2007 From: http (Paul Rubin) Date: 05 Feb 2007 12:11:14 -0800 Subject: alias for data member of class instance? References: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> Message-ID: <7xwt2wcql9.fsf@ruckus.brouhaha.com> "Sean McIlroy" writes: > self.y = ALIAS(self.x) ## FEASIBLE ? The closest thing is probably to use @property. From deets at nospam.web.de Mon Feb 5 06:00:45 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Feb 2007 12:00:45 +0100 Subject: python references References: <1170670211.817241.127310@v33g2000cwv.googlegroups.com> Message-ID: <52oh2tF1pnk8tU1@mid.uni-berlin.de> dustin.getz at gmail.com wrote: >>>> from Numeric import zeros >>>> p=zeros(3) >>>> p > array([0,0,0]) >>>> p[0] > 0 >>>> x=p[0] >>>> x=10 >>>> p > array([0,0,0]) #actual behavior > #array([10,0,0]) #desired behavior > > I want x to be a C++-esque reference to p[0] for convenience in a > vector3 class. i dont want accessor methods. i know python can do > this, but it's been a long time since I used it and am unsuccessful in > my googling and docreading. a little help please? Nope, python can't do this. Diez From edreamleo at charter.net Fri Feb 16 09:43:54 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 08:43:54 -0600 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: > print is only a problem if you expect your code to work under both Python > 2.x and 3.x. Exactly. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tinaweb at bestemselv.com Thu Feb 8 02:53:16 2007 From: tinaweb at bestemselv.com (Tina I) Date: Thu, 08 Feb 2007 08:53:16 +0100 Subject: Calling J from Python In-Reply-To: <1170874782.600836.210670@a34g2000cwb.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> <1170796103.766866.18320@a34g2000cwb.googlegroups.com> <1170861935.779969.52980@v33g2000cwv.googlegroups.com> <1170874782.600836.210670@a34g2000cwb.googlegroups.com> Message-ID: <2ZKdnYNMboxxS1fYRVnzvA@telenor.com> Gosi wrote: > On Feb 7, 3:46 pm, Marc 'BlackJack' Rintsch wrote: >> In <1170861935.779969.52... at v33g2000cwv.googlegroups.com>, Gosi wrote: >>> I like to use J for many things and I think that combining Python and >>> J is a hell of a good mixture. >> I was able to follow this sentence up to and including the word "hell"... :-) >> >> Ciao, >> Marc 'BlackJack' Rintsch > > > That is a start. > > "Hell" is also what most example start with as in "Hello something" > Hell in northern countries is very cold. > Hell in middle east is very hot. > I do not know which is your Hell hot or cold. > Hell o ver?ld > It's also a village in Norway: http://en.wikipedia.org/wiki/Hell,_Norway :D From hg at nospam.org Mon Feb 26 07:55:01 2007 From: hg at nospam.org (hg) Date: Mon, 26 Feb 2007 13:55:01 +0100 Subject: Python+Windows specific questions Message-ID: Hi, Do I need the pywin32 extentions to: 1) change the pc system date ? 2) launch a ppp connection ? Thanks, hg From nagle at animats.com Sun Feb 4 21:49:15 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Feb 2007 18:49:15 -0800 Subject: sgmllib bug in Python 2.5, works in 2.4. Message-ID: (Was prevously posted as a followup to something else by accident.) I'm running a website page through BeautifulSoup. It parses OK with Python 2.4, but Python 2.5 fails with an exception: Traceback (most recent call last): File "./sitetruth/InfoSitePage.py", line 268, in httpfetch self.pagetree = BeautifulSoup.BeautifulSoup(sitetext) # parse into tree form File "./sitetruth/BeautifulSoup.py", line 1326, in __init__ BeautifulStoneSoup.__init__(self, *args, **kwargs) File "./sitetruth/BeautifulSoup.py", line 973, in __init__ self._feed() File "./sitetruth/BeautifulSoup.py", line 998, in _feed SGMLParser.feed(self, markup or "") File "/usr/lib/python2.5/sgmllib.py", line 99, in feed self.goahead(0) File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead k = self.parse_starttag(i) File "/usr/lib/python2.5/sgmllib.py", line 291, in parse_starttag self.finish_starttag(tag, attrs) File "/usr/lib/python2.5/sgmllib.py", line 340, in finish_starttag self.handle_starttag(tag, method, attrs) File "/usr/lib/python2.5/sgmllib.py", line 376, in handle_starttag method(attrs) File "./sitetruth/BeautifulSoup.py", line 1416, in start_meta self._feed(self.declaredHTMLEncoding) File "./sitetruth/BeautifulSoup.py", line 998, in _feed SGMLParser.feed(self, markup or "") File "/usr/lib/python2.5/sgmllib.py", line 99, in feed self.goahead(0) File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead k = self.parse_starttag(i) File "/usr/lib/python2.5/sgmllib.py", line 285, in parse_starttag self._convert_ref, attrvalue) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: ordinal not in range(128) The code that's failing is in "_convert_ref", which is new in Python 2.5. That function wasn't present in 2.4. I think the code is trying to handle single quotes inside of double quotes, or something like that. To replicate, run http://www.bankofamerica.com or http://www.gm.com through BeautifulSoup. Something about this code doesn't like big companies. Web sites of smaller companies are going through OK. Also reported as a bug: [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 John Nagle From aahz at pythoncraft.com Tue Feb 6 10:35:19 2007 From: aahz at pythoncraft.com (Aahz) Date: 6 Feb 2007 07:35:19 -0800 Subject: when will python 2.5 take in mainstream? References: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> Message-ID: In article <1170765935.772254.101930 at q2g2000cwa.googlegroups.com>, Ben Sizer wrote: > >It would be great if someone could invest some time in trying to fix >this problem. I don't think I know of any other languages that require >recompilation of libraries for every minor version increase. How do you define "minor version increase"? If you look at the progression from 2.0 through 2.5, it's pretty clear that each version doesn't particularly fit "minor version increase" even though each one only increments by 0.1. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From naci at mac.com Sat Feb 10 09:50:32 2007 From: naci at mac.com (enes naci) Date: Sat, 10 Feb 2007 16:50:32 +0200 Subject: Hacking in python Message-ID: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> i would like to know about hacking in python too whether its illegal or not is not the point and anyway it doesn't mean i'm gong to use it. From robert.kern at gmail.com Mon Feb 19 11:08:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 19 Feb 2007 10:08:57 -0600 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? In-Reply-To: <1171871775.848808.102080@q2g2000cwa.googlegroups.com> References: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> <1171871775.848808.102080@q2g2000cwa.googlegroups.com> Message-ID: openopt at ukr.net wrote: > Ok, thx > But can I somehow determing how many outputs does caller func require? > for example: > MATLAB: > function [objFunVal firstDerive secondDerive] = simpleObjFun(x) > objFunVal = x^3; > if nargout>1 > firstDerive = 3*x^2; > end > if nargout>2 > secondDerive = 6*x; > end > > So if caller wants only > [objFunVal firstDerive] = simpleObjFun(15) > than 2nd derivatives don't must to be calculated with wasting cputime. > Is something like that in Python? Return an object with each of the results objFunVal, firstDerive, and secondDerive as attributes (or a dictionary). Use keyword arguments to inform the function of which ancillary computations it needs to perform. If at all possible, don't change the number of return values. It's annoying to deal with such an API. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bearophileHUGS at lycos.com Thu Feb 22 13:17:11 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Feb 2007 10:17:11 -0800 Subject: JIT (just-in-tme accelerator) for Python - exists or no? In-Reply-To: <1172167441.845600.154270@s48g2000cws.googlegroups.com> References: <1172167441.845600.154270@s48g2000cws.googlegroups.com> Message-ID: <1172168231.391379.291570@p10g2000cwp.googlegroups.com> On Feb 22, 7:04 pm, open... at ukr.net wrote: > Or is any progress going on now? > The JIT in MATLAB or Java seems to be very effective. Have you tried Psyco? Other progress is probably in the PyPy field too. Bye, bearophile From liuwensui at gmail.com Wed Feb 28 14:53:19 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Wed, 28 Feb 2007 14:53:19 -0500 Subject: convert many excel files to pdf in batch Message-ID: <1115a2b00702281153h46aca0j14aa5513b3ff9acb@mail.gmail.com> Dear all, right now, I have 20 something excel reports that need to be converted to pdf and I have pdf write installed on my PC. Is there a way that I can do so in python? From http Thu Feb 1 15:46:55 2007 From: http (Paul Rubin) Date: 01 Feb 2007 12:46:55 -0800 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> Message-ID: <7xd54twqps.fsf@ruckus.brouhaha.com> "Krypto" writes: > The correct answer as told to me by a person is > > (N>>3) + ((N-7*(N>>3))>>3) > > > The above term always gives division by 7 Well, not exactly: [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f(N): return (N>>3) + ((N-7*(N>>3))>>3) ... >>> f(7) 0 >>> f(70) 9 >>> f(700) 98 From troy.melhase at gmail.com Fri Feb 23 16:51:10 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Fri, 23 Feb 2007 12:51:10 -0900 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: > Why do people sometimes use one leading underscore? Many folks like to use the single leading underscore to emphasize that the attribute isn't part of the normal way to use the class or instance. It's bad style in my opinion, but I'm probably in the minority. From aisaac at american.edu Wed Feb 28 07:41:47 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 28 Feb 2007 12:41:47 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01><1172561344.290126.191530@h3g2000cwc.googlegroups.com><3c5Fh.3664$Tg7.2156@trnddc03> Message-ID: Ben Finney writes: > Really, though, adding attributes to an instance is a normal thing to > do in Python, and you've not yet shown why you want that normal > functionality to be special-cased here. I accept your earlier point that if an interface changes one can just trap use of the old interface. But I remain interested in preventing dynamic attribute creation in particular cases. I have not tried to argue that dynamic attribute creation can be dangerous for a couple reasons. - There is no reason to expect this list to be receptive. - I do not have the experience to make a general argument. - I do not always find it a problem, but only in certain situations. However I will observe that - entire languages are structured on the premise that dynamic attribute creation can be hazardous - debuggers watch out for dynamic attribute creation, which tells us it is a common source of bugs - I sincerely doubt that anyone who has written more than a couple scripts in Python has never accidentally created an attribute dynamically while intending to assign to an existing attribute. I know the response: write good unit tests. OK, but right now I am writing code where this restriction will serve as a reasonable error check, and the design I offered allows very easy removal of the restriction in the future. Say, once I have written adequate unit tests. Alan From openopt at ukr.net Thu Feb 22 06:49:03 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 22 Feb 2007 03:49:03 -0800 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? Message-ID: <1172144943.794384.73270@s48g2000cws.googlegroups.com> I don't know to which forum should I post the message I hope someone related to the Python kernel development will read & consider the idea I'm (a former? meanwhile not sure) MATLAB user & it's very annoing typing each time for example while i: print i ... instead of while i print i ... of course if all is written in a single line ':' I guess should not be omited Thank you for you suggestions. Sorry my bad English. WBR, Dmitrey From jstroud at mbi.ucla.edu Mon Feb 12 01:53:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 11 Feb 2007 22:53:01 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: <7xbqjzud45.fsf@ruckus.brouhaha.com> References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> <7xbqjzud45.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "agent-s" writes: > >>Basically I'm programming a board game and I have to use a list of >>lists to represent the board (a list of 8 lists with 8 elements each). >>I have to search the adjacent cells for existing pieces and I was >>wondering how I would go about doing this efficiently. Thanks > > > You're getting a bunch of Pythonic suggestions which are easy to > understand though not so efficient. If you're after efficiency you > might look at a book like Welsh and Baczynskyj "Computer Chess II" for > some techniques (warning, this is a rather old book though) and > program in a closer-to-the-metal language. One common approach these > days is "bit boards". Basically you represent the board state as a > bunch of 64-bit words, one bit per square. So for checking occupancy, > you'd have a word having the bits set for occupied squares. If you > only want to check adjacent squares (king moves), you could have a > bunch of bit masks (one for each square) with bits set only for the > adjacent squares (similarly for bishop moves, rook moves, etc.) Then > to check adjacency you'd mask off the appropriate bits for that > square, then AND it against the occupancy word. Normally you'd have > separate occupancy words for your own pieces and your opponent's. In defense of the less efficient suggestions, he did say he had to use a list of lists. But what you describe is pretty cool. James From paddy3118 at netscape.net Sat Feb 3 01:02:00 2007 From: paddy3118 at netscape.net (Paddy) Date: 2 Feb 2007 22:02:00 -0800 Subject: python bracket In-Reply-To: References: Message-ID: <1170482520.770997.311690@m58g2000cwm.googlegroups.com> On Feb 3, 5:48 am, fatwallet... at yahoo.com wrote: > there is no bracket in python > > how can i know where a loop or a function ends? Hi fatwallet, Please, please, please, peruse the following: http://wiki.python.org/moin/BeginnersGuide There is lots in their to get you started and up-and-running in Python in a much quicker time than posting very elementary questions to a newsgroup. (Although we value your interest). Welcome to Python by the way. - Paddy. From __peter__ at web.de Fri Feb 9 05:27:57 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Feb 2007 11:27:57 +0100 Subject: from __future__ import absolute_import ? References: Message-ID: Ron Adam wrote: > Peter Otten wrote: >> Ron Adam wrote: >> >>> >>> work >>> | >>> |- foo.py # print "foo not in bar" >>> | >>> `- bar >>> | >>> |- __init__.py >>> | >>> |- foo.py # print "foo in bar" >>> | >>> |- absolute.py # from __futer__ import absolute_import >>> | # import foo >>> | >>> `- relative.py # import foo >>> >>> >>> * Where "work" is in the path. >>> >>> >>> (1) >>> >>> C:\work>python -c "import bar.absolute" >>> foo not in bar >>> >>> C:\work>python -c "import bar.relative" >>> foo in bar >>> >>> >>> (2) >>> >>> C:\work>python -m "bar.absolute" >>> foo not in bar >>> >>> C:\work>python -m "bar.relative" >>> foo not in bar >>> >>> >>> (3) >>> >>> C:\work>python >>> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit >>> (Intel)] on win 32 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import bar.absolute >>> foo not in bar >>> >>> import bar.relative >>> foo in bar >>> >>> >>> (4) >>> >>> C:\work>cd bar >> >> A path below the package level is generally a good means to shoot >> yourself in the foot and should be avoided with or without absolute >> import. > > Seems so. :-/ > > >>> C:\work\bar>python -c "import bar.absolute" >>> foo in bar >>> >>> C:\work\bar>python -c "import bar.relative" >>> foo in bar >>> >>> >>> (5) >>> >>> C:\work\bar>python >>> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit >>> (Intel)] on win 32 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import bar.absolute >>> foo in bar >>> >>> import bar.relative >>> foo in bar >>> >>> >>> >>> >>> >>> Case (2) seems like it is a bug. >> >> I think so, too. > > This one is the reasons I had trouble figuring it out. I was using the -m > command option when I tried to test it. > > There is a bug report on absolute/relative imports already. I'm not sure > if > this particular item is covered under it or not. Doesn't sound like it as > the bug report address the relative aspects of it. > > >>> Why not also have (4), and (5) do the same as cases (1) and (3)? >> >> The work/bar directory is the current working directory and occurs in the >> path before the work directory. > > Yes. Unfortunately this is a side effect of using the os's directory > structure > to represent a python "package" structure. If a package was represented > as a > combined single file. Then the working directory would always be the > package directory. > > > > When bar.absolute imports foo python is > > unaware that work/bar/foo.py is part of the bar package. > > Umm.... isn't the "bar" stuck on the front of "bar.absolute" a pretty > obvious > hint. ;-) > > If you run the module directly as a file... > > python bar/foo.py > or python foo.py > > Then I can see that it doesn't know. But even then, it's possible to find > out. > ie... just check for an __init__.py file. > > Python has a certain minimalist quality where it tries to do a lot with a > minimum amount of resources, which I generally love. But in this > situation that > might not be the best thing. It would not be difficult for python to > detect if > a module is in a package, and determine the package location. With the > move to explicit absolute/relative imports, it would make since if python > also were a little smarter in this area. I have not used the new import behaviour seriously, but -- I think I like it :-) >>> in cases (4) and (5), that is the result I would expect if I did: >>> >>> import absolute # with no 'bar.' prefix. >>> import relative >>> >>> >>> From what I understand, in 2.6 relative imports will be depreciated, >>> and in 2.7 >>> they will raise an error. (providing plans don't change) >>> >>> Would that mean the absolute imports in (4) and (5) would either find >>> the 'foo not in bar' or raise an error? >> >> No, in 1, 3 -- and 2 if the current behaviour is indeed a bug. This is >> only for the relative import which would have to be spelt >> >> from . import foo > > Was that a 'yes' for exampels 4 and 5, since 1,2 and 3 are 'no'? (4) and (5) are misconfigurations, IMHO. >> in an absolute-import-as-default environment; >> >> import foo >> >> would always be an absolute import. > > But what is the precise meaning of "absolute import" in this un-dotted > case? > > Currently it is: > > "A module or package that is located in sys.path or the current > directory". > > But maybe a narrower interpretation may be better?: > > "A module or package found in sys.path, or the current directory > and is *not* in a package." You'd have to add a not-in-package test to every import - I don't think it's worth the effort. > If it's in a package then the dotted "absolute" name should be used. > Right? Either that or the full path. The dotted path makes it easy to move the module between packages. > I guess what I'm getting at, is it would be nice if the following were > always true. > > from __import__ import absolute_import > > > import thispackage.module > import thispackage.subpackage > > # If thispackage is the same name as the current package, > # then do not look on sys.path. > > > import otherpackage.module > import otherpackage.subpackage > > # If otherpackage is a different name from the current package, > # then do not look in this package. > > > import module > import package > > # Module and package are not in a package, even the current one, > # so don't look in any packages, even if the current directory is > # in this (or other) package. > > > If these were always true, :-) I think it avoid some situations where > things don't work, or don't work like one would expect. > > In addition to the above, when executing modules directly from a directory > inside a package, if python were to detect the package and then follow > these > same rules. It would avoid even more surprises. While you are editing > modules in a package, you could then run them directly and get the same > behavior you get if you cd'd out of the package and then ran it. > > All in all, what I'm suggesting is that the concept of a package (type) be > much > stronger than that of a search path or current directory. And that this > would add a fair amount of reliability to the language. I think if you go that way, ultimately you will need some kind of package registry. I expect that the new import behaviour will get you 99 percent there with one percent of the hassle. But we will see... Peter From john.pye at gmail.com Mon Feb 19 06:27:50 2007 From: john.pye at gmail.com (John Pye) Date: 19 Feb 2007 03:27:50 -0800 Subject: 'import dl' on AMD64 platform In-Reply-To: References: <1171757251.224765.171800@s48g2000cws.googlegroups.com> Message-ID: <1171884470.410211.311270@v33g2000cwv.googlegroups.com> On Feb 19, 6:30 am, Nick Craig-Wood wrote: > John Pye wrote: > > application from running on the Debian Etch AMD64 platform. > > It seems that the 'dl' module is not available on that platform. The > > only reason I need the 'dl' module, however, is for the values of > > RTLD_LAZY etc, which I use with sys.setdlopenflags() in order to make > > my imported SWIG module share its symbols correctly with more deeply- > > nested plugin modiles in my C-code layer. > > > I wonder if there is a workaround for this -- perhaps another way to > > access the values of those RTLD flags? > > Read stuff out of /usr/include/bits/dlfcn.h ? > > It seems to be a constant 1 anyway > > #define RTLD_LAZY 0x00001 > > You could try compiling the dl module by hand. Well yes, and that's the workaround I came up with: for systems that don't provide the 'dl' module, I just default to the values I found on my linux (ubuntu) system. This is a nasty hack however. I wonder if anyone could say why the Debian people left out this important module from their AMD64 platform? Cheers JP From horpner at yahoo.com Fri Feb 2 09:01:46 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 15:01:46 +0100 Subject: Overloading the tilde operator? References: Message-ID: On 2007-02-02, Ben Finney wrote: > James Stroud writes: >> Ben Finney wrote: >> > The Python runtime parser is designed to parse Python, not >> > some arbitrary language that someone chooses to implement in >> > Python. >> >> You haven't addressed why the limitation isn't arbitrary. > > Good thing I wasn't trying to do that, then. I was pointing out > the source of the limitation. > > The Python syntax parser must follow the rules of the Python > language. If you accept that premise, it follows that the '~' > operator is unary only. If you *don't* accept that premise, I > have no help to offer. There's been only one (or two?) languages in history that attempted to provide programmers with the ability to implement new infix operators, including defining precedence level and associativity (I can't think of the name right now). C++, for example, works the same way as Python here. You can override most of the operators, but you cannot change their arity, associativity, or precedence level. -- Neil Cerutti Let us join David and Lisa in the celebration of their wedding and bring their happiness to a conclusion. --Church Bulletin Blooper From simon at brunningonline.net Wed Feb 14 12:29:26 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 14 Feb 2007 17:29:26 +0000 Subject: list of range of floats In-Reply-To: References: Message-ID: <8c7f10c60702140929u2116c0aev259d4a221580d12a@mail.gmail.com> On 2/14/07, Steve wrote: > I'm trying to create a list range of floats and running into problems. > I've been trying something like: > > a = 0.0 > b = 10.0 > > flts = range(a, b) > > fltlst.append(flts) > > When I run it I get the following DeprecationWarning: integer argument > expected, got float. How can I store a list of floats? There would be an *enormous* number of floats between zero and ten. Do you really want all of them in your list? I hope you have a few terrabytes of RAM... Or do you just want the integer values as floats? fits = list(float(a) for a in range(0, 10)) -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 7 20:43:15 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 08 Feb 2007 02:43:15 +0100 Subject: help on packet format for tcp/ip programming References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> Message-ID: <52vdh6F1qp2n6U1@mid.individual.net> rattan at cps.cmich.edu wrote: > I want a specific packet format for packet exchange between a > client server across the network. For example frame format > as a python class could be: > class Frame: > def __init__(self, buffer=None, count=0, offset=0): > self.buffer = buffer > self.count = count > self.offset = offset > the question is how to convert it to a byte stream so that format > of count and offset also becomes a sequence of bytes. Try struct. Regards, Bj?rn -- BOFH excuse #208: Your mail is being routed through Germany ... and they're censoring us. From gagsl-py at yahoo.com.ar Mon Feb 19 01:40:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 03:40:58 -0300 Subject: bluetooth on windows....... References: <1171865073.564109.240970@q2g2000cwa.googlegroups.com> Message-ID: En Mon, 19 Feb 2007 03:04:33 -0300, srj escribi?: > i've been trying to access Bluetooth via python in windows Xp. > py bluez for windows required something called _msbt. > i'm running python 2.5. some problem with vb 7.1 compatibility. > > what do i do to get bluetooth up and running on > Xp? Python extensions must match the Python version up to the second digit. You have 3 choices: - try to find a PyBluez version already built for your Python 2.5 - install Python 2.4 and use the 2.4 version of PyBluez - recompile the extension yourself for 2.5 -- Gabriel Genellina From wolf_tracks at invalid.com Fri Feb 2 22:03:09 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 03 Feb 2007 03:03:09 GMT Subject: Numeric and PIL Files? Message-ID: I'm looking at some files that are related to Python: Python-2.4.2.msi Numeric-24.2.win32-py2.4.exe PIL-1.1.5.win32-py2.4.exe What are the three files? msi is the install file for MS, but what are the other two, and where can I find them? The first one no longer seems available on the site. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet The obituary of Alfred Russel Wallace, a prolific writer to the end of his life in his 90s and contemporary of Charles Darwin, read "... he laid his pen aside only to die." -- Web Page: From jonc at icicled.net Mon Feb 5 12:24:00 2007 From: jonc at icicled.net (Jonathan Curran) Date: Mon, 5 Feb 2007 11:24:00 -0600 Subject: Will Python Run On Microsoft Vista? In-Reply-To: <1170695324.106530.157720@v45g2000cwv.googlegroups.com> References: <1170695324.106530.157720@v45g2000cwv.googlegroups.com> Message-ID: <200702051124.00109.jonc@icicled.net> On Monday 05 February 2007 11:08, slogging_away wrote: > I know, I know - flame away but its not clear to me if Python will run > on a system running Microsoft Vista. Is anyone successfully running > Python on Vista? If so, is it what version of Python are you > running? I'm ordering a new system and if Python won't work on Vista > then it will definately influence the OS selection. > > Thanks in advance! I don't see why Python wouldn't work. The 2.5 version clearly has a version for Vista albeit its the x64 Edition. If you downloaded the regular version (x86) then I assume it would work just fine. D/L an evaluation copy of Vista and try it yourself. - Jonathan From gnewsg at gmail.com Mon Feb 12 10:38:28 2007 From: gnewsg at gmail.com (billie) Date: 12 Feb 2007 07:38:28 -0800 Subject: WindowsNT user authentication In-Reply-To: References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> Message-ID: <1171294708.261232.18290@p10g2000cwp.googlegroups.com> On 12 Feb, 14:45, Tim Golden wrote: > billie wrote: > > Hi there, > > I would like to submit a username/password pair to a Windows NT > > workstation and find out if it's valid. > > Moreover I would like to get the user's home directory given the > > username. > > Does it is possible to do that by using pywin32 extension? > > http://timgolden.me.uk/python/win32_how_do_i/check-a-users-credential... > > There are a few caveats (and there are other ways, too). This > one is pretty simple, though. > > HTH > TJG Thanks, it shoulda work. Do you got any idea about how getting user's home directory? From michele.simionato at gmail.com Sun Feb 18 08:22:26 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Feb 2007 05:22:26 -0800 Subject: Getting a class name In-Reply-To: <1171801487.767555.14150@v33g2000cwv.googlegroups.com> References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <_DJBh.20322$K8.18088@news.edisontel.com> <1171801487.767555.14150@v33g2000cwv.googlegroups.com> Message-ID: <1171804946.810703.45810@a75g2000cwd.googlegroups.com> On Feb 18, 1:24 pm, "Fuzzyman" wrote: > Why is the __name__ attribute not available to the instance? Why don't > normal lookup rules apply (meaning that a magic attribute will be > looked up on the class for instances) ? Because __name__ isn't really an attribute, it is a descriptor defined on the metaclass: >>> type(type.__dict__['__name__']) See http://users.rcn.com/python/download/Descriptor.htm for a guide to descriptors, and the papers by me and David Mertz for a guide to metaclasses. Michele Simionato From mbm at mediamonger.ch Thu Feb 8 07:23:08 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Thu, 08 Feb 2007 13:23:08 +0100 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <45CB162C.10704@mediamonger.ch> Srikanth schrieb: > Yes, > > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. > > Thanks, > Srikanth > http://www.serpia.org/spe http://www.die-offenbachs.de/detlev/eric.html From erinhouston at gmail.com Wed Feb 28 11:04:37 2007 From: erinhouston at gmail.com (ina) Date: 28 Feb 2007 08:04:37 -0800 Subject: Running Python scripts from BASH In-Reply-To: References: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> Message-ID: <1172678677.297053.57340@z35g2000cwz.googlegroups.com> On Feb 27, 11:16 pm, "Hendrik van Rooyen" wrote: > "Ishpeck" wrote: > > 8<--------------- a bash problem --------------------- > > If it were Python, the advice would have been to use the > print statement to figure out what the content of the > variables were. > > As it is Bash, you may have to stoop to something like > echo to see what is in $i... > > hth - Hendrik When you print the string in bash it looks correct. It isn't until you try to execute it you have the problem. os.system is the solution to this problem anyway. From S.Mientki-nospam at mailbox.kun.nl Sat Feb 10 07:14:06 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 10 Feb 2007 13:14:06 +0100 Subject: pycallgraph 0.2.0 In-Reply-To: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> References: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> Message-ID: <5d727$45cdb6fb$d443bb3a$6935@news.speedlinq.nl> Gerald Kaszuba wrote: > Hi > > I just released a new version of pycallgraph. It has many improvements > over 0.1.0. Here is an example of a call graph made in pycallgraph > 0.2.0: > http://pycallgraph.slowchop.com/pycallgraph/wiki/RegExpExample > > There are more examples on the web site: > http://pycallgraph.slowchop.com/ > > The changes are: > * Windows access denied bug fixed > * graph uses different colours depending on the number of calls made > to the function > * graph settings and look are very customisable > * exclude and include filters > * stop_trace() is not required anymore, it is called automatically by > make_graph() > * will throw an exception if there is an error from dot/neato > * removed obvious use of __main__ as the module name > * added some examples > > There is no documentation yet but if you browse the source you'll be > able to figure out a lot. > > Enjoy! > > Gerald > looks very good Gerald, thanks ! My first test was terrible: a file of 800kB was created, Trying to view it, resulted in the following: - Paint Shop Pro told me it was not a valid PNG file, - Mozilla crashed after 5 minutes, - GIMP gave me a preview after half an hour ;-) So a few suggestions: - is there a way to limit the number of nodes ? - "pycallgraph." nodes are "non-information" (maybe you can find another way to place your "signature" ;-) - how do I exclude modules/files/objects (sorry I'm still a newbie in Python) cheers, Stef Mientki From johnjsal at NOSPAMgmail.com Fri Feb 2 11:29:52 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 02 Feb 2007 11:29:52 -0500 Subject: Sorting a list In-Reply-To: <45c25f5f$0$29465$426a34cc@news.free.fr> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> <45c254a2$0$674$426a34cc@news.free.fr> <45c25d9a$0$27590$c3e8da3@news.astraweb.com> <45c25f5f$0$29465$426a34cc@news.free.fr> Message-ID: <45c36617$0$29527$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: > John Salerno a ?crit : > (snip) > >> Oh I didn't sort then reverse, I just replaced sort with reverse. >> Maybe that's why! > > Hmmm... Probably, yes... > > !-) lol, this is what a couple months away from python does to me! From mensanator at aol.com Sat Feb 10 01:31:43 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 9 Feb 2007 22:31:43 -0800 Subject: pygame and python 2.5 In-Reply-To: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> Message-ID: <1171089103.528193.157800@v33g2000cwv.googlegroups.com> On Feb 9, 11:39???am, "Ben Sizer" wrote: > On Feb 9, 1:48 pm, "siggi" wrote: > > > @Ben Sizer > > Lucky I spotted this... > > > As a Python (and programming ) newbie ?allow me a ?- certainly naive - > > question: > > > What is this time consuming part of recompiling an extension, such as > > Pygame, from source code to Windows? Is it a matter of spare time to do the > > job? Or do you have to wait for some Windows modules that are necessary for > > compiling? > > The problem is something like this: > ?- Python extensions written in C require recompilation for each new > version of Python, due to Python limitations. > ?- Recompiling such an extension requires you to have a C compiler set > up on your local machine. > ?- Windows doesn't come with a C compiler, so you have to download > one. > ?- The compiler that Python expects you to use (Visual Studio 2003) is > no longer legally available. > ?- The other compiler that you can use (MinGW) is requires a slightly > convoluted set of steps in order to build an extension. > > Hopefully in the future, some of those convoluted steps will be fixed, > but that requires someone putting in the effort to do so. As is often > the case with Python, and indeed many open source projects, the people > who are knowledgeable enough to do such things usually don't need to > do them, as their setup already works just fine. So you're saying the knowledgeable people's attitude is "fuck everyone else as lomg as it's not MY problem"? And you people complain about Microsoft. > > -- > Ben Sizer From jacob.rael at gmail.com Fri Feb 23 12:03:21 2007 From: jacob.rael at gmail.com (Jacob Rael) Date: 23 Feb 2007 09:03:21 -0800 Subject: c_string missing from ctypes? Message-ID: <1172250201.092615.52940@s48g2000cws.googlegroups.com> Hello, I was following along with this site: http://www.brunningonline.net/simon/blog/archives/000659.html and I got a error. It boils down to: ==================== In [9]: import ctypes In [10]: dir(ctypes.c_string) --------------------------------------------------------------------------- Traceback (most recent call last) P:\ in () : 'module' object has no attribute 'c_string' ==================== I google ctypes.c_string and many people use it. I am using python 2.5 with ctypes version: 1.0.1 on a windows machine. I have to admit I don't know where ctypes came from. I tried to re- install it but the window binaries only support 2.4. Also: http://starship.python.net/crew/theller/ctypes/tutorial.html seems dead. An info is greatly appreciated. jr From hinnc at yahoo.com Mon Feb 5 12:08:44 2007 From: hinnc at yahoo.com (slogging_away) Date: 5 Feb 2007 09:08:44 -0800 Subject: Will Python Run On Microsoft Vista? Message-ID: <1170695324.106530.157720@v45g2000cwv.googlegroups.com> I know, I know - flame away but its not clear to me if Python will run on a system running Microsoft Vista. Is anyone successfully running Python on Vista? If so, is it what version of Python are you running? I'm ordering a new system and if Python won't work on Vista then it will definately influence the OS selection. Thanks in advance! From jstroud at mbi.ucla.edu Fri Feb 9 19:17:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 09 Feb 2007 16:17:31 -0800 Subject: Matching Strings In-Reply-To: References: Message-ID: rshepard at nospam.appl-ecosys.com wrote: > I'm not sure how to change a string so that it matches another one. > > My application (using wxPython and SQLite3 via pysqlite2) needs to compare > a string selected from the database into a list of tuples with another > string selected in a display widget. > > An extract of the relevant code is: > > selName = self.polTree.GetItemText(selID) > ... > for item in self.appData.polNat: > print 'Item: ', item, '\n', 'selName: ', selName, '\n' > if item == selName: > print '***** ', self.appData.polNat[1] > > The last comparison and print statement never work because the strings are > presented this way: > > Item: (u'ground water',) > selName: ground water > > What do I need to do to 'Item' to strip the parentheses, unicode symbol, > single quotes, and comma? Do I want 'raw' output? If so, how do I specify > that in the line 'if item == selName:'? > > TIA, > > Rich Assuming item is "(u'ground water',)" import re item = re.compile(r"\(u'([^']*)',\)").search(item).group(1) James From usenet200701 at tobyinkster.co.uk Mon Feb 5 19:52:30 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Tue, 6 Feb 2007 00:52:30 +0000 Subject: lambda functions ? References: Message-ID: Maxim Veksler wrote: > And what is the "f" object? An integer? a pointer? an Object? A function. -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From naima.mans at gmail.com Wed Feb 28 04:13:53 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 28 Feb 2007 01:13:53 -0800 Subject: spawnl and waitpid In-Reply-To: References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> Message-ID: <1172654033.173702.248160@h3g2000cwc.googlegroups.com> On 27 f?v, 19:31, Dennis Lee Bieber wrote: > On 27 Feb 2007 05:39:51 -0800, naima.m... at gmail.com declaimed the > following in comp.lang.python: > > > > > On 27 f?v, 12:27, Thinker wrote: > > > -----BEGIN PGP SIGNED MESSAGE----- > > > > > Your program will be blocked here until child process being terminated. > > > You should print your messages before this line. > > > i have tried as you said (cf bellow) and same result... > > No, you did NOT do as was suggested (unless you misunderstood which > line "before this" meant. > > > is there any link which explain how a server Web read script and send > > the answer ? > > > ------------------------------------------------------------------------- > > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > > \python.exe","python","Main.py") > > ret = os.waitpid(pid,0) > > As soon as you execute os.waitpid(), your script WAITS. NOTHING > after that point will happen until the process you are waiting on exits. > > > print """please wait ....""" > > sys.stdout.flush() > > # retourne le process id > > if ( ret[1] != 0): > > print """ wait %i """ %ret[1] > > sys.stdout.flush() > > else: > > print """ end %i """ %ret[1] > > sys.stdout.flush() > > pid = os.spawnl(os.P_NOWAIT, > "c:\\python25\\python.exe", > "python", > "Main.py") #apparently a Windows OS > print "Please wait ..." > sys.stdout.flush() > ret = os.waitpid(pid, 0) > > if ret[1]: > print "Non-zero exit code: %s %s" % (ret[1], ret[0]) > else: > print "Successful exit" > sys.stdout.flush() > > {I'm presuming a 0 return code means success... VMS used 1 for success > and 0 for failure [actually, odd numbers were informational status, even > numbers were error status]} > > > --------------------------------------------------------------------------- > > thanks > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ hello thanks a lot.. sorry for misunderstanding, my english isn't good (i'm french). i have tried like this: ---------------------------------------------- #! C:/Python25/python.exe # -*- coding: cp1252 -*- import cgitb; cgitb.enable() import os,sys print "Content-Type: text/html" print pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python","Main.py") print "please wait.." sys.stdout.flush() ret = os.waitpid(pid,0) # retourne le process id if ret[1]: print "Non-zero exit code: %s %s" % (ret[1], ret[0]) else: print "Successful exit" sys.stdout.flush() -------------------------------------------------------- and the result: At the end of the script execution it write: ==>>>> please wait.. Successful exit The browser doesn't let the script executing on background to write the message at once.. it waits the end. what happend? From exarkun at divmod.com Fri Feb 23 10:01:23 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 23 Feb 2007 10:01:23 -0500 Subject: Creating a daemon process in Python In-Reply-To: Message-ID: <20070223150123.25807.87474186.divmod.quotient.30418@ohm> On Fri, 23 Feb 2007 08:30:07 -0600, Nick Craig-Wood wrote: >Eirikur Hallgrimsson wrote: > > [snip] > >> if (not os.fork()): >> # hang around till adopted by init >> ppid = os.getppid() >> while (ppid != 1): >> time.sleep(0.5) >> ppid = os.getppid() > >Why do you need hang around until adopted by init? I've never see >that in a daemonize recipe before? > I think it simplifies some signal handling logic. I'd never seen it before in a deamonizer either, but it caught my eye in this one. I haven't had time to investigate further though. I hope Eirikur will explain. :) Jean-Paul From krypto.wizard at gmail.com Wed Feb 7 13:14:19 2007 From: krypto.wizard at gmail.com (Krypto) Date: 7 Feb 2007 10:14:19 -0800 Subject: Suggestions on Starting Python Project on P2P streaming Message-ID: <1170872058.943096.83610@j27g2000cwj.googlegroups.com> I am 3 months old to python and I have done some small projects. I want to build a Peer to Peer streaming client ..something like BitTorrent. I know it is daunting but I got to start somewhere. Please come easy on me. What I want in my client program is that client software logs on to some P2P streaming session from a list, connects to several computers using TCP connection (protocol may vary in future), obtain stream from other computers and also send stream to others and play the obtained media stream on to some media playaer like xmms or any music player. My obstacles... 1. I have very little experice in network programming ..... some tips here are very welcome.... Please dont come hard on me. 2. I am not sure how stream content is gathered by client and sent to media player..... suggestions welcome. 3. I have not managed this big project so I am not sure about how to manage the code....suggestions welcome. This newbiew appreiates your tips. Any comments are welcome. Thanks From sjmachin at lexicon.net Tue Feb 13 04:45:19 2007 From: sjmachin at lexicon.net (John Machin) Date: 13 Feb 2007 01:45:19 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> <1171264811.509582.224870@p10g2000cwp.googlegroups.com> Message-ID: <1171359919.372059.148820@a75g2000cwd.googlegroups.com> On Feb 13, 4:57 pm, "Hendrik van Rooyen" wrote: > "John Machin" wrote: > > > Now for the algorithm: all of that testing to see if you are about to > > sail off the end of the world is a bit ugly and slow. You can use bit- > > bashing, as Paul suggested, even though it's on Steven D'Aprano's list > > of 6 deadly sins :-) > > Thou shallt not bit - bash > > What are the other five? """ ... regexes have their place, together with pointer arithmetic, bit manipulations, reverse polish notation and goto. The problem is when people use them inappropriately ... """ The sixth is never mentioned. Aliter: I can't count. Believe whichever hypothesis you like :-) From jfine at pytex.org Wed Feb 7 13:52:48 2007 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 07 Feb 2007 18:52:48 +0000 Subject: Two mappings inverse to each other: f, g = biject() References: <45C856E4.6090307@pytex.org> <1170795405.214593.187170@s48g2000cws.googlegroups.com> Message-ID: <45CA2000.3040200@pytex.org> bearophileHUGS at lycos.com wrote: >>A google search for biject.py and bijection.py >>produced no hits, so I suspect that this may not >>have been done before. > > > There are few (good too) implementations around, but they are called > bidict or bidirectional dicts. Sometimes I use this implementation, > with few changes: > http://www.radlogic.com.au/releases/two_way_dict.py Thank you for this. You are quite right, a dictionary is a particular type of mapping. A mapping with an inverse is called (at least by me) a bijection. Therefore, as you say, bidict or something similar is correct for a bijection that is based on dictionaries. I had a look at the code in radlogic. There, the design philosophy is to add 'inverse operations' to a dictionary. Thus, it adds a method reversed_items. In my code, I used a different philosophy, which comes down to this. If a mapping is by design a bijection, then it should have an inverse method that gives the inverse mapping. This preserves the symmetry between a mapping and its inverse. (The inverse has an inverse, which is the original mapping.) Therefore, my semantics comes down to f, g = bidict() # Use the better name. assert f = g.inverse assert g = f.inverse and also f[a] = b if and only if g[b] = a By the way, it turns out that a bidict is not what my application needs. But I find it an interesting problem, and time spent on it I do not consider wasted. Best regards Jonathan From lgoh at optonline.net Tue Feb 20 20:39:43 2007 From: lgoh at optonline.net (LG) Date: Tue, 20 Feb 2007 20:39:43 -0500 Subject: code-object Message-ID: Hi, All, >>>code = compile('print "hello everyone, how are you? "', '', 'exec') >>>exec code hello everyone, how are you? >>>print code ", line 1> how to print the code object ? like the one on .pyc Regards LG From sjmachin at lexicon.net Thu Feb 22 19:36:50 2007 From: sjmachin at lexicon.net (John Machin) Date: 22 Feb 2007 16:36:50 -0800 Subject: What is the best queue implemetation in Python? In-Reply-To: References: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> Message-ID: <1172191010.013449.75720@q2g2000cwa.googlegroups.com> On Feb 23, 11:24 am, "John" wrote: > Than C or PASCAL > I mean, list or dictionary in Python are so powerful than the traditional > array. Maybe I can make use of it? Well, you could wite your own queue manager using Python lists, but ... You have this strange reluctance to look in the documentation. Have you tried Google? Try http://docs.python.org/lib/deque-objects.html Or perhaps you want/need the Queue module or the heapq module. *You* find them and *you* work out what is best for *your* needs. If you have a question that you could not answer yourself, then ask it here. HTH, John > > "John Machin" wrote in message > > news:1172190018.915043.200560 at v45g2000cwv.googlegroups.com... > > > On Feb 23, 11:12 am, "John" wrote: > > > I want to write a code for Breadth First Traveral for Graph, which needs > a > > > queue to implement. > > > > I wonder that for such a powerful language as Python, whether there is a > > > better and simpler implementation for a traditional FIFO queue? > > > Better and simpler than *WHAT*? From steve at holdenweb.com Thu Feb 8 11:04:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Feb 2007 16:04:11 +0000 Subject: Simple Interpolation in Numpy? In-Reply-To: <134863FF4EA9A54E8EC307A2F4214566096E0E51@ACCLUST01EVS1.ugd.att.com> References: <134863FF4EA9A54E8EC307A2F4214566096E0E51@ACCLUST01EVS1.ugd.att.com> Message-ID: <45CB49FB.4030706@holdenweb.com> LAPI, VINCENT J, ATTLABS wrote: > Hi, > Please bear with me as I am new to Python and have not done any > programming in about 20 years. I am attempting to do a simple > interpolation of a line's intermediate points given the x,y coordinates > of the line's two endpoints within an Active State Python script that I > am working with. Is there a simple way to do this simple interpolation > in the Active state Python 2.4 that I have or do I need to get Numeric > Python? And where do I get it? > Thanks, > Vince Lapi > You shouldn't really *need* Numeric (NumPy or numpy, nowadays) for a relatively simple problem like that, since the formulae involved are pretty simple. Given known points on the line at (xa, ya) and (xb, yb) then for any point (x, y) on the line we get y = ya + ((x - xa) * (yb - ya))/(xb - xa) So you just need to plug the values for x and the known points into the formula to get the interpolated value of y. If you are interpolating a non-linear formula through a number of samples clearly there'd be a little more jiggery pokery involved to identify the particular interval on which interpolation is required, but nothing horrendous. Numpy, which is derived from the old Numeric code, is at http://numpy.scipy.org/ should you wish to investigate its features. It probably has better-than-linear interpolation algorithms in it. Note that if you decide to download it you should choose the Python 2.4 version - extensions coded in compiled languages are specific to a particular version of the language. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gagsl-py at yahoo.com.ar Thu Feb 8 12:05:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 8 Feb 2007 09:05:51 -0800 Subject: Fwd: Python new user question - file writeline error In-Reply-To: References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <1170887579.160693.78160@a34g2000cwb.googlegroups.com> <813A863A-3D95-47B5-8E54-B6DDF5A57DF5@Milochik.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> Message-ID: <1170954351.593141.94290@v33g2000cwv.googlegroups.com> On 8 feb, 12:41, "Shawn Milo" wrote: > I have come up with something that's working fine. However, I'm fairly > new to Python, so I'd really appreciate any suggestions on how this > can be made more Pythonic. A few comments: You don't need the formatDatePart function; delete it, and replace newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) with newDate = ",%04.4d-%02.2d-%02.2d," % (yearNum,monthNum,dayNum) and before: dayNum, monthNum, yearNum = [int(num) for num in someDate[1:-1].split('/')] And this: outfile.writelines(line) should be: outfile.write(line) (writelines works almost by accident here). You forget again to use () to call the close methods: infile.close() outfile.close() I don't like the final replace, but for a script like this I think it's OK. -- Gabriel Genellina From grahn+nntp at snipabacken.dyndns.org Tue Feb 13 12:20:18 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Feb 2007 17:20:18 GMT Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: On Tue, 13 Feb 2007 06:35:36 +1100, andrew clarke wrote: > On Mon, Feb 12, 2007 at 10:00:51AM -0800, Thomas Nelson wrote: > >> I realize I'm approaching this backwards from the direction most >> people go, but does anyone know of a good c/c++ introduction for >> python programmers? > > Thomas, I sent you a message off-list but it bounced due to your mailbox > being full. > > Short answer: Subscribe to the c-prog at yahoogroups.com mailing list and > ask your C/C++ questions there. Why on earth should he do that, seeing that he seems to post here over Usenet? There are plenty of Usenet groups for both languages. For C++, there are comp.lang.c++ and comp.lang.c++.moderated. Reading the second one has been both useful and enjoyable for me. And to echo what someone else wrote: please don't use the term "C/C++". It makes about the same sense as "Perl/Python" (or "Python/Perl"). /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From jeffrey at fro.man Sun Feb 4 15:28:54 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 04 Feb 2007 12:28:54 -0800 Subject: "Subscribing" to topics? References: <5aoxh.7440$gJ1.6708@newsfe17.lga> <1170618799.354069.327210@h3g2000cwc.googlegroups.com> Message-ID: <12scgfo858gmqca@corp.supernews.com> Mizipzor wrote: > I discovered that Google has a free newsserver, so I > joined this group from there. Sadly, I cant see a feature here that > lets me subscribe to an individual topic, so if anyone else is using > Google groups and know how to do something like this, please tell > me. I don't know about Google Groups, but you may be able to accomplish what you want to do with "filters" provided by your newsreader software. Jeffrey From uymqlp502 at sneakemail.com Tue Feb 20 17:35:54 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 20 Feb 2007 14:35:54 -0800 Subject: setup.py installation and module search path Message-ID: <1172010954.151670.274470@p10g2000cwp.googlegroups.com> When I run setup.py to install a pure python package, is it supposed to automatically set my search path to find the installed modules? Or am I supposed to set my PYTHONPATH variable myself in my .bashrc file? And what if I don't have root priviledge? Then what is supposed to happen? Can anyone give me a clue? Thanks. From openopt at ukr.net Mon Feb 19 07:35:14 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 19 Feb 2007 04:35:14 -0800 Subject: (beginners question) howto set self.field4.subfield8='asdf'? In-Reply-To: References: <1171877794.747825.294890@t69g2000cwt.googlegroups.com> Message-ID: <1171888514.200515.25890@t69g2000cwt.googlegroups.com> Thx but is there any simpleir way, if using not class, but just struct (or something like that, MATLAB equivalent for that one)? I'm thinking of rewriting some optimization solvers (non-smooth, constrained, with (sub)gradients or patterns provided by user) to Python and I don't know currently is it possible to easy convert things like prob = []; prob.advanced.ralg.hs = 1 (so in this line all subfields are generating automatically in MATLAB or Octave) I have huge amount of such lines, and implementing separate class for each one is unreal. Thank you in advance, Dmitrey From B.Ogryczak at gmail.com Thu Feb 15 08:57:45 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 15 Feb 2007 05:57:45 -0800 Subject: list of range of floats In-Reply-To: References: Message-ID: <1171547865.283724.319990@k78g2000cwa.googlegroups.com> On Feb 14, 6:12 pm, Steve wrote: > I'm trying to create a list range of floats and running into problems. I've tried it the easy way. Works. map(float,range(a,b)) From jordan.taylor2 at gmail.com Thu Feb 22 12:47:53 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 22 Feb 2007 09:47:53 -0800 Subject: How can I track/monitor an application and system resources. In-Reply-To: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> References: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> Message-ID: <1172166473.599828.170270@t69g2000cwt.googlegroups.com> On Feb 22, 11:48 am, "richar... at latter.demon.co.uk" wrote: > Hello All, > > I'm a newbie to Python! > > I am trying to develop a program that monitors the performance of an > application. The kind of information I am interested in is the CPU/ > Process/Thread and memory performance. Specifically, I would like to > track the following > > CPU usage > Used Memory on Phone > Free Memory on Phone > Number of Processes running > Number of threads running > Number of Filehandles currently open > Memory used by a process/thread > Process/Thread CPU activity. > > All this under Windows > > Can anyone help me, or direct me to the appriopriate API's so I can > get the above information? > > Does anyone have any other sugestions on what else I could monitor for > a running application? > > Does anyone have any example code they can direct me to? > > Many thanks in advance, > > Richard You will definitely want to check out pywin32api, because it is the best (and most powerful) way to interact with windows through python. Also, if you know any c++, you might search for taskmanager extensions on codeproject.com or look at the msdn on taskmanager to see how it gets all of its information (which is essentially what you want -- a taskmanager). Either way you'll almost defitely need pywin32, so look there first. Cheers, Jordan From tiedon_jano at hotmail.com Thu Feb 22 07:20:44 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 22 Feb 2007 12:20:44 GMT Subject: Finding a tuple in a tuple In-Reply-To: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> References: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> Message-ID: bg_ie at yahoo.com kirjoitti: > Hi, > > Lists say I have the following tuple - > > t1 = ("ONE","THREE","SIX") > > and then the following tuples - > > t2 = ("ONE","TWO","THREE") > > t3 = ("TWO","FOUR","FIVE","SIX") > > t4 = ("TWO",) > > t5 = ("TWO","FIVE") > > What I want to do is return true if any member of tuple t1 is found in > the remaining tuples. > > Therefore - > > 2) ("ONE","TWO","THREE") : TRUE > > 3) ("TWO","FOUR","FIVE","SIX") : TRUE > > 4) ("TWO",) FALSE > > 5) ("TWO","FIVE") > > How do I do this? > > Cheers, > > Barry. > Another variation of the theme: #==================== for t in (t2, t3, t4, t5): for x in t1: if x in t: print True break else: print False #==================== HTH, Jussi From sjmachin at lexicon.net Mon Feb 5 20:31:30 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Feb 2007 17:31:30 -0800 Subject: Decimating Excel files In-Reply-To: References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> Message-ID: <1170725490.828444.138230@v33g2000cwv.googlegroups.com> On Feb 6, 10:46 am, "Gabriel Genellina" wrote: > En Sat, 03 Feb 2007 18:52:10 -0300, mensana... at aol.com > escribi?: > > > On Feb 3, 1:43?pm, gonzlobo wrote: > >> We have a data acquisition program that saves its output to Excel's > >> .xls format. Unfortunately, the programmer was too stupid to write > >> files the average user can read. > > >> I'd like some advice on how to go about: > >> 1. Reading a large Excel file and chop it into many Excel files (with > >> only 65535 lines per file) > > > An Excel sheet only has 65535 lines. Or do yo mean it has > > multiple sheets? > > As I understand the problem, the OP has a program that generates the .xls > files, but it's so dumb that writes files too large for Excel to read. > I'd try the "xlrd" package - it is capable of reading Excel files on any > platform. Thanks for the plug, Gabriel. However xlrd is not the panacea for all evils and all idiocies :-) Excel "file sizes" are limited by the number of rows and columns that a particular version's file format will support in each worksheet. There may be a limit on the maximum number of worksheets in a file, but I've never heard of this as a problem. Before Excel 97 aka 8.0, the limits were 16384 rows x 256 columns. Excel 97 (8.0) up to Excel 2003 (11.0) allow 65536 rows by 256 columns. Excel 2007 aka 12.0 (just released) raises the limits to 2**20 rows x 16384 columns. Let's presume the OP is talking about files written in the format ("BIFF8") that is expected by Excel 97-2003. In cell data records, there are 16 bits for an unsigned row number. If the file writer writes zillions of rows, with row numbers modulo 65536, then not even xlrd can help the OP -- not out of the box; rescue would be possible with a tweaked version *if* the rows were written in sequential order. There are also 16 bits for an unsigned column number. It is possible to write 65536 columns, but I'd guess that Excel would refuse to open the file, or go bananas. In any case the OP's problem seems to be with too many rows. In any case #2, what the OP said was [my emphasis added]: "Unfortunately, the programmer was too stupid to write files *the average user* can read." -- i.e. it's not Excel being grumpy, it's the average user. It would help a great deal if the OP would say what the problem really is ... Cheers, John From NunezD at gmail.com Tue Feb 20 01:17:42 2007 From: NunezD at gmail.com (hiro) Date: 19 Feb 2007 22:17:42 -0800 Subject: file io (lagged values) newbie question Message-ID: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> Hey there, I'm currently doing data preprocessing (generating lagged values for a time series) and I'm having some difficulties trying to write a file to disk. A friend of mine, wrote this quick example for me: ----------------------------------------------------------------------------------------------------------- array = ['1','2','3','4','5','6','7'] lineSize = 4 skip = 4 condition = 1 startIndex = 0 for letter in array: line = [] startIndex = array.index(letter) for indexNum in range(startIndex, startIndex + (skip - 1), 1): #print "first loop" #print if indexNum > (len(array) - 1): break else: line.append(array[indexNum]) #print "startIndex" #print startIndex + skip for indexNum in range(startIndex + skip, (startIndex + lineSize) + 1, 1): #print "second loop" #print if indexNum > (len(array) - 1): break else: line.append(array[indexNum]) print line ---------------------------------------------------------------------------------------------------------------------- which outputs to the console: ['1', '2', '3', '5'] ['2', '3', '4', '6'] ['3', '4', '5', '7'] ['4', '5', '6'] ['5', '6', '7'] ['6', '7'] ['7'] This is exactly what I want and need, but when modified to read and write files from/to disk, I run into problems. example text file for reading: C:\>more kaka.txt 1 2 3 4 5 6 7 tweaked code: ------------------------------------------------------------------------------------------------------------------- f=open('c:/kaka.txt','r') array=f.readlines() f.close() f=open('c:/kakaDump.txt','w') lineSize = 4 skip = 4 condition = 1 startIndex = 0 for letter in array: line = [] startIndex = array.index(letter) for indexNum in range(startIndex, startIndex + (skip - 1), 1): if indexNum > (len(array) - 1): break else: line.append(array[indexNum]) for indexNum in range(startIndex + skip, (startIndex + lineSize) + 1, 1): if indexNum > (len(array) - 1): break else: line.append(array[indexNum]) f.writelines(line) ------------------------------------------------------------------------------------------------------------------------------- C:\>more kakaDump.txt 1 2 3 5 2 3 4 6 3 4 5 74 5 6 5 6 76 77 For those familiar with neural networks, the input file is a time series and the output file needs to have 3 lagged variables for training and a (two time steps ahead) variable for the target. Ie: input file 1 2 3 4 5 6 7 output file 1 2 3 5 2 3 4 6 3 4 5 7 4 5 6 5 6 7 6 7 7 Thanks in advanced, D. From B.Ogryczak at gmail.com Mon Feb 5 10:22:00 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 5 Feb 2007 07:22:00 -0800 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <1170688920.020673.164420@p10g2000cwp.googlegroups.com> On Jan 7, 1:07 am, "time.sw... at gmail.com" wrote: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. > > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? Often it?s a question of efficiency. Function calls in Python are bloody slow. There is no "inline" directive, since it?s intepreted, not compiled. Eg. consider code like that: class MyWhatever: ... def getSomeAttr(self): return self._someAttr def getSomeOtherAttr(self): return self._someOtherAttr [x.getSomeAttr() for x in listOfMyWhatevers if x.getSomeOtherAttr() == 'whatever'] You?d get it running hundreds times faster doing it the "wrong" way: [x._someAttr for x in listOfMyWhatevers if x._someOtherAttr == 'whatever'] From vinjvinj at gmail.com Fri Feb 23 17:36:24 2007 From: vinjvinj at gmail.com (vj) Date: 23 Feb 2007 14:36:24 -0800 Subject: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API In-Reply-To: References: Message-ID: <1172270184.855786.146510@q2g2000cwa.googlegroups.com> Cool. Why is python 2.5 required, will it not work with python 2.4? VJ From sjangity at gmail.com Sat Feb 17 08:27:24 2007 From: sjangity at gmail.com (sqad) Date: 17 Feb 2007 05:27:24 -0800 Subject: how do you expose pylons c variables to javascript functions Message-ID: <1171718844.608381.49230@a75g2000cwd.googlegroups.com> Hi, I am making a javascript call to google maps to get the geocodes of an address. Ok, so its trivial to get the latitude/longitude, but now I want to pass that data via the Pylons MVC framework so that my controllers have access to them. I could get the lat/long by instead going through HTTP via a webservice call, but new problem comes up - how do I now hand off the c variables to the javascript function. Appreciate any help. From jura.grozni at gmail.com Wed Feb 7 21:13:52 2007 From: jura.grozni at gmail.com (azrael) Date: 7 Feb 2007 18:13:52 -0800 Subject: uml and python Message-ID: <1170900832.692717.259160@l53g2000cwa.googlegroups.com> hy guys i've been googling and got several posts, but nothing that is a satisfaction in my eyes. can someone tell me a nice uml diagram tool with python export (if possible nice gui), or at least nice uml tool gpl or freeware (widows) prefered thanks From gianmt at gnome.org Wed Feb 21 16:59:27 2007 From: gianmt at gnome.org (Gian Mario Tagliaretti) Date: 21 Feb 2007 21:59:27 GMT Subject: [Ann] PyGooCanvas 0.6.0 Message-ID: <45dcc0bf$1$17944$4fafbaef@reader1.news.tin.it> I am pleased to announce version 0.6.0 of the Python bindings for Goocanvas. It is available at: https://developer.berlios.de/projects/pygoocanvas/ The bindings are updated with the new Goocanvas API PyGooCanvas 0.6.0 (Feb 19 2007) ================= o Rename and implement latest API changes according to goocanvas 0.6 (Gian Mario) o wrap GooCanvasItem.find_child_property as classmethod (Gian Mario) o New example of Table (Gian Mario) o Wrap goo_canvas_polyline_model_new_line Gian Mario) o Wrap goo_canvas_item_model_[get|set]_child_properties (Gian Mario) o Wrap goo_canvas_item_[get|set]_child_properties (Gian Mario) o Add setters for bounds_x1, bounds_x2, bounds_y1, bounds_y2 of goocanvas.ItemSimple. Closes LP#81992. (Gustavo) o Wrap all new methods of goocanvas.Style (Gustavo) o Implement mapping methods in goocanvas.Style (Gustavo) o _wrap_GooCanvasItem__proxy_do_get_bounds, _wrap_GooCanvasItem__proxy_do_update, Override to implement proper 'return value' semantics for the bounds parameter. (Gustavo) o Add a reversewrapper. Parameter handler for GooCanvasBounds* (Gustavo) o Added new examples (Gian Mario, Gustavo) o _cairo_pattern_to_gvalue: allow pattern=None in properties (Gustavo) o Regenerated defs files with new goocanvas include files (Gian Mario) Blurb: ====== Goocanvas [1] is a canvas widget for GTK+, It is similar in many ways to FooCanvas, hence the name, but it uses cairo for rendering, it has an optional model/view split, and uses interfaces for items & views (so you can easily turn any application object into a canvas item or view). PyGooCanvas is a wrapper which exposes the goocanvas API to the python world. It is fairly complete; most of the API are covered. The documentation is a work in progress, needs quite a lot of work in order to reflect the new API, a lot of new examples are provided, anyway help will be greatly appreciated. Like the GTK+ library, PyGTK and GooCanvas itself PyGooCanvas is licensed under the GNU LGPL, so is suitable for use in both free software and proprietary applications. PyGooCanvas requires: ===================== o Goocanvas >= 0.6.0 o PyGObject >= 2.10.1 (2.11.3 to build the docs) o PyGTK >= 2.10.4 o PyCairo >= 1.2.0 Bug reports should go to https://launchpad.net/pygoocanvas/ [1] http://sourceforge.net/projects/goocanvas cheers -- Gian Mario Tagliaretti From james.abley at gmail.com Sun Feb 18 18:17:07 2007 From: james.abley at gmail.com (James Abley) Date: Sun, 18 Feb 2007 23:17:07 +0000 Subject: unicodedata implementation In-Reply-To: <23fce8e60702151556v8e99633w65721740c194d88d@mail.gmail.com> References: <23fce8e60702151556v8e99633w65721740c194d88d@mail.gmail.com> Message-ID: <23fce8e60702181517u566fb12ey8459a010da8a5030@mail.gmail.com> Hi, [Originally posted this to the dev list, but the moderator advised posting here first] I'm looking into implementing this module for Jython, and I'm trying to understand the contracts promised by the various methods. Please bear in mind that means I'm probably targeting the CPython implementation as of 2.3, although I would obviously be quite happy if my implementation doesn't need too much extra to fit the 2.5 functionality! As someone has previously posted [1], the documentation is a little thin and they were pointed at the Unicode specification [2]. I've done a little reading there, and have a little knowledge now, which is always dangerous. There are still gaps, and I was hoping someone here might be able to point out what I'm missing. My problem, described here [3], but I'll summarise and add a little to it. 2468;CIRCLED DIGIT NINE;No;0;EN; 0039;;9;9;N;;;;; (UnicodeData.txt [4] for Unicode 3.2.0 [5] entry for code-point 0x2468) verify(unicodedata.decimal(u'\u2468',None) is None) verify(unicodedata.digit(u'\u2468') == 9) verify(unicodedata.numeric(u'\u2468') == 9.0) That works fine, and I can see in the UnicodeData.txt file (the mirrored property N towards the end is a fine marker; go back three fields and then start working forward from there) that the decimal property isn't defined, the digit property is 9 and the numeric property is also 9. However, this next bit is what confuses me: 325F;CIRCLED NUMBER THIRTY FIVE;No;0;ON; 0033 0035;;;35;N;;;;; (UnicodeData.txt for Unicode 3.2.0 entry for code-point 0x325F) verify(unicodedata.decimal(u'\u325F',None) is None) verify(unicodedata.digit(u'\u325F', None) is None) verify(unicodedata.numeric(u'\u325F') == 35.0) The last one fails - ValueError: not a numeric character. Now, again looking at the UnicodeData.txt entry and the mirrored N property, working back three fields and going forward from there shows that the decimal property isn't set, the digit property isn't set and the numeric property appears to be 35. So from my understanding of the Unicode (3.2.0) spec, the code point 0x325F has a numeric property with a value of 35, but the python (2.3 and 2.4 - I haven't put 2.5 onto my box yet) implementation of unicodedata disagrees, presumably for good reason. I can't see where I'm going wrong. Cheers, James [1] http://groups.google.com/group/comp.lang.python/browse_frm/thread/39a894325686f329/7dbdda27be118836?lnk=st&q=unicodedata&rnum=10#7dbdda27be118836 [2] http://www.unicode.org/ [3] http://eternusuk.blogspot.com/2007/02/jython-unicodedata-initial-overview.html [4] http://www.unicode.org/Public/3.2-Update/UnicodeData-3.2.0.txt [5] http://www.unicode.org/Public/3.2-Update/UnicodeData-3.2.0.html From deets at nospam.web.de Thu Feb 22 08:47:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 14:47:44 +0100 Subject: plugin development best practices References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> <545ifrF1v049oU1@mid.uni-berlin.de> <1172150532.157803.299330@m58g2000cwm.googlegroups.com> Message-ID: <545l80F1vd5s1U1@mid.uni-berlin.de> > > I will search the archives. I am aware of the setuptools feature It is > quite nice. But the documentation is not very clear on how to define > "entry point groups" on the importing end, i.e. how to prepare a an > application to accept plugins it doesn't even now exist. The entry-points are just a method of discovery. Writing a plugin by itself - if that is what you are talking about here - is usually done by exposing a certain interface, and invoking some registration functionality - after the plugin is discovered, that is. Diez From mccredie at gmail.com Wed Feb 14 12:38:08 2007 From: mccredie at gmail.com (Matimus) Date: 14 Feb 2007 09:38:08 -0800 Subject: list of range of floats In-Reply-To: References: Message-ID: <1171474688.756658.248060@a34g2000cwb.googlegroups.com> > fits = list(float(a) for a in range(0, 10)) Another way of writing that: flts = map(float,range(10)) From gosinn at gmail.com Mon Feb 5 09:48:49 2007 From: gosinn at gmail.com (Gosi) Date: 5 Feb 2007 06:48:49 -0800 Subject: Calling J from Python Message-ID: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> It is quite easy to call J from Python http://groups.google.com/group/J-Programming/browse_thread/thread/5e84b75667f5f64e From arkanes at gmail.com Mon Feb 5 11:35:30 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 5 Feb 2007 10:35:30 -0600 Subject: wxPython: TextCtrl delayed update when using TE_RICH(2) In-Reply-To: <45c7533d$0$21148$7a628cd7@news.club-internet.fr> References: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> <45c5aa41$0$21142$7a628cd7@news.club-internet.fr> <45c7533d$0$21148$7a628cd7@news.club-internet.fr> Message-ID: <4866bea60702050835w1800f324la698b0a4e621254c@mail.gmail.com> On 2/5/07, jean-michel bain-cornu wrote: > >> For this kind of stuff, I'd try to put "self.out.WriteText(string)" in > >> some 'Idle' event, which avoid to fall in focus loops or other objects > >> events management problems not easy to solve. > >> > > > > This doesn't have anything to do with focus loops or otherwise, it's > > because the OP isn't familiar with event based programming. > > > > You're performing a long-running task which is preventing the event > > loop from processing, so your text isn't updating and your application > > is unresponsive. You need to rewrite your task - either do everything > > asynchronously, or use a threaded approach. If you use the thread > > approach, be sure to not call the updates directly, you can use the > > wx.CallAfter mechanism to call gui functions in a threadsafe manner. > > So it is an event management problem. > The event loop is not yet finished when the program want to display > something, potentially initiating a new event loop. > This is almost totally wrong. There is no "new event loop" involved. The OP is running a long task in the main thread, which is blocking the event loop. When the event loop is blocked, the application will not update and cannot be interacted with. It's that simple. The event loop in a gui application doesn't "finish" until the application exits. > If you don't want to bother with threads, the idle event approach is not > so bad. Put something to display in a buffer, and display it only one > time the gui have nothing else to do. The problem is not putting the text into the control - the OP is mislead by the symptoms. The problem is the task he's perform in addition to the logging, which is a long running task (and in his sample code is represented by time.sleep). The logging issue is a red herring, the real problem is the way he's structured his application, with work blocking the event loop. Until he changes this, nothing about the way he writes to his log is going to fix the problem. > I use it every time I can, and it's very safe and easy to do. > Furthermore, you can still step into the program with a debugger, which > can be tricky if the program uses threads (I'd say impossible, but I > didn't try in fact). > Using idle events for continual calculation actually has several caveats you need to be aware of, and I don't recommend it. A background thread or a timer is generally a better solution. From duncan.booth at invalid.invalid Wed Feb 7 04:44:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Feb 2007 09:44:32 GMT Subject: Python compiled on Windows References: Message-ID: Franz Steinhaeusler wrote: >>Yes, people have compiled Python with gcc on windows. I believe it is >>slightly slower than the standard release, but I would guess that may >>depend on the exact versions of gcc/msc you choose to compare, and the >>exact compiler options you choose (or I may even be imagining it >>entirely). > > I cannot imagine, that there is a decisive difference, especially as > in gcc, you have also a couple of options. > I did a quick comparison running pystone and taking the best of several runs: On one system which had the Windows Python 2.4 distribution and also Python 2.4 installed under cygwin: Windows Python 2.4: 46k Cygwin Python 2.4: 41k On another system which has a dual boot setup: Windows Python 2.5: 43.7k Ubuntu Python 2.5: 42.0k So in the first case there was about a 12% improvement and in the second case about 5% improvement using the Windows distribution. I don't know whether the gap is closing from improvements in gcc or whether there is an OS related difference as well. Unfortunately cygwin doesn't appear to offer Python 2.5 yet. From nick at craig-wood.com Tue Feb 20 04:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 20 Feb 2007 03:30:06 -0600 Subject: Forking SocketServer daemon -- updating state References: Message-ID: Reid Priedhorsky wrote: > I am implementing a forking SocketServer daemon that maintains significant > internal state (a graph that takes ~30s to build by fetching from a SQL > database, and eventually further state that may take up to an hour to > build). > > I would like to be able to notify the daemon that it needs to update its > state. Because it forks for each new request, a request handler can't > update the state because then only the child would have the new state. > > One idea I had was to use signals. Is it safe to write a signal handler > that does extensive work (several seconds)? Seems like even so, it might > be tricky to do this without race conditions. In general no it isn't safe. However due to the way python handles its interrupts (it sets a flag in its own signal handler which the bytecode interpreter examines and acts upon when it is safe to do so) you won't corrupt python if you do this. I'd still recommend the set a flag and do it in your mainloop approach though if you can. > Another possibility is that the signal handler simply sets a > needs_update flag, which I could check for in a handle_request() > loop. The disadvantage here is that the update wouldn't happen > until after the next request is handled, and I would like the state > to be available for that next request. A solution might be to send > a signal followed by a dummy request, which seems a bit awkward. Can't you get SocketServer to timeout and return you control regularly? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jonathan.sabo at gmail.com Wed Feb 21 18:15:33 2007 From: jonathan.sabo at gmail.com (jonathan.sabo at gmail.com) Date: 21 Feb 2007 15:15:33 -0800 Subject: pexpect regex help In-Reply-To: <1172099628.074816.61980@q2g2000cwa.googlegroups.com> References: <1172099628.074816.61980@q2g2000cwa.googlegroups.com> Message-ID: <1172099731.535866.234380@s48g2000cws.googlegroups.com> On Feb 21, 6:13 pm, jonathan.s... at gmail.com wrote: > I have a pexpect script to walk through a cisco terminal server and I > was hoping to get some help with this regex because I really suck at > it. > > This is the code: > > index = s.expect(['login: ', pexpect.EOF, pexpect.TIMEOUT]) > if index == 0: > m = re.search('((#.+\r\n){20,25})(\s.*)', > s.before) #<---------- MY PROBLEM > print m.group(3), > print ' %s %s' % (ip[0], port) > s.send(chr(30)) > s.sendline('x') > s.sendline('disco') > s.sendline('\n') > elif index == 1: > print s.before > elif index == 2: > print > print '%s %s FAILED' % (ip[0], port) > print 'This host may be down or locked on the TS' > s.send(chr(30)) > s.sendline('x') > s.sendline('disco') > s.sendline('\n') > > This is attempting to match the hostname of the connected host using > the output of a motd file which unfortunately is not the same > everywhere... It looks like this: > > ######################################################################### > # This system is the property > of: # > # > # > # DefNet > # > # > # > # Use of this system is for authorized users > only. # > # Individuals using this computer system without authority, or > in # > # excess of their authority, are subject to having all of > their # > # activities on this system monitored and recorded by > system # > # > personnel. # > # > # > # In the course of monitoring individuals improperly using > this # > # system, or in the course of system maintenance, the > activities # > # of authorized users may also be > monitored. # > # > # > # Anyone using this system expressly consents to such > monitoring # > # and is advised that if such monitoring reveals > possible # > # evidence of criminal activity, system personnel may provide > the # > # evidence of such monitoring to law enforcement > officials. # > ######################################################################### > > pa-chi1 console login: > > And sometimes it looks like this: > > ######################################################################### > # This system is the property > of: # > # > # > # DefNet > # > # > # > # Use of this system is for authorized users > only. # > # Individuals using this computer system without authority, or > in # > # excess of their authority, are subject to having all of > their # > # activities on this system monitored and recorded by > system # > # > personnel. # > # > # > # In the course of monitoring individuals improperly using > this # > # system, or in the course of system maintenance, the > activities # > # of authorized users may also be > monitored. # > # > # > # Anyone using this system expressly consents to such > monitoring # > # and is advised that if such monitoring reveals > possible # > # evidence of criminal activity, system personnel may provide > the # > # evidence of such monitoring to law enforcement > officials. # > ######################################################################### > pa11-chi1 login: > > The second one works and it will print out pa11-chi1 but when there > is a space or console is in the output it wont print anything or it > wont match anything... I want to be able to match just the hostname > and print it out. > > Any ideas? > > Thanks, > > Jonathan It is also posted here more clearly and formatted as it would appear on the terminal: http://www.pastebin.ca/366822 From steve at holdenweb.com Wed Feb 21 22:35:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Feb 2007 22:35:51 -0500 Subject: getting a thread out of sleep In-Reply-To: <1172114738.832487.193750@v33g2000cwv.googlegroups.com> References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> <1172098070.913952.20730@h3g2000cwc.googlegroups.com> <1172103051.070952.182060@q2g2000cwa.googlegroups.com> <1172114738.832487.193750@v33g2000cwv.googlegroups.com> Message-ID: placid wrote: > On Feb 22, 12:08 pm, mark wrote: >> On 21 Feb 2007 16:10:51 -0800, placid wrote: >> >>> On Feb 22, 10:20 am, mark wrote: >>>> On 21 Feb 2007 14:47:50 -0800, placid wrote: >>>>> On Feb 22, 3:23 am, mark wrote: >>>>>> On 20 Feb 2007 21:26:18 -0800, placid wrote: >>>>>>> On Feb 21, 4:21 pm, "placid" wrote: >>>>>>>> On Feb 21, 4:12 pm, mark wrote: >>>>>>>>> On 20 Feb 2007 20:47:57 -0800, placid wrote: >>>>>>>>>> On Feb 21, 3:08 pm, mark wrote: >>>>>>>>>>> Right now I have a thread that sleeps for sometime and check if an [...] Perhaps in future we can avoid quoting the whole preceding thread except when strictly necessary? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gosinn at gmail.com Wed Feb 7 13:59:42 2007 From: gosinn at gmail.com (Gosi) Date: 7 Feb 2007 10:59:42 -0800 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> <1170796103.766866.18320@a34g2000cwb.googlegroups.com> <1170861935.779969.52980@v33g2000cwv.googlegroups.com> Message-ID: <1170874782.600836.210670@a34g2000cwb.googlegroups.com> On Feb 7, 3:46 pm, Marc 'BlackJack' Rintsch wrote: > In <1170861935.779969.52... at v33g2000cwv.googlegroups.com>, Gosi wrote: > > I like to use J for many things and I think that combining Python and > > J is a hell of a good mixture. > > I was able to follow this sentence up to and including the word "hell"... :-) > > Ciao, > Marc 'BlackJack' Rintsch That is a start. "Hell" is also what most example start with as in "Hello something" Hell in northern countries is very cold. Hell in middle east is very hot. I do not know which is your Hell hot or cold. Hell o ver?ld From greg at cosc.canterbury.ac.nz Thu Feb 8 01:23:42 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 08 Feb 2007 19:23:42 +1300 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: <52vu3eF1pf54sU1@mid.individual.net> Dave Benjamin wrote: > Neil Cerutti wrote: > >> There's been only one (or two?) languages in history that >> attempted to provide programmers with the ability to implement >> new infix operators, including defining precedence level and >> associativity (I can't think of the name right now). > > You're probably thinking of SML or Haskell. OCaml also allows you to > define new infix operators, but the associativities are fixed (and > determined by what punctuation you use). Prolog lets you do this, too. In Smalltalk, you can use just about any sequence of non-letters as an infix operator, but it has no notion of precedence, even for the built-in operators. I think SNOBOL may have had something for defining new operators, but I can't remember the details. -- Greg From aleax at mac.com Mon Feb 26 01:23:42 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Feb 2007 22:23:42 -0800 Subject: gmpy moving to code.google.com Message-ID: If you're interested in gmpy (the Python wrapper of GMP, for unlimited-precision arithmetic, rationals, random number generation, number-theoretical functions, etc), please DO check out http://code.google.com/p/gmpy/ -- gmpy 1.02 is there (as far as I can tell) in a workable state. Source on Subversion (and a prerelease zipfile too), downloadable binaries for MacOSX (download and read the README file first!) and Windows (for Python 2.4 and 2.5 only, built and minimally tested on a shaky Win2K+mingw -- on -- Parallels/MacOSX setup... I have no other Windows machine to check 'em out...!). Please help me check that the move-and-upgrade went OK -- download some or all of the pieces (including an svn checkout of the sources), build, install, test, try it out. I will HEARTILY welcome feedback (mail aleaxit at gmail.com) telling me what worked and/or what didn't so I can finalize this release -- and hopefully move on to a future 1.03 (I won't aim to 1.03 until I'm convinced that 1.02 is OK...). Thanks in advance, Alex From worlman385 at yahoo.com Mon Feb 12 17:54:48 2007 From: worlman385 at yahoo.com (worlman385 at yahoo.com) Date: Mon, 12 Feb 2007 14:54:48 -0800 Subject: star_new_thread Message-ID: please take a look at my code (short version) http://chiu424.hypermart.net/code5.py.txt I write a instant messaging app over bluetooth My code will send / receive data from a bluetooth socket (same concept TCP socket) at the same time The code has infinite loop poll for and send data to the socket but I want to have 2nd thread taking user input text and send to the socket I used thread.start_new_thread but the code hangs forever ======================================== here is the code with only signle thread (send / receive) data at same time working OK - it can send text + receive text from socket http://chiu424.hypermart.net/code5f.py.txt (full version) - works OK ======================================== after change the code to use - thread.start_new_thread, the code hangs forever at the begin of while loop and never execute self.timer.after(3, self.timeout_h) http://chiu424.hypermart.net/code5e.py.txt (full version) - hangs Thank you From eurleif at ecritters.biz Sun Feb 11 23:59:44 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 11 Feb 2007 23:59:44 -0500 Subject: About getattr() In-Reply-To: References: Message-ID: <45cff433$0$6823$4d3efbfe@news.sover.net> Jm lists wrote: > Since I can write the statement like: > >>>> print os.path.isdir.__doc__ > Test whether a path is a directory > > Why do I still need the getattr() func as below? > >>>> print getattr(os.path,"isdir").__doc__ > Test whether a path is a directory You don't. getattr() is only useful when the attribute name is determined at runtime. From stanc at al.com.au Tue Feb 20 23:09:19 2007 From: stanc at al.com.au (Astan Chee) Date: Wed, 21 Feb 2007 15:09:19 +1100 Subject: eval('000052') = 42? Message-ID: <45DBC5EF.1020406@al.com.au> Hi, I just tried to do eval('00052') and it returned 42. Is this a known bug in the eval function? Or have I missed the way eval function works? Thanks From dingbat at codesmiths.com Thu Feb 15 06:29:45 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 15 Feb 2007 03:29:45 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: <7xps8cjt8s.fsf@ruckus.brouhaha.com> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <7xps8cjt8s.fsf@ruckus.brouhaha.com> Message-ID: <1171538985.045430.317190@v45g2000cwv.googlegroups.com> On 14 Feb, 21:59, Paul Rubin wrote: > Why don't you describe the actual problem instead of the rot13 analogy. I don't know what the actual problem is! I need to perform a complex mapping between "old style" structured identifiers and "new style" structured identifers. As the original specification was never thought through or written down anywhere, I'm now having to try and reverse- engineer from 5 years of collected inconsistent practice. So far I have about four pages of BNF to describe things and I'm still not sure what's accurate, what's inaccurate spec and what's merely an error in practice. Hopefully there's a neat little structure underlying it all and a few typos I can merely ignore, but probably it really is just an inconsistent structure that needs a lot of explicit tests around the corner-cases to make sense of. rot13 isn't the issue here, and I already know how to use .translate() What I'm after is a tutorial of my Python coding style for an example that's quite similar to the rot13 case. Your previous posting was very helpful here. From nswebster at gmail.com Fri Feb 9 09:03:51 2007 From: nswebster at gmail.com (Neil Webster) Date: 9 Feb 2007 06:03:51 -0800 Subject: Glob returning an empty list when passed a variable Message-ID: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Hi, I was wondering whether anybody could help me out. I have a program, for part of it I am trying to pass a variable to a glob function, this returns an empty list. The strange thing is when I hard code in the variable the glob section works. Does anybody have any ideas as why it is not working? The section of code that is not working is: # The variable to be passed to the glob function area_name_string = '"*% s*"' % (Area_name) os.chdir(Input) filename = glob.glob(area_name_string) Thanks in advance Neil From stj911 at rock.com Sat Feb 24 11:22:44 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 24 Feb 2007 08:22:44 -0800 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** Message-ID: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Canada anti-terror law is struck down >From the Associated Press February 24, 2007 OTTAWA - Canada's Supreme Court on Friday unanimously declared it unconstitutional to detain foreign terrorism suspects indefinitely while the courts review their deportation orders. Five Arab Muslim men have been held for years under the "security certificate" program, which the Justice Department has said is a key tool in the fight against global terrorism and essential to Canada's security. The court found that the system violated the Charter of Rights and Freedoms, Canada's bill of rights. However, it suspended its ruling for a year to give Parliament time to rewrite the part of the Immigration and Refugee Protection Act that covers the certificate process. The security certificates were challenged by three men from Morocco, Syria and Algeria - all alleged by the Canadian Security Intelligence Service to have ties to terrorist networks. The men have spent years in jail while fighting deportation orders. They risk being labeled terrorists and sent back to their native countries, where they say they could face torture. The court said the treatment of the suspects was a violation of their rights. "The overarching principle of fundamental justice that applies here is this: Before the state can detain people for significant periods of time, it must accord them a fair judicial process," Chief Justice Beverley McLachlin wrote in a ruling for all nine justices. "The secrecy required by the scheme denies the person named in a certificate the opportunity to know the case put against him or her, and hence to challenge the government's case," she said. The challenged law allows sensitive intelligence to be heard behind closed doors by a federal judge, with only sketchy summaries given to defense attorneys. The court said the men and their lawyers should have a right to respond to the evidence used against them by intelligence agents. Stockwell Day, the minister of public safety, noted that because the ruling does not take effect for a year, the certificates would remain in place. He said the government would address the court's ruling "in a timely and decisive fashion." Two of the men are out on bail and remain under house arrest. Three others are being held in a federal facility in Ontario. From siona at chiark.greenend.org.uk Wed Feb 28 09:28:48 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Feb 2007 14:28:48 +0000 (GMT) Subject: os.system and quoted strings References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> <1172627614.008588.176800@p10g2000cwp.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: >>>> import os.path >>>> os.path.join("c:", >... "Documents and Settings", >... "somepath") >'c:Documents and Settings\\somepath' >>>> > >Hmmm, a quick test with > >dir "e:userdata" > >worked, so the top level \ may not be needed... "drive:" is the 'cwd' on the drive, so "drive:directory" is relative to that. Try "cd e:userdata" and repeat "dir e:userdata" and see what happens. os.path.join() has to behave as above, otherwise you wouldn't be able to use it to construct a relative path like that. (And since I don't think anyone's mentioned it in this thread yet, subprocess.call() instead of os.system().) -- \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 lbates at websafe.com Fri Feb 23 18:48:18 2007 From: lbates at websafe.com (Larry Bates) Date: Fri, 23 Feb 2007 17:48:18 -0600 Subject: Having multiple instances of a single application start a single instance of another one In-Reply-To: <45df6400$0$489$cc7c7865@news.luth.se> References: <45df6400$0$489$cc7c7865@news.luth.se> Message-ID: <45DF7D42.2090402@websafe.com> buffinator wrote: > I have two applications that should work together, let's call them A and B. > > The first time A starts, it should open a B process and start > communicating with it. All other times an A instance starts it should > simply talk with the B that already is open. > > The problem here is, if I start say 40 A applications at once... how do > I check if a B is open "fast enough" so that the other A's (not the > first one) won't spawn new B's? > > Im programming this in windows and am currently using the horrible > solution in A > > if not win32gui.FindWindow(None, "Name of B"): > spawn_B_here() > > This only works well if there is a small time between the A's started > first... > > What would the best solution for my problem be? > > /buffis Others have answered your specific question on the forum, I thought I would make a suggestion. You should consider writing application B as a Windows Service that gets started once (maybe even auto start when the machine boots) and runs forever in the background. Then have all your A's bind to it and communication (via sockets, pipes, filesystem, database, ...). That way your A's won't have the problem you describe. Just a suggestion. -Larry From http Thu Feb 22 13:03:18 2007 From: http (Paul Rubin) Date: 22 Feb 2007 10:03:18 -0800 Subject: when will python 2.5 take in mainstream? References: <45DDD8EE.7030104@v.loewis.de> Message-ID: <7xr6sink7t.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > I think it should be possible to specify a Python API that then future > versions can guarantee. This would be a subset of what you can currently > do on the Python API, in particular, access to the structure layout of > Python objects would not be available. An FFI like this is a reasonable idea, but it shouldn't look anything like the current C API. It should be more like a Lisp FFI, or the Java Native Interface. There might have to be a wrapper layer to get it to work with CPython. From michele.simionato at gmail.com Thu Feb 15 11:55:52 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Feb 2007 08:55:52 -0800 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> Message-ID: <1171558552.557623.274040@l53g2000cwa.googlegroups.com> On Feb 13, 9:14 am, Peter Otten <__pete... at web.de> wrote: > "Avoid inheritance" would be almost as justified :-) Yep, I strongly agree. Inheritance is overrated, as Guido says. For what concerns the debate of multiple vs single inheritance, yes it is true that multiple inheritance is worse, but even single inheritance can be bad enough, unfortunately :-( The issue is that inheritance *does not scale*: i.e. in simple situations it works fine, but it has the tendence to becomes unmanageable very easily In other words, if you are inheriting just two or three methods it may works, but when you start having dozens of methods inherited from different sources, your code will become to look as spaghetti code. This is why in general I (as many people here) suggest delegation over inheritance. Michele Simionato From kirk at nospam.jobsluder.net Sat Feb 3 11:29:58 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Sat, 03 Feb 2007 11:29:58 -0500 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> Message-ID: In article <7xirek9pdt.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > I do think the core should have more stuff than it does, so that its > functionality can be on a par with competing language distros like > J2SE and PHP. Both of those distros include database connectvity > modules and web frameworks. Can't speak for PHP, but J2SE requires the additional installation of the Mysql Connector/J JDBC driver. Java also does not include a web framework as far as I can tell, with many people bolting on struts and Tomcat for this purpose. Now granted, it may or may not be a good idea for python to copy the java way of doing things by including the generic database API into the core libraries rather than expect database module developers to use the API. But that doesn't solve the core problem that you can't get database connectivity just through the core language. And for that matter, perl doesn't include the database drivers or a web framework either. php does, but I've always considered php to be a web framework with an embedded programming language. Comparing python to php here strikes me as comparing apples and oranges. From ke5crp1 at verizon.net Sat Feb 3 04:08:52 2007 From: ke5crp1 at verizon.net (John Barrett) Date: Sat, 03 Feb 2007 09:08:52 GMT Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170482833.643671.254640@s48g2000cws.googlegroups.com> <1170488368.634755.138920@m58g2000cwm.googlegroups.com> Message-ID: wrote in message news:1170488368.634755.138920 at m58g2000cwm.googlegroups.com... > On Feb 2, 10:32 pm, "John Barrett" wrote: >> wrote in message > >> >> > [snip] >> >> > Run your "experiment" again but add some pure oxygen such as was >> >> > escaping from the on-board breathing oxygen tanks on the >> >> > airplanes that were crashed into the WTC. >> >> > No need to do it. We have the pictures of live humans waving from the >> > gaping holes in the towers where the planes crashed. We have the >> > testimonies of the fire fighters that the fires were not that hot and >> > minor. The fuel of the plane which is mainly in the wings were severed >> > outside the netting and much of them burnt outside in the fireball >> > that is visible in all the videos. Futhermore, the black soot that was >> > visible to the naked eye is indicative of bloody cold flame. Also, the >> > probability of the oxygen tanks oriented in such a way to inject >> > oxygen onto the steel as in a oxygen cutting torch is extremely low. >> > These cylinders have a 1000-3000psi of pressure which makes them into >> > a rocket or an explosive under uncontrolled gas release. And they >> > would not contaminate the molten metal with any sulfur. Either the >> > atmosphere inside was oxidising or reducing. If it was oxidising, how >> > did the sulfur in huge quantities contaminate the molten metal pools? >> > The official lies to explain sulfur is from the plaster wall. But that >> > requires a reducing atmosphere with finely divided and intimately >> > mixed reactants in a calciner where they are continuously rotated and >> > run for several hours. Yet the fires ran not even for an hour before >> > the building collapsed. >> >> OK - given all that -- you are left with only one conclusion (or at least >> I >> am) -- progressive structural failure, the loss of support where the >> plane >> hit was sufficient to put excessive stress on the remaining structural >> members, resulting in a catastrophic sequential failure > > I dont think you have seen any actual structural failures, esp > progressive. > That happens often in earthquake and they have stacked floors. There > is > famous picture of an earthquake on these websites and in the videos. > Futhermore > due to erratic stops and goes in the progressive failure, the > structure falls on the side esp a big bldg like WTC1&2 should have > fallen from the tipping torque to one side. That did not happen. only > controlled demolition bldgs fall down straight. > >> -- it doesnt take >> exotic chemical mixes to put excessive mechanical stress on a system... >> just >> chop out enough supports.. it may take time for the remaining supports to >> deform enough to reach the failure point.. but they will get there, as >> demonstrated -- occams razor dude -- the least hypothesis is usually the >> right one -- and I get enough conspiracy theory crap out of my dad -- >> makes >> a good movie -- but doesnt pan out in real life -- too many >> whistle-blowers >> around !! > > Occams razor is applicable to nature's works. human works are not > amenable to it. Besides, the official fairy tale is the conspiracy > theory. > >> The city I live in is installing those red-light cameras to catch >> light-runners -- my dad likes to claim that they manipulate the yellow >> time >> to catch people in the intersection and increase revenue from traffic >> tickets -- I told him to shut up until he got out there with a stop watch >> and proved it -- and I say the same to you -- PROVE it -- then make some >> noise -- conjecture and conspiracy theories without proof are a waste of >> everyones time. -- how do you know the sulphur was in large quantities ?? >> did you do a chemical analysis ?? or can you produce one done by a >> reputable >> metalurgy company ?? > > These pillars are not machinable steel. the sulfur here was excessive. > we are talking about intergranular corrosion, not that teeny amount > used for imparting machinability and that is not nowadays needed. It > only for cheap and rough chinese type crap and i am not sure even > there if someone would ruin their steel mills by adding this kind of > corrosive sulfur shit. come on dude ... dont mix categories. > >> Ohhh and by the way -- high sulphur steels are regularly used for >> machined >> components -- was the amount of sulphur detected incosistent with what >> may >> have been present due to the use of high sulphur steels ?? (where is that >> metalurgy report again ??) > > yeah a damn fool would put sulfur in the bolts and load bearing > elements such as the bolts of aircrafts and space shuttle. > > Besides how do you explain the completely pulverized building ?????? > if not for explosives. > > lets try that again :) http://www.tms.org/pubs/journals/JOM/0112/Eagar/Eagar-0112.html A very concise and MUCH more believable explanation of the structural failure modes involved WITH numbers that MAKE SENSE !! (and interestingly enough, a progressive failure as I surmised earlier.. one thing (one one thing) leads to another !!) and a VERY good explanation of why it fell straight down instead of to the side !! It even explains the speed of collapse, which given the masses involved (which they detail), will allow you to compute the energy of impact that so complexly pulverized the structure (remember what I said about RESEARCH -- try it some time !! It didn't take me and hour to find that one !! Google "world trade center structure") And so I wield Occam's Razor -- the simplest explanation that makes sense !! From nswebster at gmail.com Fri Feb 9 09:22:33 2007 From: nswebster at gmail.com (Neil Webster) Date: 9 Feb 2007 06:22:33 -0800 Subject: Glob returning an empty list when passed a variable In-Reply-To: References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: <1171030953.736118.89940@h3g2000cwc.googlegroups.com> On 9 Feb, 14:15, Steve Holden wrote: > Neil Webster wrote: > > Hi, > > > I was wondering whether anybody could help me out. > > > I have a program, for part of it I am trying to pass a variable to a > > glob function, this returns an empty list. The strange thing is when > > I hard code in the variable the glob section works. > > > Does anybody have any ideas as why it is not working? > > > The section of code that is not working is: > > > # The variable to be passed to the glob function > > area_name_string = '"*% s*"' % (Area_name) > > > os.chdir(Input) > > > filename = glob.glob(area_name_string) > > > Thanks in advance > > Because you are trying to match filenames that have a double-quote > character at the start and end? Try > > area_name_string = '*% s*' % (Area_name) > > Interesting, I never realised until now that you can have spaces between > the percent sign and th format effector. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007- Hide quoted text - > > - Show quoted text - Steve and Philipp, Thanks very much for the promptness of the reply and providing the answer. Steve, it appears to work so I left it, should it not be possible? Regards Neil From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 18:37:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 00:37:29 +0100 Subject: Python new user question - file writeline error In-Reply-To: <1170887579.160693.78160@a34g2000cwb.googlegroups.com> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <1170887579.160693.78160@a34g2000cwb.googlegroups.com> Message-ID: <45ca5b93$0$30648$426a74cc@news.free.fr> James a ?crit : > On Feb 7, 4:59 pm, "Shawn Milo" wrote: > (snip) >>I'm pretty new to Python myself, but if you'd like help with a >>Perl/regex solution, I'm up for it. For that matter, whipping up a >>Python/regex solution would probably be good for me. Let me know. >> >>Shawn > > > Thank you very much for your kind offer. > I'm also coming from Perl myself - heard many good things about Python > so I'm trying it out - but it seems harder than I thought :( If I may comment, Python is not Perl, and trying to solve things the Perl way, while still possible, may not be the best idea (I don't mean Perl is a bad idea in itself - just that it's another language with another way to do things). Here, doing the parsing oneself - either manually as james did or with regexps - is certainly not as easy as with Perl, and IMHO not the simplest way to go, when the csv module can take care of parsing and formatting CSV files and the datetime module of parsing and formatting dates. Just my 2 cents... From charleshixsn at earthlink.net Fri Feb 23 19:42:58 2007 From: charleshixsn at earthlink.net (Charles D Hixson) Date: Fri, 23 Feb 2007 16:42:58 -0800 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) In-Reply-To: References: <45DF5467.6000803@earthlink.net> Message-ID: <45DF8A12.2020400@earthlink.net> Gabriel Genellina wrote: >> En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson >> escribi?: >> >> >>> I'm sure I've read before about how to construct prototypes in Python, >>> but I haven't been able to track it down (or figure it out). >>> >>> What I basically want is a kind of class that has both class and >>> instance level dict variables, such that descendant classes >>> automatically create their own class and instance level dict variables. >>> The idea is that if a member of this hierarchy looks up something in >>> it's local dict, and doesn't find it, it then looks in the class dict, >>> and if not there it looks in its ancestral dict's. This is rather like >>> what Python does at compile time, but I want to do it at run time. >>> >> >> Well, the only thing on this regard that Python does at compile time, >> is to determine whether a variable is local or not. Actual name >> lookup is done at runtime. >> You can use instances and classes as dictionaries they way you >> describe. Use getattr/setattr/hasattr/delattr: >> >> py> class A: >> ... x = 0 >> ... y = 1 >> ... >> py> class B(A): >> ... y = 2 >> ... >> py> a = A() >> py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable >> py> print 'a=',vars(a) >> a= {'y': 3} >> py> >> py> b = B() >> py> print 'b=',vars(b) >> b= {} >> py> setattr(b,'z',1000) >> py> print 'b=',vars(b) >> b= {'z': 1000} >> py> print 'x?', hasattr(b,'x') >> x? True >> py> print 'w?', hasattr(b,'w')? False > The trouble is, I'd want to be adding variables at run time. At > least, I *think* that's a problem. Perhaps I'm misunderstanding what > Python's capabilities already are. How would one write a member > function to add a variable to a class? > > > From pDOTpagel at gsf.de Fri Feb 9 06:07:12 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Fri, 9 Feb 2007 11:07:12 +0000 (UTC) Subject: os.popen and broken pipes Message-ID: Hi Pythoneers, I need to process a large number of files which have been packed by the UNIX compress tool (*.Z files). As I am not aware of a compress equivalent of the gzip, zipfile or bzip2 modules, I thought I'd use the uncompress or zcat commands directly to deal with the files: for filename in file_list: file = os.popen('uncompress -c '+filename, 'r') do_something(file) file.close() This works fine for some files but results in 'write error onstdout: Broken pipe' emitted by uncompress for others. Using zcat instead of uncompress changes the wording of the error message but not the result. I tried to give popen a large bufsize argument but that didn't really help. Probably I'm overlooking something obvious here but right now I can't see it. Any hints? cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From rshepard at nospam.appl-ecosys.com Sun Feb 25 19:33:52 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 26 Feb 2007 00:33:52 GMT Subject: Referencing Items in a List of Tuples References: <1172424046.323933.85250@q2g2000cwa.googlegroups.com> Message-ID: On 2007-02-25, Paddy wrote: > You might also use list comprehensions to accumulate the values you > need: > > ec = [ item[2:] for item in mainlist if item[:2] == ['eco','con'] ] Thank you, Paddy. That's the syntax I couldn't work out myself. Rich From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 15:19:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 21:19:40 +0100 Subject: Calling J from Python In-Reply-To: <1170692852.549730.81030@v33g2000cwv.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: <45c78a46$0$29725$426a74cc@news.free.fr> Gosi a ?crit : > On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: > >>Gosi wrote: >> >>>It is quite easy to call J from Python >> >>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... >> >>What is J, and why should we care? >> >>Diez > > > J is in many ways similar to Python. So are Javascript and Ruby. > J has very many advanced operations. what's an "advanced operation" ? From jstroud at mbi.ucla.edu Thu Feb 22 00:28:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 21 Feb 2007 21:28:37 -0800 Subject: Question about classes and possible closure. In-Reply-To: References: Message-ID: Steven W. Orr wrote: > This is all an intro learning experience for me, so please feel free to > explain why what I'm trying to do is not a good idea. > > In the Cookbook, they have a recipe for how to create global constants. > > ----------------- > class _const: > class ConstError(TypeError): pass > def __setattr__(self,name,value): > if self.__dict__.has_key(name): > raise self.ConstError, "Can't rebind const(%s)"%name > self.__dict__[name]=value > > import sys > sys.modules[__name__]=_const() > ---------------- > > I'd like to be able to create constants within a class. (Yes I > understand that uppercase names is a far better and easier convention > but this is a learning experience for me.) > > I can't get this to work, but my idea is that MyClass is defined thusly: > > class ConstError(TypeError): pass > class Myclass: > def mprint(self): > print "C1 = ", self._C1 > > # Define a subclass to create constants. It refs upself to access > # the uplevel copy of self. > class _const: > class ConstError(TypeError): pass > def __setattr__(_upself,name,value): > if upself.__dict__.has_key(name): > raise self.ConstError, "Can't rebind const(%s)"%name > else: > print "Just set something" > upself.__dict__[name]=value > > # I want the const instance to be contained in this class so I > # instantiate here in the constructor. > def __init__(self): > upself = self > upself.consts = const() > upself.consts._C1 = 0 > setattr(upself.consts, "_C1", 44) > self = upself > > Then the call in another file is this: > #! /usr/bin/python > from c2 import Myclass > foo = Myclass() > foo.mprint() > # end > > Is it possible to nest a class in another class and is it possible to > make this work? > > TIA > I see no reason to nest classes, ever, as each creates a seperate name space. Better would be to de-nest _const and make it available to all of your classes, otherwise you have lost some of its reusability. A class is esentially the definition of a behavior and so nesting assumes that the nesting confers upon the outer class that having a nested class changes its behavior. This is what composition is for. If you want a reference to a class in your code, then make an assignment: # Const.py class ConstError(TypeError): pass class Const: def __setattr__(self, name, value): if hasattr(self, name): raise ConstError, "Can't rebind const(%s)" % name else: print "Just set something" self.__dict__[name] = value # Myclass.py import Const class Myclass: def mprint(self): print "C1 = ", self.consts._C1 def __init__(self): self.consts = Const() self.consts._C1 = 0 # This will raise an error!!!! self.consts._C1 = 44 This makes a lot more sense and follows the "flat is better than nested" rule. Notice how, otherwise, ConstError would be triple nested. Now you can import Const and have constants in all your classes. I also pythonized some of your code. James From charitylynn at charitylynn.net Mon Feb 12 12:57:48 2007 From: charitylynn at charitylynn.net (Charity) Date: 12 Feb 2007 09:57:48 -0800 Subject: Jython / Java / C / C++ interoperability Message-ID: <1171303068.745886.49570@h3g2000cwc.googlegroups.com> Hi all, I have a code base primarily written in Java. I would like to use Jython to "use" this code base. Everything is wonderful because Jython calls Java easily. However, there may be a time when I would like to call C/C++ from Jython. I can't do this directly, can I? Would I have to wrap the C/ C++ in Java to access from Jython? Or call Python which will call the C/C++? What method would be the easiest and most elegant solution for gaining access to C/C++ functionality from Jython? Please keep in mind that I have very little Jython experience. Much thanks for any information! Have a great day! Charity From Robert.Katic at gmail.com Sat Feb 24 00:06:18 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 23 Feb 2007 21:06:18 -0800 Subject: Solved: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: <1172293578.590167.268210@m58g2000cwm.googlegroups.com> > If you say > > from foo import _fooa, _foob, > > then the import will fail because the _ is used only by the import to > decide that you shouldn't see _fooa or _foob. ??? Read Python manuals, please. From iansan at gmail.com Thu Feb 8 19:50:48 2007 From: iansan at gmail.com (IamIan) Date: 8 Feb 2007 16:50:48 -0800 Subject: Regexp not performing the same in FTP versus Python In-Reply-To: <1170978596.337428.261110@h3g2000cwc.googlegroups.com> References: <1170978596.337428.261110@h3g2000cwc.googlegroups.com> Message-ID: <1170982248.233555.252840@p10g2000cwp.googlegroups.com> It's strange but since more files have been added to this directory the regexp appears to be working correctly. Sorry to bother the list and thanks for your time. Ian From gert.cuykens at gmail.com Wed Feb 28 05:58:19 2007 From: gert.cuykens at gmail.com (gert) Date: 28 Feb 2007 02:58:19 -0800 Subject: random textimage Message-ID: <1172660299.114009.42950@a75g2000cwd.googlegroups.com> import string import random import PIL from PIL import Image, ImageFont, ImageDraw from PIL import ImageEnhance, ImageOps, ImageStat from StringIO import StringIO import os pwd = os.path.dirname(os.path.abspath(__file__)) fpath=os.path.join(pwd,'img.ttf') iname=os.path.join(pwd,'pass.jpg') def gen(): text = str(random.randint(0,1000)) im = Image.new("RGB", (125, 34), "#fff") ttf = ImageFont.truetype(fpath, 16) draw = ImageDraw.Draw(im) draw.text((10,10), text, font=ttf, fill="green") img = StringIO() im.save(img, "JPEG") f = open(iname) f.write(im) f.close() return text if __name__ == "__main__": print gen() gert at gert:~/Desktop/svn/xhtml$ python2.5 textimg.py Traceback (most recent call last): File "textimg.py", line 27, in print gen() File "textimg.py", line 22, in gen f.write(im) TypeError: argument 1 must be string or read-only character buffer, not instance gert at gert:~/Desktop/svn/xhtml$ i am stuck anybody can help me ? From Janak.Mandowara at gmail.com Wed Feb 7 08:41:43 2007 From: Janak.Mandowara at gmail.com (Janak) Date: 7 Feb 2007 05:41:43 -0800 Subject: http://www.freeanything4you.com/ Message-ID: <1170855703.283438.47660@a34g2000cwb.googlegroups.com> http://www.freeanything4you.com/ From martin at v.loewis.de Thu Feb 22 12:54:54 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 22 Feb 2007 18:54:54 +0100 Subject: when will python 2.5 take in mainstream? In-Reply-To: References: Message-ID: <45DDD8EE.7030104@v.loewis.de> > Its simple to require changes, not so sure that doing these > modifications keep things simple. Maybe an internal Python hacker can > give us his advice on such a modification (ie. staying compatible with > legacy modules compiled for previous versions). I think it should be possible to specify a Python API that then future versions can guarantee. This would be a subset of what you can currently do on the Python API, in particular, access to the structure layout of Python objects would not be available. Extension modules compiled against this API could then be compatible across versions. This would require both a change to the interpreter (to really mark all API that is or is not "stable"), and to extension modules (to restrict themselves to only this API). Regards, Martin From jjl at pobox.com Sun Feb 11 15:55:13 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 11 Feb 2007 20:55:13 GMT Subject: urllib2 request htaccess page through proxy References: <45cf1e70$0$32731$4fafbaef@reader1.news.tin.it> Message-ID: <87tzxsife5.fsf@pobox.com> Alessandro Fachin writes: > I write this simply code that should give me the access to private page with > htaccess using a proxy, i don't known because it's wrong... [...] > i get no access on access.log from apache2 and nothing from the proxy in > tcpdump log. If i use only the proxy with a page that doesn't use htaccess > it works... if anyone could help,regards... [...] > urllib2.HTTPError: HTTP Error 401: Authorization Required Works for me (using Squid and Apache both running on localhost). Looking at what goes over the wire, I see a 401 followed by a 299 response, which is what is expected (the 401 prompts the client to send the username and password, which is then rewarded with the 200). Could you describe in more detail what your proxy and Apache configuration are like? And more about your network (on what machines do proxy, HTTP server, and HTTP client run -- all on the same machine, some on the same machine, all three on three different machines?) The more detail the better. John From sjmachin at lexicon.net Wed Feb 14 02:15:51 2007 From: sjmachin at lexicon.net (John Machin) Date: 13 Feb 2007 23:15:51 -0800 Subject: python not returning true In-Reply-To: <1171435541.291367.299290@j27g2000cwj.googlegroups.com> References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171431443.737052.183960@j27g2000cwj.googlegroups.com> <1171435541.291367.299290@j27g2000cwj.googlegroups.com> Message-ID: <1171437351.206085.236450@q2g2000cwa.googlegroups.com> On Feb 14, 5:45 pm, "agent-s" wrote: > On Feb 13, 9:37 pm, "John Machin" wrote: > > > > > On Feb 14, 4:15 pm, "agent-s" wrote: > > > > I have a function, generally described as so: > > > > def function(args): > > > if condition: > > > if condition2: > > > function(args+1) > > > return None> elif condition3: > > > print "text" > > > return True > > > else: > > > return False > > > else: > > return None > > > There are two cases, indicated above, where you don't explicitly do a > > "return", so you fall off the end of the function, and Python returns > > None. > > > Then when the function's caller tests the returned value, None is > > treated as logically false. > > > > which is used in: > > > > if function(args): > > > print "ok" > > > > so here basically "text" will print out when condition3 is true but it > > > will not print out "ok" when condition3 is true. When it's true it > > > should print out borth "text" and "ok" > > > In the second last sentence, it is difficult to determine what you > > think is expected behaviour and what you say is the actual behaviour. > > In the last sentence, what does the first "it" refer to? > > > If the knowledge about returning None doesn't help you, try some > > standard(??) techniques like inserting print statements or debugger > > break-points. > > > HTH, > > John > > Thanks! That was exactly what it was. I solved it by using "return > function(args+1)" instead of simply "function(args+1)." That takes care of only 1 of the two cases of returning None instead of True/False. > > btw Steven you are so witty I hope to one day pwn noobs on newsgroups > too. Wit has nothing to do with it. The fact that you are a Python noob is also irrelevant. Your problem statement was unintelligible, as is your response. What does "pwn" mean? From vatamane at gmail.com Wed Feb 7 02:56:04 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 6 Feb 2007 23:56:04 -0800 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: References: Message-ID: <1170834964.383885.316960@v33g2000cwv.googlegroups.com> >From the www.parallelpython.com , the 'Features' section: -------------------------------- Features: *Parallel execution of python code on SMP and clusters ------------------------------- PP uses processes, and thus it will take advantage of multiple cores for a CPU bound task. -Nick On Feb 6, 9:13 pm, "fdu.xia... at gmail.com" wrote: > Hi all, > > I'm interested in Parallel Python and I learned from the website of > Parallel Python > that it can run on SMP and clusters. But can it run on a our muti-CPU > server ? > We are running an origin3800 server with 128 CPUs. > > Thanks. From paul at boddie.org.uk Tue Feb 27 10:09:59 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Feb 2007 07:09:59 -0800 Subject: installing "pysqlite" In-Reply-To: <1172579710.514139.103170@s48g2000cws.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <1172579710.514139.103170@s48g2000cws.googlegroups.com> Message-ID: <1172588999.749895.3310@j27g2000cwj.googlegroups.com> On 27 Feb, 13:35, "Nader" wrote: > > Thank for your reaction. I don't know also how the interaction sith > 'easy_install' is. I think that I have to install 'pysqlite' from > source code also, because i can change ther the 'setup.cfg' file and I > can give there where the 'libsqlie3' is. What I did was to go to the pysqlite site (http://www.initd.org/ tracker/pysqlite/wiki/pysqlite), download the sources for the latest version, then change the setup.cfg file so that include_dirs refers to the place where the SQLite headers (eg. sqlite.h) were installed, and that library_dirs refers to the place where the SQLite libraries were installed. For example: include_dirs=/opt/sqlite/usr/include library_dirs=/opt/sqlite/usr/lib (You'd get the above if you configured SQLite to install into /opt/ sqlite/usr.) Then, just do the usual build: python setup.py build And install with a prefix: python setup.py install --prefix=/opt/pysqlite/usr Since you seem to be installing things in non-root-controlled places, I imagine you're familiar with specifying things like the --prefix above, as well as setting up your PYTHONPATH afterwards. Paul From jjl at pobox.com Sat Feb 10 07:38:31 2007 From: jjl at pobox.com (John J. Lee) Date: 10 Feb 2007 12:38:31 +0000 Subject: urllib2 hangs "forever" where there is no network interface References: <1170315718.860222.160810@k78g2000cwa.googlegroups.com> <1170353063.024553.10060@s48g2000cws.googlegroups.com> <871wl7b828.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > (I'm having news trouble, sorry if anybody sees a similar reply three > times...) > > "dumbkiwi" writes: > > On Feb 2, 5:02 am, j... at pobox.com (John J. Lee) wrote: > > > "dumbkiwi" writes: > [...] > > > > If there is no network interface, urllib2 hangs for a very long time > > > > before it raises an exception. I have set the socket timeout with > > > > socket.setdefaulttimeout(), however, where there is no network > > > > interface, this seems to be ignored - presumably, because without a > > > > network interface, there is nothing for the socket module to interact > > > > with. > [...] > > > Presumably Windows? (Unix systems almost always have at least a > > > loopback interface) > > > > > > John > > > > Sorry, I should have been more specific. The network interfaces are > > up - ie lo and eth1, it's where the wireless connection has dropped > > out. > > The underlying problem is that Python's socket timeout is implemented > using select() or poll(). Those system calls only allow timing out > activity on file descriptors (e.g. sockets). The problem you're > seeing is caused by getaddrinfo() blocking for a long time, and that > function doesn't involve file descriptors. The problem should really > be fixed at the C level (in Modules/socketmodule.c), using something > like alarm() or a thread to apply a timeout to getaddrinfo() calls. Seems doing this portably with threads is a bit of a nightmare, actually. You'd have to extend every one of CPython's thread implementations (pthreads, Solaris threads, etc. etc. etc.) -- and I don't even know if it's possible on all systems. And since the GIL is released around the getaddrinfo() call in socketmodule.c (and that can't be changed), one can't guarantee that a Python thread won't set a different signal handler, so alarm() is not good. And of course Windows is a separate case. > > Is the best solution to test for a wireless connection through / > > proc before trying to download data? > > That may be a good practical solution. > > Another workaround that might be useful is to do your DNS lookups only > once, then use only IP addresses. The portable way to actually solve what I assume is your underlying problem (latency in a GUI) is to have a Python thread or separate process do your urlopen()s (this can be done at the Python level). John From bj_666 at gmx.net Wed Feb 14 15:54:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 14 Feb 2007 21:54:07 +0100 Subject: reference data in a dictionary References: <1115a2b00702141226i4f23dc17x1360d87ed253dd3e@mail.gmail.com> <87ps8c79tv.fsf@benfinney.id.au> Message-ID: In , Wensui Liu wrote: > I know dict['row1'] will always work. but it will only get 1 row out > of the dict. is there anyway i can get multiple (>1) rows out of dict > by directly refeencing them, something like dict[['row1', 'row2']]. Not by directly referencing them, but with a list comprehension:: result = [the_dict[key] for key in ('row1', 'row2', 'row3')] Ciao, Marc 'BlackJack' Rintsch From tubby at bandaheart.com Tue Feb 27 13:21:03 2007 From: tubby at bandaheart.com (tubby) Date: Tue, 27 Feb 2007 13:21:03 -0500 Subject: threading a thread Message-ID: I have a program written in Python that checks a class B network (65536 hosts) for web servers. It does a simple TCP socket connect to port 80 and times out after a certain periods of time. The program is threaded and can do all of the hosts in about 15 minutes or so. I'd like to make it so that I can check for other open ports (instead of just port 80) and I'd like to thread the port checks as well. Right now I'm just prototyping and the threaded hosts portion works very well for my needs. I'd just like to add a threaded ports check and wanted to know if anyone had done something similar in Python. Many thanks From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Feb 16 13:37:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 16 Feb 2007 19:37:13 +0100 Subject: Any Idea about thread safe issue with python References: <1171623555.377250.228240@j27g2000cwj.googlegroups.com> Message-ID: <53mbupF1sepr5U1@mid.individual.net> mralokkp wrote: > I need help guys. I have a code running properly and execute again > after a certain time. > In Simple words [incomplete and useless code line] is not solving > my purpose. Would any body like to help. Please be so kind and read this paragraph: http://www.catb.org/~esr/faqs/smart-questions.html#explicit Regards, Bj?rn -- BOFH excuse #331: those damn raccoons! From donmorrison at gmail.com Wed Feb 7 16:09:00 2007 From: donmorrison at gmail.com (Don Morrison) Date: Wed, 7 Feb 2007 13:09:00 -0800 Subject: string.find for case insensitive search In-Reply-To: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: string.find is deprecated as per the official python documentation. take a look at the "re" module On 7 Feb 2007 12:53:36 -0800, Johny wrote: > Is there a good way how to use string.find function to find a > substring if I need to you case insensitive substring? > Thanks for reply > LL > > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 16:52:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 22:52:15 +0100 Subject: xml.dom.minidom memory usage In-Reply-To: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> References: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> Message-ID: <45c25a17$0$25086$426a34cc@news.free.fr> Dan a ?crit : > I'm using python's xml.dom.minidom module to generate xml files, and > I'm running into memory problems. The xml files I'm trying to create > are relatively flat, with one root node which may have millions of > direct child nodes. Woops ! You're looking for trouble. > > So, my questions are (1) am I doing something dumb in the script Yes : using minidom !-) > that > stops python from collecting temp garbage? That's not the problem. The problem is with how xml dom APIs work: they build the whole damn tree in memory. > (2) If not, is there > another reasonable module to generate xml (as opposed to parsing it), > or should I just implement my own xml generation solution? You should have a look at Genshi: http://genshi.edgewall.org/ From robert.kern at gmail.com Tue Feb 6 15:05:45 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 06 Feb 2007 14:05:45 -0600 Subject: Trouble fixing a broken ASCII string - "replace" mode in codec not working. In-Reply-To: References: Message-ID: John Nagle wrote: > I'm trying to clean up a bad ASCII string, one read from a > web page that is supposedly in the ASCII character set but has some > characters above 127. And I get this: > > File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch > sitetext = sitetext.encode('ascii','replace') # force to clean ASCII > > UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151: > ordinal not in range(128) > > Why is that exception being raised when the codec was told 'replace'? The .encode('ascii') takes unicode strings to str strings. Since you gave it a str string, it first tried to convert it to a unicode string using the default codec ('ascii'), just as if you were to have done unicode(sitetext).encode('ascii', 'replace'). I think you want something like this: sitetext = sitetext.decode('ascii', 'replace').encode('ascii', 'replace') -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From skip at pobox.com Wed Feb 14 19:09:14 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 14 Feb 2007 18:09:14 -0600 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <17875.42154.857324.181836@montanaro.dyndns.org> >> Concatenating tuples and lists seems logical if you think of tuples >> as sequences. If you think of them more like Pascal records or C >> structs instead (I believe that's Guido's perspective on tuples) then >> it makes no sense at all. James> Then iterating over them makes no sense? I agree that tuples are a bit schizophrenic. They really are sequences from an implementation standpoint, but from a logical standpoint it's maybe best not to think of them that way. That said, this: for x in (1,2,3): pass is a skosh faster (perhaps an immeasurably small skosh) than this: for x in [1,2,3]: pass so people will probably continue to use tuples instead of lists in these sorts of situations. For an example of the struct-ness of a tuple consider the output of os.stat: >>> import os >>> s = os.stat("/etc/hosts") >>> s (33188, 34020475L, 234881029L, 1, 0, 0, 214L, 1170562950, 1124700602, 1142602578) >>> s.st_mtime 1124700602.0 >>> s[0] 33188 >>> type(s) It's effectively a tuple with field names. I don't know when the switch occurred (it's in 2.2, as far back as my built interpreter versions currently go), but back in the day os.stat used to return a plain old tuple. I have no idea if the schizophrenic personality of tuples will improve with drugs^H^H^H^H^H Python 3, but I wouldn't be at all surprised if it did. Skip From jeremit0 at gmail.com Wed Feb 7 08:28:47 2007 From: jeremit0 at gmail.com (jeremito) Date: 7 Feb 2007 05:28:47 -0800 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <45c8f5b5$0$19714$426a74cc@news.free.fr> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> <1170795607.938431.144340@p10g2000cwp.googlegroups.com> <45c8f5b5$0$19714$426a74cc@news.free.fr> Message-ID: <1170854927.013819.320020@a75g2000cwd.googlegroups.com> On Feb 6, 5:10 pm, Bruno Desthuilliers wrote: > jeremito a ?crit : > > On Feb 6, 2:36 pm, Bruno Desthuilliers > wrote: > > > > (snip) > > >>Here's an alternative implementation, so you get the idea. > >> > >>class Xs(dict): > > oops ! I meant: > class Xs(object): > > of course... > > (snip) > > > I guess I just > > need more experience. > > Possibly - but not only. You may want to have a look at the > FineManual(tm) for all this kind of "magic", starting with :http://docs.python.org/ref/specialnames.htmlhttp://docs.python.org/ref/sequence-types.html > > HTH Thanks again! Sometimes the problem is simply not knowing where to find the documentation, or finding the right portion of the documentation. Your help has been invaluable. Jeremy From lionchao at gmail.com Sat Feb 24 22:29:53 2007 From: lionchao at gmail.com (Eric CHAO) Date: Sun, 25 Feb 2007 11:29:53 +0800 Subject: convert python scripts to exe file Message-ID: I know py2exe can make an exe file. But python runtime dll is still there. How can I combine the dll file into the exe, just make one file? Thanks. From gagsl-py at yahoo.com.ar Fri Feb 9 00:49:04 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Feb 2007 02:49:04 -0300 Subject: strange problem using modules from my own package. In-Reply-To: References: Message-ID: <20070209054912.937F11E4010@bag.python.org> At Friday 9/2/2007 02:10, you wrote: Please keep posting on the list - you'll reach a whole lot of people there... >On 09/02/07, Gabriel Genellina wrote: >> >>It's a bit hard to tell from your description - would be better if you had >>copied the exact error messages. >>But the overall architecture looks wrong - a package is a *library*, and >>it is *used* by others. >>Your main application should be a standalone script that uses (imports) >>the package. >>Look at how other Python applications are structured. > >yes I have a different script to run the package. but I was just >checking the script because mainwindow is any ways the main window of >my application. >well, the error is, >import error: no module pbcf. >actually pbcf is the name of my package not the module. >is it because I am using a module on itself from within the package? Using again my crystal ball I can see this statement: import pbcf or perhaps: from pbcf import something (it's not so clear...) written inside any module in your package. So, your package must be installed in any directory listed in sys.path, for python to be able to actually find it; perhaps in site-packages. Also, if you try to execute a module "inside" your package, it does not even *know* that it lives inside a package. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bfritz at sprynet.com Sat Feb 17 00:53:10 2007 From: bfritz at sprynet.com (Captain) Date: Sat, 17 Feb 2007 05:53:10 GMT Subject: WHAT IS THIS? Message-ID: Just bought a new PC with Windows XP Media Edition. I have two entries in the "Add or Remove Programs" section of Control Panel, but there is no corresponding item in the Start Menu. One entry says: Python 2.2.3 and the other says: Python 2.2 pywin32 extensions (build203).. The size for each is 29.28mb. I gather Python is a programming language, but I am wondering why it was installed on my PC, and is it safe to remove it? I have no intention of learning the program. Thanks in advance From ms at cerenity.org Sun Feb 11 08:14:52 2007 From: ms at cerenity.org (Michael) Date: Sun, 11 Feb 2007 13:14:52 +0000 Subject: Shed Skin Optimizing Python-to-C++ Compiler 0.0.19 References: Message-ID: <45cf1609$0$8717$ed2619ec@ptn-nntp-reader02.plus.net> Mark Dufour wrote: > This > latest release adds basic support for iterators and generators Oooh, I may try our miniaxon tutorial against shed skin in that case. (ie http://kamaelia.sourceforge.net/MiniAxon/) Great to see you're plowing through this BTW ! Michael. -- Kamaelia Project Lead http://kamaelia.sourceforge.net/Home http://yeoldeclue.com/blog From http Fri Feb 2 14:41:03 2007 From: http (Paul Rubin) Date: 02 Feb 2007 11:41:03 -0800 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <7xr6t89wkw.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > How about because thats what you pay them for? Seriously. Do you even > think about what you're saying? Python needs to move MySQL (and only > MySQL, of course) into the core because installing packages is too > much of a burden for hosting companies? What does "batteries included" mean to you? To me, it means you don't have to install add-ons. If you don't like that, complain to the people who put that into the Python sales pitch, not to me. From eric_brunel at despammed.com Mon Feb 26 03:32:45 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 26 Feb 2007 09:32:45 +0100 Subject: Question about idiomatic use of _ and private stuff. References: <45e1f41d$0$25582$426a74cc@news.free.fr> Message-ID: On Sun, 25 Feb 2007 22:12:52 +0100, Bruno Desthuilliers wrote: > Steven W. Orr a ?crit : >> I understand that two leading underscores in a class attribute make the >> attribute private. > > Nope. It doesn't make it "private", it mangles the attribute name with > the class name (ie : Bar.__mangled will become Bar._Bar__mangled > everywhere except inside Bar). This is only useful when you want to make > sure an attribute will not be *accidentally* accessed by a child class. > FWIW, I've found it of very limited use so far... If I'm not mistaken, it was originally introduced to allow designers of sub-classes to use any attribute name they liked, without bothering to go up the whole class hierarchy to make sure this name was not already used. Even if Python relies far less on inheritance than other languages, class hierarchies are sometimes quite large. If in addition, each class has a lot of attributes, looking for an unused name can become long and painful. In this context, the double-underscore may be a blessing. My [??$?]0.02... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From usable.thought at gmail.com Fri Feb 16 12:24:48 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 09:24:48 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: <1171644713.924096.173940@h3g2000cwc.googlegroups.com> References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> <1171642551.277929.233540@l53g2000cwa.googlegroups.com> <1171644713.924096.173940@h3g2000cwc.googlegroups.com> Message-ID: <1171646688.785593.275060@j27g2000cwj.googlegroups.com> On Feb 16, 11:51 am, "Endless Story" wrote: > I did add c:/cywgin to the path, don't remember why now. Having looked at the Cygwin user manual, I think I probably did this as the result of misunderstanding the installation process. A PATH variable is needed, but it can go into cygwin.bat. From mail at timgolden.me.uk Mon Feb 26 11:56:30 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Feb 2007 16:56:30 +0000 Subject: ez_setup.py In-Reply-To: <45E30F7E.6020509@knmi.nl> References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> <45E305D0.4010806@timgolden.me.uk> <45E3075E.2090308@knmi.nl> <45E3083F.2020303@timgolden.me.uk> <45E30AE9.40900@knmi.nl> <45E30C8A.1020307@timgolden.me.uk> <45E30F7E.6020509@knmi.nl> Message-ID: <45E3113E.2060604@timgolden.me.uk> Nader Emami wrote: > Tim Golden wrote: >> Nader Emami wrote: >>> Tim Golden wrote: >>>> Nader Emami wrote: >>>> >>>>>>> How can do the second solution, (take off the home from Python >>>>>>> path)? >>>>>> >>>>>> Depends on your setup. Since you're on *nix, I can't >>>>>> test whether $HOME is automatically on sys.path (it >>>>>> isn't on Win32). Are you running *in* /usr/people/emami? >>>>>> If so, go somewhere else before you run ez_setup. Check >>>>>> your PYTHONPATH env var; perhaps reset it before >>>>>> running ez_setup. There are other more obscure possibilities >>>>>> to do with things set in site.py but they're less likely. >>>>>> >>>>>> TJG >>>>> I have a Linux and I don't have any PYTHONPTH variable, because if >>>>> I run the next command it returns nothig: >>>>> >>>>> %env | grep -i pythonpath or >>>>> %env | grep -i python >>>> >>>> I'm no expert here, but I believe that Linux is >>>> case-sensitive, so you'd need to do: >>>> >>>> env | grep PYTHONPATH >>>> >>>> TJG >>> 'grep' with 'i' option can catch both of them. I have done with >>> capital letters also and the answer stays the same: >>> %env | grep PYTHONPATH of %env | grep PTYTHON >> >> OK. Keep copying to the list, please. As I said, I'm not >> a *nix person (and I'm running here on Windows) so you'll >> get a more informed and wider audience from c.l.py. >> >> If there's no PYTHONPATH that means it's just down to >> your system setup what goes on the path. Try (from >> within the python interpreter): >> >> >> import sys >> for i in sys.path: >> print i >> >> >> >> Do you see your home directory there? >> >> TJG > This is the result of the code: > /usr/people/emami/lib/python24.zip > /usr/people/emami/lib/python2.4 > /usr/people/emami/lib/python2.4/plat-linux2 > /usr/people/emami/lib/python2.4/lib-tk > /usr/people/emami/lib/python2.4/lib-dynload > /usr/people/emami/lib/python2.4/site-packages (Sigh). Copying back to the list. So, are you running in /usr/people/emami when you're call ez_setup? TJG From robert.kern at gmail.com Sat Feb 3 02:37:37 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 03 Feb 2007 01:37:37 -0600 Subject: using numpy to do linear algebra In-Reply-To: <1170487229.700734.80930@k78g2000cwa.googlegroups.com> References: <1170487229.700734.80930@k78g2000cwa.googlegroups.com> Message-ID: Michael O'Brien wrote: > Hola~ > > I have a large array of points (over a million). I would like to > multiply each point in the array by a 4x4 matrix. I keep thinking > there should be an easy way to do this using numpy, but I can't figure > out the mojo to do it. Is that possible? numpy questions are best asked (and best answered!) on the numpy list. http://www.scipy.org/Mailing_Lists Now, you haven't given quite enough information for us to answer your question definitively. What's the format of your array of points? Is it (N, 4) or (4, N)? Is your (4, 4) matrix set up to left-multiply column-vectors or right-multiply row-vectors? I'm guessing that you have an (N, 4) array of N row-vectors and your (4, 4) matrix is set up to left-multiply column-vectors, as is the usual case. Since you have row-vectors and your matrix needs column-vectors, you need to transpose the matrix and multiply it on the *right* of your vectors array. dot(n_x_four, four_x_four.T) If the matrix had already been set up to right-multiply row-vectors, then you could skip the transpose. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Sat Feb 3 12:56:28 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 3 Feb 2007 09:56:28 -0800 Subject: Checking default arguments In-Reply-To: References: Message-ID: <1170525388.330296.71480@j27g2000cwj.googlegroups.com> On Feb 2, 1:30 pm, i... at ifi.uio.no (Igor V. Rafienko) wrote: > Hi, > > I was wondering whether it was possible to find out which parameter > value is being used: the default argument or the user-supplied one. > That is: > > def foo(x, y="bar"): > # how to figure out whether the value of y is > # the default argument, or user-supplied? > > foo(1, "bar") => user-supplied > foo(1) => default > > {}.pop seems to be able to make this dictinction. > > I've checked the inspect module, but nothing obvious jumped at me. Any > hints? I don't know why you might want to distinguish between the two in practice (the unique object idea mentioned in other posts should handle most uses cases), but if you insist, here's one way to do it: import inspect def determine_supplied_args(func): varnames,_,_,defaults = inspect.getargspec(func) num_varnames = len(varnames); num_defaults = len(defaults) def wrapper(*args, **kwds): max_defaults = min(num_defaults, num_varnames-len(args)) supplied_args = dict(zip(varnames,args)) default_args = {} if max_defaults > 0: for var,default in zip(varnames[-max_defaults:], defaults[- max_defaults:]): # if passed as keyword argument, don't use the default if var in kwds: supplied_args[var] = kwds[var] else: default_args[var] = default wrapper._supplied_args = supplied_args wrapper._default_args = default_args return func(*args, **kwds) return wrapper @determine_supplied_args def f(x, y='bar', z=None, *args, **kwds): print "Supplied:", f._supplied_args print "Default:", f._default_args >>> f(1) Supplied: {'x': 1} Default: {'y': 'bar', 'z': None} >>> f(1, 'bar') Supplied: {'y': 'bar', 'x': 1} Default: {'z': None} >>> f(1, y='bar') Supplied: {'y': 'bar', 'x': 1} Default: {'z': None} >>> f(1, z=None) Supplied: {'x': 1, 'z': None} Default: {'y': 'bar'} >>> f(1, 'bar', None) Supplied: {'y': 'bar', 'x': 1, 'z': None} Default: {} >>> f(1, 'bar', z=None) Supplied: {'y': 'bar', 'x': 1, 'z': None} Default: {} >>> f(1, z=None, y='bar') Supplied: {'y': 'bar', 'x': 1, 'z': None} Default: {} Regards, George From horpner at yahoo.com Wed Feb 21 07:59:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 21 Feb 2007 13:59:33 +0100 Subject: eval('000052') = 42? References: <542nk8F1t6krbU1@mid.individual.net> Message-ID: On 2007-02-21, Andr? Malo wrote: > Astan Chee wrote: > >> Hi, >> I just tried to do >> eval('00052') and it returned 42. >> Is this a known bug in the eval function? Or have I missed the way eval >> function works? > > You know, it's just the answer to the ultimate question of > Life, the universe, and everything. Yeah, but I was hoping the question would've turned out better. -- Neil Cerutti From __peter__ at web.de Tue Feb 13 03:14:14 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Feb 2007 09:14:14 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> Message-ID: devicerandom at gmail.com wrote: > Thanks both for suggestions. I still think that using inheritance is > somehow cleanest in this case (I always hear the mantra "avoid > multiple inheritance!", but this is one of the cases it seems to make > a lot of sense to me), but it's nice food for thought/code anyway. "Avoid inheritance" would be almost as justified :-) Problems that may arise with this case of multiple inheritance: - If you need initializers, ensure that they are all invoked - What would you do about name clashes? To avoid them your plugins need to know about each other. - State (instance attributes) is shared among all your plugins. Since you call all base classes Commands, Python's double-underscore hack won't work. Peter From dustin.getz at gmail.com Mon Feb 5 05:10:11 2007 From: dustin.getz at gmail.com (dustin.getz at gmail.com) Date: 5 Feb 2007 02:10:11 -0800 Subject: python references Message-ID: <1170670211.817241.127310@v33g2000cwv.googlegroups.com> >>> from Numeric import zeros >>> p=zeros(3) >>> p array([0,0,0]) >>> p[0] 0 >>> x=p[0] >>> x=10 >>> p array([0,0,0]) #actual behavior #array([10,0,0]) #desired behavior I want x to be a C++-esque reference to p[0] for convenience in a vector3 class. i dont want accessor methods. i know python can do this, but it's been a long time since I used it and am unsuccessful in my googling and docreading. a little help please? From mail at microcorp.co.za Fri Feb 16 00:46:43 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 16 Feb 2007 07:46:43 +0200 Subject: Enter Enter... troubles References: <500853.58412.qm@web56004.mail.re3.yahoo.com> Message-ID: <007501c7518d$d70de880$03000080@hendrik> Sorin Schwimmer wrote: 8<------------------------- > def handler(self,event): > self.aButton.unbind('') > self.aButton.unbind('') 8<------------------------- > >The idea is to prevent a fast user (like my boss) to press repeatedly the "enter" >key and create havoc with self.property and localVar. But it doesn't work: my >boss manages to start at least twice the handler (which, among other things >creates a Toplevel, so I end up with a messy screen). I would have separate handlers for the two keys - should be slightly faster.. I generally use configure to change the button's command to a do nothing thing to sort out the multiple click maniacs. hth - Hendrik From deets at nospam.web.de Sun Feb 18 10:04:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Feb 2007 16:04:27 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: <53r88cF1tq2vsU1@mid.uni-berlin.de> Stef Mientki schrieb: >>> - designing the GUI will cost me about 2 .. 3 times as much in Python >> >> You mean delphi here I presume? > No, but if that's your believe .. I'm sorry, that was a misreading of mine. > Some examples: > - Creating a treeview (like in the M$ explorer), with full edit > capabilities and full drag & drop > facilities: Delphi takes about 40 lines of code (most of them even ^C ^V). As does Qt. > - Creating a graphical overview of relations between database tables, > which can be graphical > manipulated by the user (like in M$ Access): Delphi 20 lines of code. > I wonder what this costs in Python ? Qt has data-aware classes, albeit I didn't play with them. > I've been using Python for just 2 months, and didn't try any graphical > design, > I've other priorities first. May I cite you: """ - Python is not capable of doing everything I need (almost all interactive actions are very primitive and crashes a lot) """ To me, that sounded like you were talking about gui-design. Diez From gonzlobo at gmail.com Mon Feb 5 21:19:32 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Mon, 5 Feb 2007 19:19:32 -0700 Subject: Decimating Excel files In-Reply-To: <1170727172.316685.49980@h3g2000cwc.googlegroups.com> References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> <1170725241.634632.100830@v45g2000cwv.googlegroups.com> <1170727172.316685.49980@h3g2000cwc.googlegroups.com> Message-ID: I tried to open the file with Kate, trust me, it's an Excel file. I'm using xlrd, it works beautifully (although come to think of it, I haven't tried writing to an .xls file yet... hmmm) > To clear up the doubts, I'd suggest that the OP do something like this > at the Python interactive prompt: > > print repr(open('nasty_file.xls', 'rb').read(512)) > > If that produces recognisable stuff, then it's a CSV file (or a tab > separated file) masquerading as an XLS file. From moin at blackhole.labs.rootshell.ws Tue Feb 6 20:53:45 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Tue, 6 Feb 2007 19:53:45 -0600 Subject: multithreading concept Message-ID: <001901c74a5a$ce555780$0202a8c0@cisco.com> Hi Folks, Python is praised about - me too. But at one instance it fails. It fails to behave as a true multi-threaded application. That means utilizing all the CPUs parallely in the SMP efficiently stays as a dream for a Python Programmer. Discussion threads say its due to GIL - global interpreter lock. But nobody has mentioned any alternative to that apart from suggestions like "Code it in C" and POSH (http://poshmodule.sf.net). Is there any other way we can make Python programs really multithreaded in real sense. Moin From nospam at riddergarn.dk Tue Feb 13 13:43:39 2007 From: nospam at riddergarn.dk (NOSPAM plz) Date: Tue, 13 Feb 2007 19:43:39 +0100 Subject: Regex highlight html In-Reply-To: References: <45D1B976.3080704@riddergarn.dk> Message-ID: <45D206DB.3080909@riddergarn.dk> Gabriel Genellina skrev: > En Tue, 13 Feb 2007 10:13:26 -0300, NOSPAM plz > escribi?: > > >> I want to write a function that highlights html code. >> > > Well, it's already done, you have Pygments http://pygments.pocoo.org/ > and SilverCity http://silvercity.sourceforge.net/ > > >> I have read the wiki page >> http://en.wikipedia.org/wiki/Regular_expressions >> > > Ouch... Read some previous posts on why it's not a good idea to use > regexps for parsing html code. > > Thanks just what i needed :D! From http Sat Feb 3 12:08:27 2007 From: http (Paul Rubin) Date: 03 Feb 2007 09:08:27 -0800 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> <7xk5yz2q42.fsf@ruckus.brouhaha.com> <52jt3eF1p85tbU1@mid.uni-berlin.de> Message-ID: <7xy7nf1850.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > And they certainly require special treatment like putting them in the > classpath, setting up the project directory and the like - no simple > import will work out of the box, as it would witch python standard lib > drivers. Well, that's nowhere near as big a deal as having yet another set of vendors or maintainer to deal with. Minimizing configuration is nice, but getting your software from as few different sources as possible is also a big win. From bignose+hates-spam at benfinney.id.au Tue Feb 27 21:35:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 13:35:21 +1100 Subject: how to convert an integer to a float? References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> <54k05cF218n10U1@mid.individual.net> <4c0048df0702271808w512cc605o5ecb8abf063c5eb1@mail.gmail.com> Message-ID: <877iu3xb4m.fsf@benfinney.id.au> Please don't top-post; instead, reply below the lines you're responding to, and trim any irrelevant lines from the original. Subscriber123 writes: > How did the new division ever get approved?! By being introduced as a PEP, which is now numbered PEP 238. > That's not pythonic! What if you then need to divide two integers > and find an element in a list or dict? Then your code is dependent on ambiguous behaviour which has changed in newer Python versions. As described in the above document, the '//' operator will unambiguously request floor division, even in older versions of Python. > I know that at the moment it is not implemented unless imported from > __future__, but I expect that it eventually might be. Please read PEP 238 to see the implementation plan. > That would be a problem with backwards compatibility. The older Python versions aren't going away. Anyone who wants their old code to work with new versions of Python has a responsibility to see what parts of their code need to be updated. -- \ "My roommate got a pet elephant. Then it got lost. It's in the | `\ apartment somewhere." -- Steven Wright | _o__) | Ben Finney From supervau at gmail.com Sun Feb 11 17:11:29 2007 From: supervau at gmail.com (Frank) Date: 11 Feb 2007 14:11:29 -0800 Subject: Saving PyOpenGl figures as ps Message-ID: <1171231889.667812.72930@q2g2000cwa.googlegroups.com> Hi, I installed pyopengl (opengl for python) on my linux box and everything works fine. But now I want to save the generated images as, e.g., ps or eps. How can I do that and how can I adjust the resolution (if necessary)? This is probably simple but for some reason I can not find out how to do that. I appreciate every hint! Thanks, Frank From jmcmonagle at velseis.com.au Thu Feb 15 20:25:40 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 16 Feb 2007 11:25:40 +1000 Subject: Tkinter __call__ In-Reply-To: References: Message-ID: <45D50814.3020004@velseis.com.au> Gigs_ wrote: > from Tkinter import * > from tkFileDialog import askopenfilename > from tkColorChooser import askcolor > from tkMessageBox import askquestion, showerror > from tkSimpleDialog import askfloat > > demos = { > 'Open': askopenfilename, > 'Color': askcolor, > 'Query': lambda: askquestion('Warning', 'You typed > "..."\nConfirm?'), > 'Error': lambda: showerror('Error!', "He's dead, Jim"), > 'Input': lambda: askfloat('Entry', 'Enter credit card number') > } > > > class Demo(Frame): > def __init__(self, parent=None): > Frame.__init__(self, parent) > self.pack() > Label(self, text="Basic demos").pack() > for (key, value) in demos.items(): > func = (lambda key=key: self.printit(key)) > Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) > def printit(self, name): > print name, 'returns =>', demos[name]() > > > I have tried but cant get it to work properly. > I want to instead printit method to put __call__ and call it like that > Can someone help me, please? Add the following lines to the end of your script and all should work as expected: root = Tk() app = Demo(root) root.mainloop() From sjmachin at lexicon.net Fri Feb 23 10:35:40 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Feb 2007 07:35:40 -0800 Subject: Finding non ascii characters in a set of files In-Reply-To: <1172243566.906121.189930@h3g2000cwc.googlegroups.com> References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: <1172244940.559402.17040@j27g2000cwj.googlegroups.com> On Feb 24, 2:12 am, "Peter Bengtsson" wrote: > On Feb 23, 2:38 pm, b... at yahoo.com wrote: > > > Hi, > > > I'm updating my program to Python 2.5, but I keep running into > > encoding problems. I have no ecodings defined at the start of any of > > my scripts. What I'd like to do is scan a directory and list all the > > files in it that contain a non ascii character. How would I go about > > doing this? > > How about something like this: > content = open('file.py').read() > try: > content.encode('ascii') > except UnicodeDecodeError: > print "file.py contains non-ascii characters" From simon at brunningonline.net Wed Feb 28 05:23:59 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 28 Feb 2007 10:23:59 +0000 Subject: msvcr71.dll In-Reply-To: References: Message-ID: <8c7f10c60702280223s7a2059b6gdaa69169c5209573@mail.gmail.com> On 2/28/07, Konte wrote: > Are there news about the impossibility of redistributing msvcr71.ddl > with own stand-alone application written in python for who doesn't have > MSVC7 license? Last I heard the consensus was that it's OK to distribute msvcr71.ddl. But IANAL, and neither is anyone else that I've heard discussing the matter. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning MSN: small_values From ptmcg at austin.rr.com Thu Feb 15 02:34:52 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 Feb 2007 23:34:52 -0800 Subject: Method overloading? In-Reply-To: References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <1171519115.463977.220700@j27g2000cwj.googlegroups.com> Message-ID: <1171524892.726529.273500@q2g2000cwa.googlegroups.com> On Feb 15, 12:23 am, Steven D'Aprano wrote: > On Wed, 14 Feb 2007 21:58:35 -0800, Paul McGuire wrote: > > No, Python does not do overloading as part of the language, you have > > to do the variable argument interpretation for yourself. > > > For instance, if you want a method to accept a single argument of > > various types, it would look something like this: > > > def multiAccept( argOfVariousTypes ): > > if isinstance(argOfVariousTypes,int): > > # treat like an int > > elif isinstance(argOfVariousTypes,float): > > # treat like a float > > elif isinstance(argOfVariousTypes,(list,tuple)): > > # treat like a container > > Is that really called "overloading"? I've never (knowingly) come across > the term being used in that context before. I've always known that as > "multiple dispatch" or "polymorphism", depending on whether you or the > compiler handles the dispatching. > Well, I think "overloading" and "Python" may not even belong in the same sentence, actually. "Overloading" is used in C++, Java and C# to describe a single method name with multiple signatures. It is not really possible to implement such a thing in Python, which just binds methods to names, and duplicate definitions of methodX just replace the former with the latter. But from the standpoint of the caller, calls to methodX() with various numbers and types of arguments looks just the same as it does in Java or C# with method overloading, and could reasonably be thought of as such - what does the caller care how methodX handles these various calls, whether with 1 hyper-adaptive method implementation or a dozen type-specific ones? I've had this discussion before, but I personally tend to reserve the term "polymorphism" for instance-level behavior, such as when a collection of instances that all derive from a common base class have overridden method definitions. The typical example is a list of Shapes, each implementing its own draw() method, so that they polymorphically do their subclass-appropriate draw behavior. Or for a Strategy pattern implementation (one of my favorite), where derived strategy classes implement a base interface with their separate behaviors, and each is accessed through the interface definition. The beauty of Python's duck-typing is that this same kind of polymorphism can be achieved without the burden of class inheritance hierarchies. As long as the instances referenced all implement methodX(), Python is happy. If I'm desperate, I could even dynamically attach a do-nothing or default version of such a method if it were not already defined for an instance. Try *that* in C++ (without a horrifying haystack of angle brackets)! I have heard "overloading" referred to as "method polymorphism", but I think this is just a dilution of the "polymorphism" term, with no additional knowledge transfer gained. -- Paul From aahz at pythoncraft.com Wed Feb 14 18:40:31 2007 From: aahz at pythoncraft.com (Aahz) Date: 14 Feb 2007 15:40:31 -0800 Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: In article <1171303251.796306.79520 at p10g2000cwp.googlegroups.com>, Thomas Nelson wrote: > >I realize I'm approaching this backwards from the direction most >people go, but does anyone know of a good c/c++ introduction for >python programmers? This isn't an introduction, but you should probably also pick up _Effective C++_ (and possibly _More Effective C++_, though that seems less useful to me). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From jstroud at mbi.ucla.edu Sat Feb 10 07:40:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 10 Feb 2007 12:40:00 GMT Subject: Distributing Python Applications In-Reply-To: <1171110089.040455.154690@v33g2000cwv.googlegroups.com> References: <1171110089.040455.154690@v33g2000cwv.googlegroups.com> Message-ID: Finger.Octopus at gmail.com wrote: > Hello, > > It has been such a painful thing for me. As I made a program to > encrypt files, now I want to distribute that program over other > computers. I created .EXE file with py2exe but the "dist" folder makes > around 2 mb and it restricts for the python DLL to be within the same > folder. Is there any easy way to get this thing done in just one exe > file? I mean if I do interfacing with C/C++ will it work for me and if > I do interfacing with C/C++ will it be necessary on the other computer > to have python installed on it? > > > Thanks in advance... > No need for python to be installed. Don't worry about 2 MB downloads. Probably, if users are savvy enough to need encryption, they have the download speeds and hard drive space to handle 2 MB. Check out pyinstaller also, but what your really need is Innosetup. Its beautiful. James From gerdusvanzyl at gmail.com Sun Feb 25 19:00:55 2007 From: gerdusvanzyl at gmail.com (AngelBlaZe) Date: 25 Feb 2007 16:00:55 -0800 Subject: Working with C object of python object (pycairo,ctypes) Message-ID: <1172448055.159739.220810@m58g2000cwm.googlegroups.com> Can you access the c object of a python object directly? Can this be done in ctypes or directly throught python functions without reverting to forking the python module? scanario: I have pyctx object that i get in python like this: pyctx = cairo.Context(surface) defined in the python extension this: typedef struct { PyObject_HEAD cairo_t *ctx; PyObject *base; /* base object used to create context, or NULL */ } PycairoContext; PyObject * PycairoContext_FromContext(cairo_t *ctx, PyTypeObject *type, PyObject *base) { PyObject *o; assert (ctx != NULL); if (Pycairo_Check_Status (cairo_status (ctx))) { cairo_destroy (ctx); return NULL; } if (type == NULL) type = &PycairoContext_Type; o = PycairoContext_Type.tp_alloc (type, 0); if (o) { ((PycairoContext *)o)->ctx = ctx; Py_XINCREF(base); ((PycairoContext *)o)->base = base; } else { cairo_destroy (ctx); } return o; } Now my question is: Is there any way to access/get a pointer to PycairoContext->ctx from python object (pyctx)? A long shot i know :-) From S.Mientki-nospam at mailbox.kun.nl Sun Feb 4 05:57:18 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 04 Feb 2007 11:57:18 +0100 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Message-ID: Jussi Salmela wrote: > Stef Mientki kirjoitti: >> Is it possible to change the searchpath for modules on the flight, >> under winXP ? > What do you mean by *on the flight*: inside IDLE? using the command line? No, I run Python, embedded from within a Delphi program. >> Most preferred is some command to extend the searchpath. >> (the environment variable PYTHONPATH needs a reboot) >> > No, it doesn't. PYTHONPATH can be updated somewhere in the environment > options (sorry: I've got a Finnish language XP version, so I don't > remember the exact terms) and the new path comes in effect immediately > i.e. the launches after that see the new definition. > Through "My computer" | properties | advanced | Environment Variables" you have to reboot. But as I remember well there should be a way, (through the registry or DOS-box ?) but I don't want to mess in the registry, I want to keep my application portable. But the suggestion of Rob, looks perfect. thanks anyway, Stef Mientki From deets at nospam.web.de Wed Feb 14 06:34:45 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Feb 2007 12:34:45 +0100 Subject: calling php function from python References: Message-ID: <53gaelF1t13c2U1@mid.uni-berlin.de> mark wrote: > is it possible to call a php function from python and use a class from > php in python? i want to use mmslib which creates mms messages and the > only implementation is a php mmslib implementation. Do yourself - and the python community... :) - a favor and just translate the mmslib code to python. It is easy and straightforward todo. Diez From nszabolcs at gmail.com Sat Feb 10 05:52:10 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 10 Feb 2007 02:52:10 -0800 Subject: python linux distro In-Reply-To: References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> <1170955617.478249.82460@m58g2000cwm.googlegroups.com> <1171057671.866940.269130@v33g2000cwv.googlegroups.com> Message-ID: <1171104730.607570.313450@l53g2000cwa.googlegroups.com> > ^was(is)^may one day be, but probably not,^ > > From the quoted page: > > """The project is in an early development phase and as of January 2007, > no significant progress was being made due to lack of developer time.[5]""" well actually i managed to boot unununium in qemu so it _is_ an os but obviously there isn't much code and the devs gave up so that's why it _was_ an os project anyway it was not an os about python, but a desktop os with a highly different approach from current os-es they just happen to use a lot of python there were a lot of interesting ideas so the mail archives might be useful for anyone who is interested in os development http://unununium.org/pipermail/uuu-devel/ From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 18:53:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 00:53:36 +0100 Subject: idea for testing tools In-Reply-To: <87ejp1mzla.fsf@arcor.de> References: <87ejp1mzla.fsf@arcor.de> Message-ID: <45ca5f5a$0$26771$426a74cc@news.free.fr> Jens Theisen a ?crit : > Hello, > > I find it annoying that one has to write > > self.assertEqual(x, y) > > rather than just > > assert x == y > > when writing tests. This is a nuisance in all the programming > languages I know of (which are not too many). http://codespeak.net/py/current/doc/test.html#assert-with-the-assert-statement From Robert.Katic at gmail.com Sun Feb 18 02:20:33 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 17 Feb 2007 23:20:33 -0800 Subject: Getting a class name In-Reply-To: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> Message-ID: <1171783233.733860.143500@k78g2000cwa.googlegroups.com> I suppose that you wont get class name into its code (or before definition end) but not into a method definition. import sys def getCodeName(deap=0): return sys._getframe(deap+1).f_code.co_name class MyClass (object): name = getCodeName() + '!' From marco at waven.com Sun Feb 25 04:12:32 2007 From: marco at waven.com (Marco) Date: Sun, 25 Feb 2007 17:12:32 +0800 Subject: select which lib for iNet? Message-ID: <5c62a320702250112u4c4fb047u50144a4124e1d620@mail.gmail.com> Hello everyone, I wanta know why (Py)Qt has its own lib on socket/ sql/ openGL,etc ? Is the lib better than standard lib? Thank you! -- LinuX Power From bearophileHUGS at lycos.com Thu Feb 1 05:51:04 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Feb 2007 02:51:04 -0800 Subject: pil, histogram, mask In-Reply-To: References: Message-ID: <1170327064.008134.151480@v33g2000cwv.googlegroups.com> Daniel Nogradi > I don't need the histogram really, only the mean color > value, but as far as I can see the 'mean' attribute only applies to an > image and a mask can not be specified. You can slice parts of the image, and then use the ImageStat.Stat(im).mean On it. Bye, bearophile From http Sat Feb 3 10:57:51 2007 From: http (Paul Rubin) Date: 03 Feb 2007 07:57:51 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xejp89pa9.fsf@ruckus.brouhaha.com> Message-ID: <7xfy9n2pz4.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > I can't speak authoritatively for either PHP or J2SE, but I suspect the > latter at least has some signifiant monetary support (if not outright gobs > of human resources) from Sun. PHP seems to have a more limited application > domain (web apps) from which it has expanded a bit. Can I build a PHP site > out of the box with a PostgreSQL or Oracle backend? I believe so, from having looked at the docs a while back, but I haven't tried it. > Does J2SE have something comparable to Numpy or scipy? I don't think so, but Python doesn't either. > While might do the occasional bit of Python hacking for free, I still need > to put food on the table. My employer doesn't care if MySQLdb (to use one > of your examples) is delivered with Python or not. They aren't likely to > want to support me to solve your problems. The same could be said of Tkinter (a large and complex library module) or IDLE (a full blown mid-sized application shipped with Python). The answer is the same for both: if you don't need to use a given module, then don't. Why would I expect your employer to solve my problems anyway, even if they relate to some module that you actually use? From bbbart at inGen.be Fri Feb 2 08:08:21 2007 From: bbbart at inGen.be (Bart Van Loon) Date: Fri, 2 Feb 2007 18:08:21 +0500 Subject: How do I print out in the standard output coloured lines References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> <1170419225.989358.311600@h3g2000cwc.googlegroups.com> Message-ID: It was 2 Feb 2007 04:27:06 -0800, when cniharral at gmail.com wrote: > print "Hello World!!" > > I want it in red colour. > > That's all. Use colour escape codes: print "\033[1;31mHello World\033[0m" That's all. :-) -- groetjes, BBBart Golly, I'd hate to have a kid like me! -- Calvin From gregpinero at gmail.com Tue Feb 20 16:09:33 2007 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 20 Feb 2007 16:09:33 -0500 Subject: How to do a Decorator Here? In-Reply-To: <45DB5D4B.2060207@leapfrog3d.com> References: <312cfe2b0702201220n7d4d3e2o85faf8f6590564b5@mail.gmail.com> <45DB5D4B.2060207@leapfrog3d.com> Message-ID: <312cfe2b0702201309w299614e4v35a7233bacd70471@mail.gmail.com> On 2/20/07, Tim Mitchell wrote: > Hi Greg, > > Decorators would work fine if the the class you were working with was > _yours_ (ie. you wrote it), the problem here is that string.Template is > someone else's class that you're trying to modify. > > Here's how a decorator would work (unfortunately it involves subclassing) > > class myTemplate(string.Template): > def decorator(func): > def preprocess(*args, **kwargs): > # do preprocessing here > kwargs['var1'] = "greg" > # call actual method > return func(*args, **kwargs) > return preprocess > > @decorator > def substitute(self, *args, **kwargs): > return string.Template.substitute(self, *args, **kwargs) > > alternatively, if you don't mind changing the string.Template class > itself (and are sure that it's not used anywhere else that doesn't > require preprocessing) try: > > _substitute = string.Template.substitute > def subs(self, *args, **kwargs): > # do preprocessing here > kwargs['var1'] = "greg" > return _substitute(self, *args, **kwargs) > string.Template.substitute = subs > > Cheers > Tim > Thanks Tim. that makes sense now. Turns out my approach was too complicated anyway. I think I'm just going to use Cheetah :-) But at least I know decorators a little better. -Greg From gagsl-py at yahoo.com.ar Sat Feb 17 00:25:02 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 02:25:02 -0300 Subject: IOError: [Errno 4] Interrupted system call References: <1171594649.279210.139470@l53g2000cwa.googlegroups.com> <1171660060.302688.101070@k78g2000cwa.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 18:07:40 -0300, escribi?: > i don't have any signal handlers in my code, but i have no idea what > is going on in the internals of the pyQt framework that i'm using for > the GUI. > > p = subprocess.Popen('mycommand', shell=True, stdin=subprocess.PIPE, > stdout=subprocess.PIPE, close_fds=True) > output = p.stdout.readlines() There is a problem using a high-level approach like readlines(): *either* there is no exception, and you get all the output, *or* there is an exception and you get nothing. readlines() can't return a partial result *and* raise an exception at the same time. (Perhaps EINTR should be a special case, but currently it's converted into an IOError like all other error codes). You could read one character at a time with read(1) (to minimize the risk of data loss), or simply use a temporary file: "mycomand >temporary" and then read its contents. This appears to be the safest way. -- Gabriel Genellina From jgodoy at gmail.com Thu Feb 8 19:13:00 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Thu, 08 Feb 2007 22:13:00 -0200 Subject: uml and python References: <1170900832.692717.259160@l53g2000cwa.googlegroups.com> Message-ID: <87r6t0i3xv.fsf@gmail.com> "azrael" writes: > hy guys > > i've been googling and got several posts, but nothing that is a > satisfaction in my eyes. can someone tell me a nice uml diagram tool > with python export (if possible nice gui), or at least nice uml tool > > gpl or freeware (widows) prefered I like Umbrello (several OSs supported, including MacOS, Linux, *BSD and you probably can get it running in Windows though it might be somewhat hard...). -- Jorge Godoy From google at orcon.net.nz Sat Feb 17 20:10:50 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 17 Feb 2007 17:10:50 -0800 Subject: How do I save the contents of a text buffer In-Reply-To: References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> Message-ID: <1171761050.149331.208910@v45g2000cwv.googlegroups.com> I just included file opening code just to show how i read the file into the text buffer - I have no issues with this as such. Problem is only with the writing of the text buffer back to a file. When I try to write the buffer to a file it gave the following, Traceback (most recent call last): File "./configbox.py", line 78, in ? TextViewExample() File "./configbox.py", line 53, in __init__ outfile.write(textbuffer.get_text(0,1000, include_hidden_chars=True)) TypeError: start should be a GtkTextIter How can I use outfile.write() to wite the contents of the text buffer correctly? Thanks On Feb 18, 1:38 pm, "Gabriel Genellina" wrote: > En Sat, 17 Feb 2007 20:47:20 -0300, escribi?: > > > I'm using Python with pygtk and have this problem - I have read the > > contents of a file into the text buffer with this code, > > > infile = open("mytextfile", "r") > > if infile: > > string = infile.read() > > infile.close() > > textbuffer.set_text(string) > > Note that "if infile" does nothing: either the open succeeds and you get a > file object which is *always* True, or the open fails and raises an > exception and the code below never executes. > > > As a test, I tried to write the buffer back to a file with this code > > but did not work, > > "did not work" means... > > -- > Gabriel Genellina From python at rcn.com Sun Feb 18 01:19:41 2007 From: python at rcn.com (Raymond Hettinger) Date: 17 Feb 2007 22:19:41 -0800 Subject: Need an identity operator because lambda is too slow In-Reply-To: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> Message-ID: <1171779581.504807.113440@v45g2000cwv.googlegroups.com> [Deron Meranda >] I'm looking for something in > Python which would act like an identity operator, or I-combinator: a > do-nothing function. The best I know of is: (lambda x: x), but it is > not ideal. File a feature request on SourceForge and assign to me. This has come up a couple of times and would be trivial to implement in the operator or functools modules. Raymond From rmcore at gmail.com Wed Feb 14 04:20:23 2007 From: rmcore at gmail.com (Michael Bentley) Date: Wed, 14 Feb 2007 03:20:23 -0600 Subject: python not returning true In-Reply-To: <1171444128.138234.50640@l53g2000cwa.googlegroups.com> References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171437351.206085.236450@q2g2000cwa.googlegroups.com> <1171444128.138234.50640@l53g2000cwa.googlegroups.com> Message-ID: <462097E6-082A-4B22-AD8E-B98C4E5EF051@gmail.com> On Feb 14, 2007, at 3:08 AM, John Machin wrote: > So "enlightenment" has been verbed, has it? I didn't realise that the > language had been transitioned so far :-) *ALL* nouns may be verbed ;-) -michael --- # Something just doesn't seem right in those # "Every kiss begins with 'K'" commercials. >>> 'Every Kiss'.startswith('K') False From steven.bethard at gmail.com Wed Feb 21 14:31:52 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 21 Feb 2007 12:31:52 -0700 Subject: builtin set literal In-Reply-To: <1172084952.261314.4700@v33g2000cwv.googlegroups.com> References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <1171988959.628359.260710@l53g2000cwa.googlegroups.com> <1172084952.261314.4700@v33g2000cwv.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Steven Bethard: >> take a look at the current state of tuples: >> 1, 2 >> 1, >> () > > That's not a good situation. I presume the situation/syntax of tuples > in Python 2.x can't be improved. But can it be improved for Py 3.0? I'm not really losing any sleep over the current tuple syntax. ;-) The empty tuple is so uncommon in my code that the fact that it's spelled differently just doesn't bother me. And anyway, if I've learned anything from the Python community over the years, it's that syntax is best left to Guido. ;-) STeVe From fccoelho at gmail.com Thu Feb 22 07:53:02 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 04:53:02 -0800 Subject: plugin development best practices Message-ID: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> Hi, Nowadays the addition of functionality to programs by means of plugins is very frequent. I want to know the opinions of experienced Python developers about the best practices when it comes to developing a plugin system for a Python package. Should plugins be modules in a separate package? Should there be a registry of available plugins? how would such a registry be implemented? etc. thanks, Fl?vio From R.Brodie at rl.ac.uk Mon Feb 26 10:04:58 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 26 Feb 2007 15:04:58 -0000 Subject: Python / Socket speed References: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> Message-ID: wrote in message news:1172501644.228475.57540 at a75g2000cwd.googlegroups.com... > Seems like sockets are about 6 times faster on OpenSUSE than on > Windows XP in Python. > > http://pyfanatic.blogspot.com/2007/02/socket-performance.html > > Is this related to Python or the OS? It's 6 times faster even when not using Python, so what do you think? It's probably 'just' tuning though, the default window sizes are in the same ratio. From bbbart at inGen.be Mon Feb 5 05:44:33 2007 From: bbbart at inGen.be (Bart Van Loon) Date: Mon, 5 Feb 2007 15:44:33 +0500 Subject: in place-ness of list.append Message-ID: Hi all, I would like to find out of a good way to append an element to a list without chaing that list in place, like the builtin list.append() does. currently, I am using the following (for a list of integers, but it could be anything, really) #-------------------------------------------------- def addnumber(alist, num): """ work around the inplace-ness of .append """ mylist = alist[:] mylist.append(num) return mylist #-------------------------------------------------- and I am wondering if this is good practice or not. any advice on this matter? thanks! -- regards, BBBart "Someday I'll write my own philosophy book." -Calvin From jkn_gg at nicorp.f9.co.uk Wed Feb 14 06:45:35 2007 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 14 Feb 2007 03:45:35 -0800 Subject: c++ for python programmers In-Reply-To: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <1171453535.358374.305440@v33g2000cwv.googlegroups.com> Hi Thomas On Feb 12, 6:00 pm, "Thomas Nelson" wrote: > I realize I'm approaching this backwards from the direction most > people go, but does anyone know of a good c/c++ introduction for > python programmers? > They are not particularly aimed at Python programmers, but Bruce Eckel's "Thinking in C++" books are (a) excellent, and (b) freely downloadable, as well as purchasable in book form: http://www.mindview.net/ Bruce is a python fan FWIW ;-) HTH Jon N From theller at ctypes.org Wed Feb 28 13:32:05 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 28 Feb 2007 19:32:05 +0100 Subject: Py2EXE problem In-Reply-To: <2adc542f0702281009i2fd2c5e9nc626b7e34b80c270@mail.gmail.com> References: <2adc542f0702271839u472dc57aj8c9bc6d7ad3c660d@mail.gmail.com> <2adc542f0702281009i2fd2c5e9nc626b7e34b80c270@mail.gmail.com> Message-ID: Sick Monkey schrieb: > Ok I found an extremely easy way to resolving this issue (I cannot believe I > did not think of it sooner). > > After Py2exe created the .exe file I noticed a "library.zip" file. I took a > look at the Py2exe output, and saw all of the libraries that it failed to > insert. I copied all of the .pyc that my application needed and inserted > them in the "email folder" within the library.zip. I fired up the > application and it worked like a champ. > Even easier would be to let py2exe include the whole email package. One solution is to run 'setup.py py2exe -p email' Thomas From bdesth.quelquechose at free.quelquepart.fr Tue Feb 27 15:59:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Feb 2007 21:59:01 +0100 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: <45e1f41d$0$25582$426a74cc@news.free.fr> Message-ID: <45e493cc$0$32303$426a74cc@news.free.fr> Eric Brunel a ?crit : > On Sun, 25 Feb 2007 22:12:52 +0100, Bruno Desthuilliers > wrote: > >> Steven W. Orr a ?crit : >> >>> I understand that two leading underscores in a class attribute make >>> the attribute private. >> >> >> Nope. It doesn't make it "private", it mangles the attribute name >> with the class name (ie : Bar.__mangled will become >> Bar._Bar__mangled everywhere except inside Bar). This is only useful >> when you want to make sure an attribute will not be *accidentally* >> accessed by a child class. FWIW, I've found it of very limited use so >> far... > > > If I'm not mistaken, it was originally introduced to allow designers of > sub-classes to use any attribute name they liked, without bothering to > go up the whole class hierarchy to make sure this name was not already > used. > Even if Python relies far less on inheritance than other > languages, class hierarchies are sometimes quite large. Zope aside - but Zope is a world in itself, and certainly not the most Pythonic example of Python use -, I have not yet seen deep (I suppose that's what you mean here by "large") class hierarchies in Python. > If in addition, > each class has a lot of attributes, looking for an unused name can > become long and painful. In this context, the double-underscore may be > a blessing. My own experience is that it's often more trouble than gain. But please note that I said "of very limited use", not "totally useless" !-) > My [??$?]0.02... From nospamformeSVP at gmail.com Sun Feb 11 12:49:47 2007 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sun, 11 Feb 2007 12:49:47 -0500 Subject: Generating pdf files in epydoc on Windows Message-ID: Does anyone know what is needed to install to get epydoc to generate pdf files on Windows. Besides epydoc itself of course. Maybe there is a more appropriate forum to ask newbie questions about epydoc? Thanks, Don. From bearophileHUGS at lycos.com Fri Feb 2 13:09:24 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Feb 2007 10:09:24 -0800 Subject: Writing "pythonish" code In-Reply-To: References: Message-ID: <1170439764.205168.91260@p10g2000cwp.googlegroups.com> Mizipzor: > To me, the main.py code above looks very ugly. With time, and looking at other people code, you will learn what pythonic means, in the meantime you can remember that into your Python code if you find something that makes you write too much code, or you see something "ugly", then that's probably the wrong way to write it. The language is designed in a way that often the simpler and shorter things are the right ones. There are exceptions to that rule (like avoiding to use import *, using xrange instead of range, etc), but it's a stating point. Bye and welcome here, bearophile From kyosohma at gmail.com Tue Feb 27 13:52:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Feb 2007 10:52:49 -0800 Subject: Importing WMI in a child Thread throws an error Message-ID: <1172602368.563302.160060@t69g2000cwt.googlegroups.com> Hi, I am trying to create a post logon script which does various tasks, like setup a printer based on location. While most of it works very fast, I have a second Python script that I run that scans the PC using WMI (among other things) and writes the following to a database: Name, Username, Machine, IP, Login Date,CPU,Memory. The problem I have is that since I import WMI, it takes a long time and we have users complaining about it. So I stuck the import statement into a separate thread and set it to a daemon so it could do its thing in the background and the rest of the script would finish and exit. Unfortunately, I get the following error when I do this: Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python24\lib\threading.py", line 444, in __bootstrap self.run() File "C:\Python24\lib\threading.py", line 424, in run self.__target(*self.__args, **self.__kwargs) File "//serverName/Scripts/PostLogon_MT.py", line 35, in InvThread import db_inventory File "\\serverName\PythonPackages\Utilities\db_inventory.py", line 3, in ? import wmi File "C:\Python24\lib\site-packages\wmi.py", line 204, in ? obj = GetObject ("winmgmts:") File "C:\Python24\lib\site-packages\win32com\client\__init__.py", line 73, in GetObject return Moniker(Pathname, clsctx) File "C:\Python24\lib\site-packages\win32com\client\__init__.py", line 88, in Moniker moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname) com_error: (-2147221020, 'Invalid syntax', None, None) If I import the module without using threading, it works fine, but takes forever. Even after it threw that error above, the process didn't stop and I had to kill it with a control+C. I am using Windows XP with Python 2.4. Thanks for any help you can give. Mike From bdesth.quelquechose at free.quelquepart.fr Mon Feb 19 16:46:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Feb 2007 22:46:40 +0100 Subject: Declare a variable global In-Reply-To: <1171907496.269876.295200@p10g2000cwp.googlegroups.com> References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> <1171907496.269876.295200@p10g2000cwp.googlegroups.com> Message-ID: <45da133c$0$20043$426a74cc@news.free.fr> yinglcs at gmail.com a ?crit : > On Feb 19, 11:09 am, Jean-Paul Calderone wrote: > >>On 19 Feb 2007 09:04:19 -0800, "ying... at gmail.com" wrote: >> >> >>>Hi, >> >>>I have the following code: >> >>>colorIndex = 0; >> >>>def test(): >>> print colorIndex; >> >>>This won't work. >> >>Are you sure? >> >> exarkun at charm:~$ cat foo.py >> colorIndex = 0 >> >> def test(): >> print colorIndex >> >> test() >> exarkun at charm:~$ python foo.py >> 0 >> exarkun at charm:~$ >> >>The global keyword lets you rebind a variable from the module scope. It >>doesn't have much to do with accessing the current value of a variable. >> >>Jean-Paul > > > Thanks. Then I don't understand why I get this error in line 98: > > Traceback (most recent call last): > File "./gensvg.py", line 109, in ? > outdata, minX, minY, maxX, maxY = getText(data); > File "./gensvg.py", line 98, in getText > print colorIndex; > UnboundLocalError: local variable 'colorIndex' referenced before > assignment > > > Here is my complete script: > #!/usr/bin/python > > import re > import sys > import time > import os > import shutil > > colors = ["#FF0000", "#00FF00", "#0000FF", > "#FFFF00" ,"#FFA500" ,"#DA70D6"] > colorIndex = 0 > > def getText( intputstr): > rc = "" > > maxX = 0; > maxY = 0; > minX = 10000000; > minY = 10000000; > > > for str in intputstr: don't use str as an indentifier unless it's ok for you to shadow the builtin type str. > print str; > > if str != "": if str: > pattern = "x:(\d+) y:(\d+) w:(\d+) h:(\d+) (.*)" > match = re.findall(pattern, str) Move loop invariants (here, your pattern) outside of the loop. And while you're at it, compile it. > if match: > x, y, width, height, area = match[0] > > colorIndex = colorIndex + 1 You're not reading colorIndex, you're rebinding it. In this case, you do need to declare it global (or better, to rethink your code to avoid globals). > rc = rc + " (width)s\" height=\"%(height)s\" " % locals() Using augmented assignment (ie : +=) may be more readable here (MHO). Also, if you use single quotes for the template string, you can save the escapes: rc += ' rc = rc + "fill=\"%s\" stroke=\"#000000\" stroke-width= > \"1px\" fill-opacity=\".5\" />\n" % colors[colorIndex % len(colors)] idem (snip) From gagsl-py at yahoo.com.ar Mon Feb 5 20:16:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 22:16:17 -0300 Subject: Taint (like in Perl) as a Python module: taint.py References: <1170713584.199237.22210@v33g2000cwv.googlegroups.com> Message-ID: En Mon, 05 Feb 2007 19:13:04 -0300, Johann C. Rocholl escribi?: > The following is my first attempt at adding a taint feature to Python > to prevent os.system() from being called with untrusted input. What do > you think of it? A simple reload(os) will drop all your wrapped functions, leaving the original ones. I suppose you don't intend to publish the SafeString class - but if anyone can get a SafeString instance in any way or another, he can convert *anything* into a SafeString trivially. And tainted() returns False by default????? Sorry but in general, this won't work :( -- Gabriel Genellina From gerdusvanzyl at gmail.com Tue Feb 27 04:37:00 2007 From: gerdusvanzyl at gmail.com (AngelBlaZe) Date: 27 Feb 2007 01:37:00 -0800 Subject: Working with C object of python object (pycairo,ctypes) References: <1172448055.159739.220810@m58g2000cwm.googlegroups.com> Message-ID: <1172569020.081900.120360@h3g2000cwc.googlegroups.com> Solved my own problem :-) For future reference here is the solution: class PycairoContext(Structure): _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__), ("ctx", c_void_p), ("base", c_void_p)] z = PycairoContext.from_address(id(ctx)) print z.ctx where ctx is the python object and PycairoContext is the C object of ctx Full Code : ( simple rsvg / librsvg ctypes wrapper ) ------------------------------------------ def WebColour(sCol): #print sCol ic = [int(sCol[i:i+2], 16)/255.0 for i in range(1, 7, 2)] #print ic return ic from ctypes import * l=CDLL('librsvg-2-2.dll') g=CDLL('libgobject-2.0-0.dll') print g.g_type_init() import cairo WIDTH, HEIGHT = 800, 800 # Setup Cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) ctx = cairo.Context(surface) error='' handle1 = l.rsvg_handle_new_from_file('test.svg',error) print error print handle1 class PycairoContext(Structure): _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__), ("ctx", c_void_p), ("base", c_void_p)] z = PycairoContext.from_address(id(ctx)) print z.ctx print '>>',l.rsvg_handle_render_cairo(handle1, z.ctx) #add some cairo stuff on top bg = WebColour('#FFFFFF') ctx.set_source_rgb(bg[0],bg[1],bg[2]) # Set thickness of brush ctx.set_line_width(15) # Draw out the triangle using absolute coordinates ctx.move_to(200, 100) ctx.line_to(300, 300) ctx.rel_line_to(-200, 0) ctx.close_path() # Apply the ink ctx.stroke() surface.write_to_png("test.png") ------------------------------------------ AngelBlaZe wrote: > Can you access the c object of a python object directly? Can this be > done in ctypes or directly throught python functions without reverting > to forking the python module? > > scanario: > I have pyctx object that i get in python like this: > > pyctx = cairo.Context(surface) > > defined in the python extension this: > > typedef struct { > PyObject_HEAD > cairo_t *ctx; > PyObject *base; /* base object used to create context, or NULL */ > } PycairoContext; > > PyObject * > PycairoContext_FromContext(cairo_t *ctx, PyTypeObject *type, PyObject > *base) > { > PyObject *o; > > assert (ctx != NULL); > > if (Pycairo_Check_Status (cairo_status (ctx))) { > cairo_destroy (ctx); > return NULL; > } > > if (type == NULL) > type = &PycairoContext_Type; > o = PycairoContext_Type.tp_alloc (type, 0); > if (o) { > ((PycairoContext *)o)->ctx = ctx; > Py_XINCREF(base); > ((PycairoContext *)o)->base = base; > } else { > cairo_destroy (ctx); > } > return o; > } > > Now my question is: > Is there any way to access/get a pointer to PycairoContext->ctx from > python object (pyctx)? > > A long shot i know :-) From gagsl-py at yahoo.com.ar Thu Feb 8 23:56:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Feb 2007 01:56:37 -0300 Subject: Newbie Question References: <1170980835.761703.163120@j27g2000cwj.googlegroups.com> <1170994729.917461.6460@p10g2000cwp.googlegroups.com> Message-ID: En Fri, 09 Feb 2007 01:18:49 -0300, azrael escribi?: > but look out for pyqt. there is one thing in the eula i don't like. > there is written that if you use qtWidgets and they like the > aplication, you have to give up all your rights of the aplication. > patent, idea, money everything is gone. i know this is open source, > but maybe one day i will manage to sell an apliction for big money. Could you please indicate where does it say so? Are you talking about the pyqt license or the qt license? -- Gabriel Genellina From gagsl-py at yahoo.com.ar Sat Feb 3 03:51:56 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Feb 2007 05:51:56 -0300 Subject: main References: <1170481031.861396.248680@j27g2000cwj.googlegroups.com> Message-ID: En Sat, 03 Feb 2007 02:37:11 -0300, Paddy escribi?: >> and what is >> __name__ >> __main__ >> >> use for in terms of Java? >> > > With respect, (hehe), maybe you need to indicate that you've searched > the Python documentation on __name__ and __main__? > (Hah! I did that without saying RTFM. - Oh pooh! Fiddlesticks). Have you acually tried to do the search? The Python tutorial doesn't menction that at all. And no one should expect that a beginner would have to read section 26.3 on the Language Reference (__main__ -- Top-level script environment) just to know what's that stuff about __name__ and "__main__"... -- Gabriel Genellina From liuwensui at gmail.com Wed Feb 14 15:50:21 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Wed, 14 Feb 2007 15:50:21 -0500 Subject: reference data in a dictionary In-Reply-To: <87ps8c79tv.fsf@benfinney.id.au> References: <1115a2b00702141226i4f23dc17x1360d87ed253dd3e@mail.gmail.com> <87ps8c79tv.fsf@benfinney.id.au> Message-ID: <1115a2b00702141250u46bb921g6c39d86a336eff34@mail.gmail.com> I know dict['row1'] will always work. but it will only get 1 row out of the dict. is there anyway i can get multiple (>1) rows out of dict by directly refeencing them, something like dict[['row1', 'row2']]. thank you for reply, Ben. wensui On 2/14/07, Ben Finney wrote: > "Wensui Liu" writes: > > > i am new to python and have a question about referencing data in a > > dict. is there anyway that allows me to do something like: > > > dict[['row1', 'row2', .....'row100']] > > What behaviour would you expect from that statement? If we know what > you're trying to do, perhaps we can suggest a solution. > > -- > \ "Like the creators of sitcoms or junk food or package tours, | > `\ Java's designers were consciously designing a product for | > _o__) people not as smart as them." -- Paul Graham | > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From sturlamolden at yahoo.no Mon Feb 26 05:56:14 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 26 Feb 2007 02:56:14 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <1171901023.751608.280430@a75g2000cwd.googlegroups.com> Message-ID: <1172487374.249192.111420@a75g2000cwd.googlegroups.com> On Feb 24, 7:04 pm, Thomas Bartkus wrote: > Most user apps. require 95% of coding effort to provide a usable user > interface and 5% effort on the algorithmic meat. The "afterwards" you > allude to. So why do we still endure so much programming effort on the > unimportant part? > Why should a programmer waste even so much as 10% of his effort to throw > together a standard interface with ordinary textboxes, labels, and option > buttons? Over and over again? That is why at least two modern GUI toolkits (Microsoft's 'avalon' and GTK with GLADE) export the GUI as an XML-resource from a graphical GUI designer. It then takes only a line of code to import the GUI and another to register the event handlers. From yinglcs at gmail.com Tue Feb 27 00:12:21 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 26 Feb 2007 21:12:21 -0800 Subject: How to use cmp() function to compare 2 files? In-Reply-To: <1172551987.182502.94000@p10g2000cwp.googlegroups.com> References: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> <1172550136.069527.103600@t69g2000cwt.googlegroups.com> <1172551987.182502.94000@p10g2000cwp.googlegroups.com> Message-ID: <1172553141.665287.65280@8g2000cwh.googlegroups.com> On Feb 26, 10:53 pm, "ying... at gmail.com" wrote: > On Feb 26, 10:22 pm, "Dan Bishop" wrote: > > > > > On Feb 26, 10:09 pm, "ying... at gmail.com" wrote: > > > > Hi, > > > > i have 2 files which are different (1 line difference): > > > $ diff groupresult20070226190027.xml groupresult20070226190027-2.xml > > > 5c5 > > > < x:22 y:516 w:740 h:120 area: > > > --- > > > > > x:22 y:516 w:740 h:1202 area: > > > > But when I use the cmp() function to compare 2 files, it return "1", > > > > $ python Python 2.4.3 (#1, Oct 23 2006, 14:19:47) > > > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > > > Type "help", "copyright", "credits" or "license" for more information.>>> cmp("groupresult20070226190027.xml", "groupresult20070226190027-2.xml") > > > > 1 > > > > Can you please tell me why? > > > Because '.' > '-' (character 25 of each string). > > > But this is comparing the filenames, which isn't what you want to do. > > > > And how can I compare the content of 2 > > > files in python? > > > Use the difflib module. > I try this: f1 = open("f1",'r') f2 = open("f2", 'r') if (difflib.context_diff(f1.readlines(), f2.readlines()).len() == 0): But I get this error: Traceback (most recent call last): File "./scripts/regressionTest.py", line 72, in ? runTest(savedPagesDirectory, outputDir, expectedResultDir, failedDir); File "./scripts/regressionTest.py", line 60, in runTest getSnapShot(fileName, testNo, outputDir, expectedResultDir, failedDir) File "./scripts/regressionTest.py", line 30, in getSnapShot if (difflib.context_diff(f1.readlines(), f2.readlines()).len() == 0): # no difference else: # files are different AttributeError: 'generator' object has no attribute 'len' Can you please help? From thinker at branda.to Mon Feb 26 11:55:16 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 00:55:16 +0800 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: <45E310F4.7070207@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 zefciu wrote: > I am trying to embed a c function in my python script for a first > time. When I try to call it I get an error > > SystemError: new style getargs format but argument is not a tuple > > Guido said on some mailing list, that it is probably an effect of > the lack of METH_VARARGS in the functions' array, but it's ok in my > source code. Here is the full code: > > #include > > static PyObject * mandelpixel(PyObject *self, PyObject *args) { > double z_real = 0, z_imag = 0, z_real2 = 0, z_imag2 = 0, c_real, > c_imag, bailoutsquare; int iteration_number; register int i; > PyObject coord; It should be "PyObject *coord;" . Maybe, it is what is wrong with your program! - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4xDz1LDUVnWfY8gRAmAAAJ9FJPqGyeI0InxrcvdNXHtGMXWK1wCg570r z3hcYDsjmqRp4BnpEFjbDy0= =REQM -----END PGP SIGNATURE----- From steven.bethard at gmail.com Tue Feb 6 10:40:40 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 06 Feb 2007 08:40:40 -0700 Subject: huge amounts of pure Python code broken by Python 2.5? Message-ID: Jean-Paul Calderone wrote: > Huge amounts of my pure Python code was broken by Python 2.5. Interesting. Could you give a few illustrations of this? (I didn't run into the same problem at all, so I'm curious.) Steve From george.sakkis at gmail.com Fri Feb 9 23:31:28 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 9 Feb 2007 20:31:28 -0800 Subject: Calling J from Python In-Reply-To: <1171074036.082831.283300@k78g2000cwa.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> <1171016992.962017.10540@m58g2000cwm.googlegroups.com> <87mz3mlxsf.fsf@tnoo.net> <1171074036.082831.283300@k78g2000cwa.googlegroups.com> Message-ID: <1171081888.750035.294170@h3g2000cwc.googlegroups.com> On Feb 9, 9:20 pm, bearophileH... at lycos.com wrote: > ant: > > > and in debugging it far outweighs the time you'd spend on all > > of that typing in a clean but more verbose language such as Python. > > Typing time counts a bit too. A language like Java is even more > verbose than Python, and that probably slows down the actual > programming, compared to less verbose languages. I think there is some > verbosity sweet spot between J and Java, and for me that's called > Python ;-) > > Martin L?thi: > > > more elegant solutions sought! > > This is a bit simpler, but probably there are simpler solutions using > modular arithmetic: > > l = [1] > for _ in range(15): > print ''.join(" *"[x] for x in l) > l = [1] + [l[i+1]^l[i] for i in range(len(l)-1)] + [1] > > Bye, > bearophile Here's another one, adapted from the example (in Java) in Wikipedia's entry (http://en.wikipedia.org/wiki/Sierpinski_triangle): N=15 for x in xrange(N,0,-1): print ''.join('* '[x&y!=0] for y in xrange(N+1-x)) George From venky at nospam.com Mon Feb 26 20:43:44 2007 From: venky at nospam.com (Venky) Date: Tue, 27 Feb 2007 01:43:44 GMT Subject: classobj? Message-ID: Hi, I am trying to create classes at runtime based on input from a textfile. I am trying to use the function new.classobj. I am able to create the new classes successfully, however I fail to understand on how to add this new class to the current dictionary. cl = new.classobj('SomeClass', (BaseClass, ), {}) After this call, how do I instantiate SomeClass? I understand cl() will instantiate this, however this defeats my purpose, since the name of the class is obtained at runtime. Thanks venky From bignose+hates-spam at benfinney.id.au Tue Feb 27 18:51:57 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 10:51:57 +1100 Subject: database without installation again References: Message-ID: <87y7mjxioy.fsf@benfinney.id.au> "andrew_s" writes: > I'm looking for any database which I could use without need of > instalation. Python 2.5 comes with SQLite built in. SQLite allows database interaction without a corresponding server; all the code is in the client, in this case provided in the Python standard library. Previous versions of Python have standard library support for DBM files, a non-relational, key-value system for storing data in local files. > Any ideas? Maybe is it possible to "install" by myself something > like SQLite or MySQLdb in my cgi-bin directory? If you can set your PYTHONPATH environment variable to point to a directory under your control, you can install Python packages and modules in that directory. -- \ "I met my girlfriend in Macy's; she was buying clothes, and I | `\ was putting Slinkies on the escalators." -- Steven Wright | _o__) | Ben Finney From bearophileHUGS at lycos.com Fri Feb 9 21:20:36 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Feb 2007 18:20:36 -0800 Subject: Calling J from Python In-Reply-To: <87mz3mlxsf.fsf@tnoo.net> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> <1171016992.962017.10540@m58g2000cwm.googlegroups.com> <87mz3mlxsf.fsf@tnoo.net> Message-ID: <1171074036.082831.283300@k78g2000cwa.googlegroups.com> ant: > and in debugging it far outweighs the time you'd spend on all > of that typing in a clean but more verbose language such as Python. Typing time counts a bit too. A language like Java is even more verbose than Python, and that probably slows down the actual programming, compared to less verbose languages. I think there is some verbosity sweet spot between J and Java, and for me that's called Python ;-) Martin L?thi: > more elegant solutions sought! This is a bit simpler, but probably there are simpler solutions using modular arithmetic: l = [1] for _ in range(15): print ''.join(" *"[x] for x in l) l = [1] + [l[i+1]^l[i] for i in range(len(l)-1)] + [1] Bye, bearophile From thinker at branda.to Tue Feb 27 06:27:14 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 19:27:14 +0800 Subject: spawnl and waitpid In-Reply-To: <1172573530.625901.36420@k78g2000cwa.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> Message-ID: <45E41592.5080302@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 naima.mans at gmail.com wrote: > On 27 f?, 11:28, Thinker wrote: > naima.m... at gmail.com wrote: >>>> hello, I run a python cgi script under Apache... and while >>>> the script is running i want to display a "please wait" >>>> message until the script finish. I have tried to do this but >>>> the "please wait" message appears at the script end (which is >>>> useless at this time! ) > You should flush sys.stdout after you print messages, or the > message will keep in buffer untill buffer is full or process > terminated. > > Hello > thanks for answering i have flush like this but same result .. the > server wait until the end... > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > \python.exe","python","Main.py") sys.stdout.flush() ret = > os.waitpid(pid,0) Your program will be blocked here until child process being terminated. You should print your messages before this line. > if ( ret[1] != 0): print """ wait %i """ %ret[1] > sys.stdout.flush() else: print """ end %i """ %ret[1] > sys.stdout.flush() - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF5BWS1LDUVnWfY8gRAkp8AKCAcTKi/MO6sfkGBBEcMjfpH42O1wCeN14I 0AZ83oVacK0hKik4YC/jfCA= =3h7d -----END PGP SIGNATURE----- From lorean2007 at yahoo.fr Fri Feb 23 02:54:20 2007 From: lorean2007 at yahoo.fr (lorean2007 at yahoo.fr) Date: 22 Feb 2007 23:54:20 -0800 Subject: parse HTML by class rather than tag Message-ID: <1172217260.318877.290250@m58g2000cwm.googlegroups.com> Hello, i'm would be interested in parsing a HTML files by its corresponding opening and closing tags but by taking into account the class attributes and its values, ...
...
...
...
...
in this example, i will need all content inside div with class="two", or only class="one", so i wondering if i should go with regular expression, but i do not think so as i must jumpt after inner closing div, or with a simple parser, i've searched and found http://www.diveintopython.org/html_processing/basehtmlprocessor.html but i would like the parser not to change anything at all (no lowercase). can you help ? best. From fred at urlbit.us Sun Feb 11 08:45:00 2007 From: fred at urlbit.us (Fred of UrlBit.Us) Date: Sun, 11 Feb 2007 08:45:00 -0500 Subject: How to access an absolute address through Python? References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> <1171197574.776135.96980@k78g2000cwa.googlegroups.com> <1171198707.889681.177270@h3g2000cwc.googlegroups.com> Message-ID: <1171201580_9817@news-east.n> volcano wrote: > On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch wrote: ... > My goal is to sync program with external equipment through a register > defined as an absolute physical address. I know how to do it from C - > was curious if it may be done from Python. Can it be done? > > Thanks, Mark Your best bet will be to create a C library callable from Python to do it for you. There may be such a beast in existence already, but it should not be hard at all to do, given the simplicity of the requirements. -- -- Fred of UrlBit.Us -- http://UrlBit.Us - Bite those URLs down to size! Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From krypto.wizard at gmail.com Thu Feb 1 15:25:21 2007 From: krypto.wizard at gmail.com (Krypto) Date: 1 Feb 2007 12:25:21 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170334830.137876.248230@h3g2000cwc.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> Message-ID: <1170361512.204099.191740@a75g2000cwd.googlegroups.com> The correct answer as told to me by a person is (N>>3) + ((N-7*(N>>3))>>3) The above term always gives division by 7 From skyofdreams at gmail.com Fri Feb 2 06:48:33 2007 From: skyofdreams at gmail.com (skyofdreams) Date: Fri, 2 Feb 2007 19:48:33 +0800 Subject: Writing "pythonish" code References: Message-ID: "Mizipzor" ??????:mailman.3452.1170415251.32031.python-list at python.org... > Hi, this is my first mail to the list (and any list for that matter) > so any pointers on errors from my part would be appreciated. Im more > used to forums. > > To start off, Ive read some python documents and done some small apps > so I think I can say I know it semi-well, and I know c++ very well. > But I want learn python even better, since I know that a company I aim > to be employed by make heavy use of python, knowing python myself > would give me an extra edge. > > The problem isnt in pythons syntax, its in the architecture/design, > the concept of writing "pythonish code" if you like. One thing is that > in c++ im used to have private members in classes and no member is > altered except through the public functions of the class. In python > everything is, as far as I know, public. Im confused by this, should I > still have members in the python class that I simply dont edit > directly and let the class do its internal stuff? Or should I see the > python classes like c++ structs with functions? > > I guess the ultimate is somewhere in between but I would like a nudge > or two to get there. > as far as i know, the class attributes haven't privilege identifier. I think If in C++ i need friend relationship between 2 classes, then in python, i'll access the attribute directly. in other cases, i treat it as class, suspose it's private attribute , just like classes in C++. > > To me, the main.py code above looks very ugly. So, assuming Im never > gonna have more than one instance of the foo class, can I write > something like this: > > foo.py > ========= > > def bar(self): > print "bar" > > ========= main.py ============ from foo import foo foo().bar() try this, it's ok, "from foo import foo" the first "foo" is module-name, the latter foo is class name. the formal package import tutortial link is http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > Thats much more cleaner if you ask me, and kinda a good way to make > sure that you dont have more than one "instance" of the foo class > (which no longer is a class at all). But is it "pythonish"? > > Gonna stop now, this mail got a little longer than i first thought. > Any input will be greatly appreciated. :) HTH -skyofdreams From loveline17 at gmail.com Tue Feb 27 23:42:01 2007 From: loveline17 at gmail.com (loveline17 at gmail.com) Date: 27 Feb 2007 20:42:01 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172637274.994742.173850@p10g2000cwp.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> Message-ID: <1172637721.119848.188380@a75g2000cwd.googlegroups.com> Hi Jeremy, that's the problem I'm having. Where should I type that " python setup.py install" ? Once again I'm using Windows system and not Unix. Should I move the file to a specific folder under Python 2.5 and then type " python setup.py install" in IDLE or Command Line window? I get the error "SyntaxError: invalid syntax" with the word "setup" On Feb 27, 10:34 pm, "Jeremy Dillworth" wrote: > I haven't used that particular package, but the norm for setup.py is > this command line: > > python setup.py install > > Hope this helps, > > Jeremy From gandalf at designaproduct.biz Thu Feb 1 15:43:20 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 01 Feb 2007 21:43:20 +0100 Subject: Newbie question: replacing nulls in CSV with preceding value In-Reply-To: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> References: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> Message-ID: <45C250E8.2070700@designaproduct.biz> > import csv > citynew='' > reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb")) > for row in reader: > row['CITY'] == citynew > else: > citynew=row['CITY'] > > The logic here -- in this case trying to fill in the city information > -- would seem to work, but I'm not sure. And I'm not sure how to write > the results of this back to the file. > I recommend that you create a writer and a new file. After you processed the input, you can delete the original file and replace it with the new one. My experience is that this is highly efficient and works with very large files. I would do something like this (not tested) import csv import os import shutil fin = file("/home/mwaite/test/test2.csv", "rb") reader = csv.DictReader(fin) fout = file(fin.name + '.tmp',"wb+") writer = csv.writer(fout) prev = {} columns = ('CITY','ZIP','NAME') for curr in reader: foreach col in columns: if (not curr.has_key(col)) or (curr[col] == ''): if prev.has_key(col): curr[col] = prev[col] else: curr[col] = '' row = [curr[col] for col in columns ] writer.write(row) prev = curr os.unlink(fin.name) fout.close() shutil.rename(fout.name,fin.name) I really did not test it, but you can get the idea. Best, Laszlo From thinker at branda.to Mon Feb 26 04:27:18 2007 From: thinker at branda.to (Thinker) Date: Mon, 26 Feb 2007 17:27:18 +0800 Subject: compile python with sqlite3 In-Reply-To: References: Message-ID: <45E2A7F6.6090505@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Nader Emami wrote: > L.S., > > I have to compile (install) locally Python 2.5, because I don't have > 'root' permission. Besides I would use 'sqlite3' as a database for > TurboGears/Django. I have installed 'sqlite3' somewhere on my Linux > (/path/to/sqlite'). What do I have to do if I want to compile 'Python' > with 'sqlite3'? I would appreciate if somebody tells me to solve this > problem. > > With regards, > Nader You need PySQLite .. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4qf21LDUVnWfY8gRArLiAKCfOG3Jh6xcJJA5ASJZ1zM01mv1BACgml19 DIMioieQqKrHqIUk0mp5kvQ= =a8si -----END PGP SIGNATURE----- From edreamleo at charter.net Fri Feb 16 11:44:12 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 10:44:12 -0600 Subject: Pep 3105: the end of print? References: Message-ID: > But that doesn't just happen. True, but it didn't happen as you imply. Leo's core defines a gui-and-platform-independent set of api's which then get instantiated in plugins. Plugins can, and do, use platform-dependent features. For example, the wxWidgets plugin uses the scintilla text widget, something that does not exist by default in Tk/Tkinter. Leo just started to work with IronPython last night, so the details are fresh in my mind. Amazingly, IronPython allows you to point sys.path (IronPython's sys.path, that is) at CPython's Python24\Lib and for the most part IronPython 'just works' with those libs. So all of Leo's core, being free of any gui code, just worked. That is, until it started to load the IronPython plugin :-) At which point I started to have newbie problems with dbgclr, but that's another story... Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From ziga.seilnacht at gmail.com Mon Feb 26 16:00:55 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 26 Feb 2007 13:00:55 -0800 Subject: 2.4->2.5 current directory change? In-Reply-To: References: Message-ID: <1172523655.177915.94840@s48g2000cws.googlegroups.com> On Feb 26, 7:44 pm, "Chris Mellon" wrote: > This appears to be a change in behavior from Python 2.4 to Python 2.5, > which I can't find documented anywhere. It may be windows only, or > related to Windows behavior. > > In 2.4, the current directory (os.curdir) was on sys.path. In 2.5, it > appears to be the base directory of the running script. For example, > if you execute the file testme.py in your current working directory, > '' is on sys.path. If you execute c:\Python25\Scripts\testme.py, '' is > *not* on sys.path, and C:\Python25\Scripts is. > > That means if you run a Python script located in another directory, > modules/etc in your current working directory will not be found. This > makes .py scripts in the PYTHONHOME\Scripts file moderately useless, > because they won't find anything in the current working directory. > > I first noticed this because it breaks Trial, but I'm sure there are > other scripts affected by it. Is this desirable behavior? Is there > anything to work around it except by pushing os.curdir onto sys.path? The change was intentional and is mentioned in the NEWS file: - Patch #1232023: Stop including current directory in search path on Windows. This unifies Python's behaviour across different platforms; the docs always said that the current directory is inserted *only* if the script directory is unavailable: As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. The old behaviour was never intentional and wasn't desired, because users could break an application simply by running it from a directory that contained inappropriately named files. For details see the bug report and patch submission: http://www.python.org/sf/1526785 http://www.python.org/sf/1232023 Ziga From larry.bates at websafe.com Mon Feb 12 18:13:33 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Feb 2007 17:13:33 -0600 Subject: can't find a way to display and print pdf through python. In-Reply-To: <12t1ch1n8hj9n69@corp.supernews.com> References: <12t17gsjh6vgh94@corp.supernews.com> <12t1ch1n8hj9n69@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-02-12, Larry Bates wrote: >> On 2007-02-12, Larry Bates wrote: >>>>> I at least need the code for useing some library for >>>>> connecting to acrobat reader and giving the print command on >>>>> windows and some thing similar on ubuntu linux. >>>> Just let the registered .PDF viewer do it for you. >>>> >>>> os.start('myfile.pdf') >>> Eh? I don't see os.start() it either 2.5 or 2.44 >>> documentation, and it's sure not there in 2.4.3: >> My bad. os.system() > > That doesn't work either: > > $ ls -l user.pdf > -rw------- 1 grante users 35640 2005-11-21 14:33 user.pdf > > $ python > Python 2.4.3 (#1, Dec 10 2006, 22:09:09) > [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import os > >>> os.system('user.pdf') > sh: user.pdf: command not found > 32512 > >>> > Works fine on my system. You linux guys just have it hard. The op said "windows". I can't answer for ubuntu linux but maybe you can help there? -Larry From brlspam at yahoo.com Mon Feb 26 14:12:28 2007 From: brlspam at yahoo.com (Bruce Lewis) Date: 26 Feb 2007 14:12:28 -0500 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: Tech HR writes: > (Actually, > it's turning out to be hard to find Python programmers too, but it's > easier to train a Java programmer or a Perler on Python than Lisp. Is this speculation or experience? If it was experience, what Lisp were you trying to train Java programmers in, and what problems did you encounter? From marc.omorain at gmail.com Mon Feb 12 08:48:13 2007 From: marc.omorain at gmail.com (marc.omorain at gmail.com) Date: 12 Feb 2007 05:48:13 -0800 Subject: Progress when parsing a large file with SAX In-Reply-To: <53b7v6F1qkl6qU1@mid.uni-berlin.de> References: <1171277000.671586.191250@q2g2000cwa.googlegroups.com> <53b0r2F1rqg29U1@mid.uni-berlin.de> <53b7v6F1qkl6qU1@mid.uni-berlin.de> Message-ID: <1171288093.469317.291270@q2g2000cwa.googlegroups.com> On Feb 12, 1:21 pm, "Diez B. Roggisch" wrote: > Anastasios Hatzis wrote: > > Diez B. Roggisch wrote: Thanks guys! I'll try it out later today and let you know how I get on. From bearophileHUGS at lycos.com Tue Feb 27 19:18:28 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Feb 2007 16:18:28 -0800 Subject: how to convert an integer to a float? In-Reply-To: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Message-ID: <1172621908.642157.272460@8g2000cwh.googlegroups.com> yinglcs, you can use float() or the new division: >>> 1 / 2 0 >>> 1 / float(2) 0.5 >>> from __future__ import division >>> 1 / 2 0.5 Bye, bearophile From vishal at veriwave.com Sat Feb 3 03:24:15 2007 From: vishal at veriwave.com (vishal at veriwave.com) Date: Sat, 3 Feb 2007 00:24:15 -0800 (PST) Subject: Regd. Regular expressions PyQt Message-ID: <50924.71.109.230.173.1170491055.squirrel@mail.veriwave.com> Hello All: I am trying to work out a regular expression in a PyQt environment for time in hh:mm:ss format. Any suggestions? Thanks, Vishal From arkanes at gmail.com Mon Feb 12 09:24:55 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Feb 2007 08:24:55 -0600 Subject: wxPython libraries never detected In-Reply-To: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> Message-ID: <4866bea60702120624q28be9ae0x5f67edb6e6b7e7eb@mail.gmail.com> On 10 Feb 2007 07:55:05 -0800, d.lidell at gmail.com wrote: > Hi, I recently started coding with Python and I've been trying for the > past hour or so to determine why, every time I "import wx" (or compile > another piece of code that imports wx), Python can never find the > libraries. > > I'm running Ubuntu Edgy 6.10, and, as per http://www.wxpython.org/download.php#sources, > updated sources.list with the sources and installed python-wxgtk2.8, > python-wxtools and wx2.8-i18n. I compiled the latest Python (as of > writing), 2.5, from source. > > For example, SPE tells me that I "need to install at least wxPython v. > 2.5.4.1 to run SPE" and any code that relies on "import wx" reports > "ImportError: No module named wx". However, "whereis wx" on the > command line reports "wx: /usr/lib/wx /usr/local/lib/wx /usr/include/ > wx". What could be wrong here? I can't figure out why wx isn't being > detected. > > Many thanks. > > -- wxPython binaries for 2.4 won't run with 2.5. From gagsl-py at yahoo.com.ar Sun Feb 11 21:35:23 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 23:35:23 -0300 Subject: Read/write 2D data from/to file..? References: <1171244850.077289.130330@s48g2000cws.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 22:47:30 -0300, mech point escribi?: > I was able to read the data from file into a two dimensional array > (lists) > > rows=[map(float,line.split())for line in file("data")] > > but How to write them back into the file. This way uses the same structures as your example; line.split(",") -> ",".join(...); map(float,...) -> map(str,...) yourfile.writelines(",".join(map(str,row))+"\n" for row in rows) If you are using Python<2.5, put [] inside the writelines call: writelines([","...]). Or move the iteration outer. If you want control on the format too: for row in rows: yourfile.write("%.2f,%.6g\n" % (row[0], row[1])) -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Tue Feb 20 17:35:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 09:35:43 +1100 Subject: file io (lagged values) newbie question References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> <1171984082.488529.76040@p10g2000cwp.googlegroups.com> <45db5ac8$0$7473$426a74cc@news.free.fr> Message-ID: On Tue, 20 Feb 2007 22:03:43 +0100, Bruno Desthuilliers wrote: [snip] >>>And that's not cruft? >> >> >> No. Why do you think it is crufty? > > Because it is ? *shrug* "Is not." "Is too." "Is not." Why is converting a list of integers to a string all at once more crufty than converting them one at a time? Because you have to remove the delimiters? That's no bigger a deal than adding spaces or newlines, and if removing the commas worries you, change the output format to separate the numbers with comma instead of space. >> Would it be less crufty if I wrote it as a cryptic one liner without >> comments? >> >> f.write(str(data)[1:-1].replace(',', '') + '\n') > > Nope. It's still a WTF. > >> Okay, it depends on the string conversion of a list. > > Nope. It depends on the *representation* of a list. No, that would be repr(data) instead of str(data). An insignificant detail for lists, but potentially very different for other data types. >> But that's not going >> to change any time soon. > >> >>>Try this: f.write(' '.join(str(x) for x in data) + '\n') >> >> >> That will only work in Python 2.5 or better. > > Really ? [snip demonstration] Well, I'll be hornswaggled. Who snuck generator expressions into 2.4? I thought they were only in 2.5 and up. -- Steven. From anthra.norell at vtxmail.ch Wed Feb 14 08:13:05 2007 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Wed, 14 Feb 2007 14:13:05 +0100 Subject: Parsing HTML In-Reply-To: <1171148616.780656.13230@m58g2000cwm.googlegroups.com> References: <1171148616.780656.13230@m58g2000cwm.googlegroups.com> Message-ID: <45D30AE1.6040900@vtxmail.ch> mtuller wrote: > Alright. I have tried everything I can find, but am not getting > anywhere. I have a web page that has data like this: > > > > LETTER > > 33,699 > > 1.0 > > > > What is show is only a small section. > > I want to extract the 33,699 (which is dynamic) and set the value to a > variable so that I can insert it into a database. I have tried parsing > the html with pyparsing, and the examples will get it to print all > instances with span, of which there are a hundred or so when I use: > > for srvrtokens in printCount.searchString(printerListHTML): > print srvrtokens > > If I set the last line to srvtokens[3] I get the values, but I don't > know grab a single line and then set that as a variable. > > I have also tried Beautiful Soup, but had trouble understanding the > documentation, and HTMLParser doesn't seem to do what I want. Can > someone point me to a tutorial or give me some pointers on how to > parse html where there are multiple lines with the same tags and then > be able to go to a certain line and grab a value and set a variable's > value to that? > > > Thanks, > > Mike > > Posted problems rarely provide exhaustive information. It's just not possible. I have been taking shots in the dark of late suggesting a stream-editing approach to extracting data from htm files. The mainstream approach is to use a parser (beautiful soup or pyparsing). Often times nothing more is attempted than the location and extraction of some text irrespective of page layout. This can sometimes be done with a simple regular expression, or with a stream editor if a regular expression gets too unwieldy. The advantage of the stream editor over a parser is that it doesn't mobilize an arsenal of unneeded functionality and therefore tends to be easier, faster and shorter to implement. The editor's inability to understand structure isn't a shortcoming when structure doesn't matter and can even be an advantage in the presence of malformed input that sends a parser on a tough and potentially hazardous mission for no purpose at all. SE doesn't impose the study of massive documentation, nor the memorization of dozens of classes, methods and what not. The following four lines would solve the OP's problem (provided the post really is all there is to the problem): >>> import re, SE # http://cheeseshop.python.org/pypi/SE/2.3 >>> Filter = SE.SE (' "~(?i)col[0-9]_[0-9](.|\n)*?/td>~==SOME SPLIT MARK"') >>> r = re.compile ('(?i)(col[0-9]_[0-9])(.|\n)*?([0-9,]+)>> for line in Filter (s).split ('SOME SPLIT MARK'): print r.search (line).group (1, 3) ('col2_1', '33,699') ('col3_1', '0') ('col4_1', '7,428') ----------------------------------------------------------------------- Input: >>> s = ''' LETTER 33,699 1.0 7,428 ''' The SE object handles file input too: >>> for line in Filter ('file_name', '').split ('SOME SPLIT MARK'): # '' commands string output print r.search (line).group (1, 3) From piet at cs.uu.nl Thu Feb 22 11:06:28 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 22 Feb 2007 17:06:28 +0100 Subject: Local class variables? (mod_python problem) References: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> Message-ID: >>>>> Rory Campbell-Lange (RC) wrote: >RC> totalgia keeps incrementing when this code is used under mod_python. And also when used outside of mod_python. It is because it is a class level variable. In fact I think under certain circumstances in mod_python it will not do that because different requests can run in different Apache processes (on Linux, Unix, Mac OS X etc.). So it this desired behaviour or not? Your post isn't clear about that. And if it isn't what is the desired behaviour? And you certainly should do something about the concurrent access. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From akonsu at gmail.com Wed Feb 14 16:42:40 2007 From: akonsu at gmail.com (akonsu) Date: 14 Feb 2007 13:42:40 -0800 Subject: swf format verification? Message-ID: <1171489359.975911.222280@j27g2000cwj.googlegroups.com> hello, can someone recommend a good library to verify whether a file is in swf format (and ideally flv as well)? i need it to enable file uploading on to my web site. thanks konstantin From andre.roberge at gmail.com Wed Feb 7 21:19:57 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 7 Feb 2007 18:19:57 -0800 Subject: winsound/ossaudiodev equivalent on a mac Message-ID: <1170901197.595238.32000@m58g2000cwm.googlegroups.com> I'm using winsound and ossaudiodev to produce simple sounds (of set frequency for a given duration) in a an application that is used on Windows-based computer and Linux-based ones. Is there a similar module for Mac OS? Andr? From liuwensui at gmail.com Tue Feb 13 15:11:49 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Tue, 13 Feb 2007 15:11:49 -0500 Subject: New Pythin user looking foe some good examples to study In-Reply-To: References: Message-ID: <1115a2b00702131211m6db19fa7sa36492c9e016ed90@mail.gmail.com> yeah! i also think cookbook is easy to read and code is very practical. On 2/12/07, Larry Bates wrote: > Johnny Garcia wrote: > > I have just discovered Python and am familiarizing myself with the syntax > > but I have always found that code examples where the best way for me to > > learn. > > > > > > > > Can anyone point me to a site with some good open source functioning python > > applications? > > > > > > > > I would appreciate any help. > > > > > > > > Also, does anyone know of any good Linux or python user groups in the orange > > county, California area? > > > > > Pick up a copy of "Python Cookbook" from O'Reilly. > > -Larry > -- > http://mail.python.org/mailman/listinfo/python-list > -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From wdraxinger at darkstargames.de Wed Feb 21 05:25:46 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 21 Feb 2007 11:25:46 +0100 Subject: Sorting directory contents References: Message-ID: Tim Williams wrote: > Are you running on windows? No. Of course I could use some installed tool, like ls, but I want a portable solution. > HTH :) Not really. Windows is only a niche for desktop systems. In my case the python script is running on a heterogenous grid monitoring system accessing a _large_ distributed Oracle9i DB - a query can take up to half a minute, so obviously I'm caching the results of previous queries in the mentioned files, where the modification time is the sorting criterium for later reading. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From deets at nospam.web.de Tue Feb 20 13:10:45 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Feb 2007 19:10:45 +0100 Subject: Regd. converting seconds to hh:mm:ss format In-Reply-To: References: Message-ID: <540rtnF1tvsb3U1@mid.uni-berlin.de> Vishal Bhargava schrieb: > Is there an inbuilt library in Python which you can use to convert time in > seconds to hh:mm:ss format? Module datetime. Did you even _bother_ to google or skim the docs? Diez From yaipa at yahoo.com Fri Feb 16 14:03:21 2007 From: yaipa at yahoo.com (yaipa) Date: 16 Feb 2007 11:03:21 -0800 Subject: XOR Binascii Hex Strings using the PyCrypto module Message-ID: <1171652601.587064.305020@v45g2000cwv.googlegroups.com> I snipped this bit of code out of Andrew Kuchling 'pyCrypto' test fixture. Having a need to XOR Binascii Hex strings in my current project, I found it very helpful to cut down on a bit of code clutter. So if you have a need for a Crypto module, this one seems to work off the self without much effort and it comes /w a nice XOR function too boot. :-) PyCrypto can be found at: http://www.amk.ca/python/code/crypto import binascii from Crypto.Cipher import XOR def die(string): import sys print '***ERROR: ', string # sys.exit(0) # Will default to continuing onward... testdata_xor = [('ffffffffffffffff', 'a5a5a5a5a5a5a5a5','5a5a5a5a5a5a5a5a')] for entry in testdata_xor: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=XOR.new(key) ciphertext=obj.encrypt(plain) print binascii.b2a_hex(ciphertext) if (ciphertext!=cipher): die('XOR failed on entry '+`entry`) From steve at holdenweb.com Tue Feb 6 10:41:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 06 Feb 2007 15:41:42 +0000 Subject: glutInit and wxPython on Mac OSX In-Reply-To: <1170714820.700451.33090@v45g2000cwv.googlegroups.com> References: <1170714820.700451.33090@v45g2000cwv.googlegroups.com> Message-ID: Artie wrote: > I seem to have uncovered a problem when using glutInit alongside > wxPython on Mac OSX. If glutInit is called prior to creating a > wx.App, many window and mouse events are either lost, not generated, > or misgenerated for the glcanvas. However, if glutInit is called > after the wx.App has been created then all is well. > > Has anyone ran across this issue before? If so, why does this order > matter or affect the wx Event system? > As to the whys and wherefores I cannot say, but there are many functions within the Wx package that require the application to be running before they can be called, so I presume glutInit makes use of some of those. Note that you can create a wx.App without creating windows visible on the screen. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From fuzzyman at gmail.com Tue Feb 20 19:29:35 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Feb 2007 16:29:35 -0800 Subject: Bypassing __setattr__ for changing special attributes In-Reply-To: References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> <1171955882.929647.86700@v33g2000cwv.googlegroups.com> Message-ID: <1172017775.924341.135920@t69g2000cwt.googlegroups.com> On Feb 20, 12:57 pm, Steven D'Aprano wrote: > On Mon, 19 Feb 2007 23:18:02 -0800, Ziga Seilnacht wrote: > > George Sakkis wrote: > >> I was kinda surprised that setting __class__ or __dict__ goes through > >> the __setattr__ mechanism, like a normal attribute: > > >> class Foo(object): > >> def __setattr__(self, attr, value): > >> pass > > >> class Bar(object): > >> pass > > >> >>> f = Foo() > >> >>> f.__class__ = Bar > >> >>> print f.__class__ is Foo > >> True > > >> Is there a way (even hackish) to bypass this, or at least achieve > >> somehow the same goal (change f's class) ? > > >> George > > >>>> object.__setattr__(f, '__class__', Bar) > >>>> f.__class__ is Bar > > True > > This version is arguably more "correct", although a tad longer to write, > and doesn't need you to hard-code the class superclass: > > super(f.__class__, f).__setattr__('__class__', Bar) > > But what surprised me was that this *didn't* work: > > >>> f = Foo() > >>> f.__dict__['__class__'] = Bar > >>> f.__class__ > > > > Unless I'm confused, it looks like instance.__class__ bypasses the usual > lookup mechanism (instance.__dict__, then instance.__class__.__dict__) for > some reason. > > >>> Foo.x = 1 # stored in class __dict__ > >>> f.x > 1 > >>> f.__dict__['x'] = 2 # stored in instance __dict__ > >>> f.x > 2 > >>> Foo.x > > 1 > > But __class__ doesn't behave like this. Why? > Magic attributes like __class__ are looked up on the class rather than the instance. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -- > Steven. From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 12:40:26 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 18:40:26 +0100 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: Thinker wrote: > You can add some printf() to throw out messages to make sure where the > program stop at. > If you can compile the module with debug information and use gdb to > backtrace dump file, > it would be useful. Did it. The arguments are parsed, but the coord tuple isn't. But can PyArg_ParseTuple be used to tuples other than function arguments? If not, what should I use? zefciu From tiedon_jano at hotmail.com Sun Feb 25 12:44:06 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 25 Feb 2007 17:44:06 GMT Subject: Referencing Items in a List of Tuples In-Reply-To: <1172424046.323933.85250@q2g2000cwa.googlegroups.com> References: <1172424046.323933.85250@q2g2000cwa.googlegroups.com> Message-ID: Paddy kirjoitti: > On Feb 25, 2:01 am, rshep... at nospam.appl-ecosys.com wrote: >> While working with lists of tuples is probably very common, none of my >> five Python books or a Google search tell me how to refer to specific items >> in each tuple. I find references to sorting a list of tuples, but not >> extracting tuples based on their content. >> >> In my case, I have a list of 9 tuples. Each tuple has 30 items. The first >> two items are 3-character strings, the remaining 28 itmes are floats. >> >> I want to create a new list from each tuple. But, I want the selection of >> tuples, and their assignment to the new list, to be based on the values of >> the first two items in each tuple. >> >> If I try, for example, writing: >> >> for item in mainlist: >> if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': >> ec.Append(mainlist[item][2:]) >> >> python doesn't like a non-numeric index. >> >> I would really appreciate a pointer so I can learn how to manipulate lists >> of tuples by referencing specific items in each tuple (string or float). >> >> Rich > > You might also use list comprehensions to accumulate the values you > need: > > ec = [ item[2:] for item in mainlist if item[:2] == ['eco','con'] ] > > - Paddy. > I'm nitpicking, but the OP has a list of tuples: ec = [ item[2:] for item in mainlist if item[:2] == ('eco','con') ] Cheers, Jussi From nagle at animats.com Wed Feb 14 15:12:10 2007 From: nagle at animats.com (John Nagle) Date: Wed, 14 Feb 2007 20:12:10 GMT Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: Mathias wrote: >> >> What module are you using for SSH? >> >> What's in your program that isn't pure Python? >> The problem is probably in some non-Python component; you shouldn't >> be able to force a memory protection error from within Python code. >> > > It looks like the error could be in scipy/Numeric, when a large array's > type is changed, like this: > > >>> from scipy import * > >>> a=zeros(100000000,'b') #100 MiB > >>> b=a.copy().astype('d') #800 MiB, ok > >>> a=zeros(1000000000,'b') #1GiB > >>> b=a.copy().astype('d') #8GiB, fails with sf > Segmentation fault > > if I use zeros directly for allocation of the doubles it works as expected: > > >>> from scipy import * > >>> a=zeros(1000000000,'d') #8GiB, fails with python exception > Traceback (most recent call last): > File "", line 1, in ? > MemoryError: can't allocate memory for array > >>> > > I use python 2.4, but my scipy and Numeric aren't quite up-to-date: > scipy version 0.3.2, Numeric v 24.2 That sounds like the case where the array has to be reallocated from 4-byte floats to 8-byte doubles is being botched. Take a look at "http://www.mail-archive.com/numpy-discussion at lists.sourceforge.net/msg02033.html" and then at array_cast in arrraymethods.c of scipy. There may be a reference count bug in that C code. I'm not familiar enough with Python reference count internals to be sure, though. John Nagle From kylotan at gmail.com Fri Feb 9 17:56:20 2007 From: kylotan at gmail.com (Ben Sizer) Date: 9 Feb 2007 14:56:20 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171052486.043598.239470@p10g2000cwp.googlegroups.com> Message-ID: <1171061780.336778.111050@v33g2000cwv.googlegroups.com> On Feb 9, 9:01 pm, s... at pobox.com wrote: > Ben> If someone could explain the limitation in detail, I expect ways > Ben> could be found around it. After all, I don't know of any other > Ben> systems that require you to recompile all the extensions when you > Ben> upgrade the application. > > Python used to work that way. You'd then silently get errors if the API > changed between version A and version B and you neglected to recompile the > extensions you compiled against version A. Maybe the Python extension API > is mature enough now that it can be frozen, but I sort of doubt it. The only reason this is an issue is because the system is tightly bound on a binary level. Decouple that and the problem goes away. These 'silent' errors will all stem from a small number of specific things, each of which can be addressed. eg. PyFile_AsFile returns a FILE*, which is all well and good if both the extension's compiler and the language's compiler agree on what you get when you dereference that type, and probably not so good when they don't. The answer there is not to make assumptions about the structure of complex types across the boundary. The same may well go for the multitude of macros that make assumptions about the structure of a PyObject. It's not really much to do with the maturity, since functions don't seem to be getting regularly removed from the API. It's more the choices made about how to implement it. -- Ben Sizer From jjl at pobox.com Sun Feb 25 11:55:13 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 25 Feb 2007 16:55:13 GMT Subject: timeout in urllib.open() References: Message-ID: <87abz2npn1.fsf@pobox.com> skip at pobox.com writes: > >> I believe this can only be set globally: > >> > >> import socket > >> socket.setdefaulttimeout(seconds) > > Stefan> Uuuh this is no solution for me, because the website-checking > Stefan> tool is part of a very very big application running in an > Stefan> application server, so globally setting the timeout may break a > Stefan> lot of other things... > > Can you try this patch: > > http://python.org/sf/723312 > > ? It's against current CVS. Also, it doesn't include urllib or urllib2 > changes, just httplib. Getting this completed would be nice. Great. Added some comments, will try to write tests and urllib2 patch later. John From steve at holdenweb.com Sat Feb 10 03:32:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 08:32:01 +0000 Subject: Glob returning an empty list when passed a variable In-Reply-To: References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 09 Feb 2007 14:15:51 +0000, Steve Holden wrote: > >> area_name_string = '*% s*' % (Area_name) >> >> Interesting, I never realised until now that you can have spaces between >> the percent sign and th format effector. > > Space is one of the flags. From the docs: > > > The conversion flag characters are: > > Flag Meaning > # The value conversion will use the ``alternate form'' (where defined > below). > 0 The conversion will be zero padded for numeric values. > - The converted value is left adjusted (overrides the "0" conversion if > both are given). > (a space) A blank should be left before a positive number (or empty > string) produced by a signed conversion. > + A sign character ("+" or "-") will precede the conversion (overrides a > "space" flag). > > > http://docs.python.org/lib/typesseq-strings.html > >>> "% s" % 'banana' 'banana' >>> "% s" % 1 '1' >>> "% s" % -1 '-1' >>> Since it appears non-operative in the case of strings I'd be tempted to leave it out, though my original post was triggered by my surprise that I'd not seen the feature before. There are no limits to my ignorance :) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From paul at boddie.org.uk Mon Feb 26 10:05:42 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 26 Feb 2007 07:05:42 -0800 Subject: Python / Socket speed In-Reply-To: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> References: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> Message-ID: <1172502342.047416.280140@k78g2000cwa.googlegroups.com> On 26 Feb, 15:54, "m... at infoserv.dk" wrote: > Seems like sockets are about 6 times faster on OpenSUSE than on > Windows XP in Python. > > http://pyfanatic.blogspot.com/2007/02/socket-performance.html > > Is this related to Python or the OS? >From the output: > TCP window size: 8.00 KByte (default) > TCP window size: 49.4 KByte (default) I don't pretend to be an expert on TCP/IP, but might the window size have something to do with it? Paul From exarkun at divmod.com Fri Feb 16 10:51:56 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 16 Feb 2007 10:51:56 -0500 Subject: Pep 3105: the end of print? In-Reply-To: <740c3aec0702160749m7586f102u218374c31d7792df@mail.gmail.com> Message-ID: <20070216155156.25807.1133265258.divmod.quotient.23974@ohm> On Fri, 16 Feb 2007 16:49:05 +0100, BJ?rn Lindqvist wrote: >On 2/16/07, Jean-Paul Calderone wrote: >>I was just pointing out that some people might be confused. I didn't make >>any judgement about that fact. You seem to be suggesting that because >>there >>are other confusing things, it's okay for Python to be confusing too. I'm >>not making any judgements about that, either. > >Does not change always cause confusion? The confusion in Python land >is pretty minor in comparison to the one caused Java 1.1, 1.2, 1.3, >1.4, 1.5, 1.6, 1, 2, 4, 5, 6 SE/ME/EE. You're just repeating the same argument. I don't buy it, but I'm sure you and other people will continue to repeat it. Fine, whatever, but I'm not interested, and your not countering the point I made. > >I think that people are just complaining to much. The python-devvers >are managing the transition extraordinarily well. >> >Even in the Python world, nobody expects to run the same code base under >> >C Python and Jython and IronPython and PyPy. >> > >> >>I wonder if the fact that Jython and IronPython can't run most Python >>programs >>is one of the reasons they are generally only used in special >>circumstances? > >Or maybe it is because Jython requires Java and IronPython a CLR? > I have a JVM and I have Mono. I don't use Jython or IronPython. Maybe because none of my Python programs run on it? Jean-Paul From jstroud at mbi.ucla.edu Wed Feb 14 22:45:14 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 19:45:14 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Wed, 14 Feb 2007 13:25:21 -0800, James Stroud wrote: > > >>But then again, the unimaginative defense would be that it wouldn't be >>python if you could catentate a list and a tuple. > > > Since lists and tuples are completely different objects with completely > different usages, what should concatenating a list and a tuple give? > Should it depend on the order you pass them? Is that a guess or just common sense? > 1.0 + 1 == 1 + 1.0 for very good reasons: we consider (for pragmatic > reasons to do with loss of significant digits) that floats coerce ints > into floats rather than the other way around. But what should lists and > tuples do? > > From the Zen of Python: > "In the face of ambiguity, refuse the temptation to guess." Do you guess with __add__ and __radd__? James From ahmerhussain at gmail.com Sat Feb 17 23:56:24 2007 From: ahmerhussain at gmail.com (Ahmer) Date: 17 Feb 2007 20:56:24 -0800 Subject: PyDev on Mac Message-ID: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> I've been trying to set up PyDev on my new MacBook Pro, but i have not had an success. Could you please help! From istvan.albert at gmail.com Wed Feb 14 10:29:35 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 14 Feb 2007 07:29:35 -0800 Subject: threading and multicores, pros and cons In-Reply-To: References: <7xodnx2vir.fsf@ruckus.brouhaha.com> Message-ID: <1171466975.480917.6540@l53g2000cwa.googlegroups.com> On Feb 14, 1:33 am, Maric Michaud wrote: > At this time, it 's not easy to explain him that python > is notflawed compared to Java, and that he will not > regret his choice in the future. Database adaptors such as psycopg do release the GIL while connecting and exchanging data. Apache's MPM (multi processing module) can run mod_python and with that multiple python instances as separate processes thus avoiding the global lock as well. > plone install up and running, he will immediately compare it to > J2EE wonder why he should pay a consultant to make it work properly. I really doubt that any performance difference will be due to the global interpreter lock. This not how things work. You most certainly have far more substantial bottlenecks in each application. i. From tech-hr at smartcharter.com Sat Feb 24 12:58:46 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Sat, 24 Feb 2007 09:58:46 -0800 Subject: Jobs: Lisp and Python programmers (Los Angeles) Message-ID: http://www.smartcharter.com/jobs.html From gagsl-py2 at yahoo.com.ar Sun Feb 25 04:32:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 06:32:50 -0300 Subject: select which lib for iNet? References: <5c62a320702250112u4c4fb047u50144a4124e1d620@mail.gmail.com> Message-ID: En Sun, 25 Feb 2007 06:12:32 -0300, Marco escribi?: > I wanta know why (Py)Qt has its own lib on socket/ sql/ openGL,etc ? > Is the lib better than standard lib? See http://www.commandprompt.com/community/pyqt/x3738 In short, because Qt already had them, and some callbacks or function calls may need to use them instead of the native Python classes. -- Gabriel Genellina From naima.mans at gmail.com Tue Feb 27 05:19:28 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 27 Feb 2007 02:19:28 -0800 Subject: spawnl and waitpid Message-ID: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> hello, I run a python cgi script under Apache... and while the script is running i want to display a "please wait" message until the script finish. I have tried to do this but the "please wait" message appears at the script end (which is useless at this time! ) here my script: ------------------------------------------------------------------------------------------------ def get_ret(status): signal = status & 0xff if signal == 0: retcode = status >> 8 else: retcode = 0 return signal,retcode pidActuel = os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python","Main.py") if ( get_ret(os.waitpid(pidActuel,0))[1] == 0 ): print """ END""" else: print """ please wait... """ ------------------------------------------------------------------------------------------------- From fredrik at pythonware.com Sun Feb 11 09:17:37 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Feb 2007 15:17:37 +0100 Subject: HTML Parsing References: <1171148863.807386.310960@h3g2000cwc.googlegroups.com> <1171182045.946209.15730@l53g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > One can even use ElementTree, if the HTML is well-formed. See below. > However if it is as ill-formed as the sample (4th "td" element not > closed; I've omitted it below), then the OP would be better off > sticking with Beautiful Soup :-) or get the best of both worlds: http://effbot.org/zone/element-soup.htm From researchbase at gmail.com Sun Feb 11 12:37:03 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 11 Feb 2007 23:07:03 +0530 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: Message-ID: well yes, I need to view reports on line and also print them from within my app. so yes I need to display the pdf in my app and print it as well. regards. Krishnakant From bg_ie at yahoo.com Wed Feb 7 04:02:39 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 7 Feb 2007 01:02:39 -0800 Subject: Getting a class name from within main Message-ID: <1170838959.441543.19720@s48g2000cws.googlegroups.com> Hi, Lets say I have the following class - class MyClass: def __init__(self): print (__name__.split("."))[-1] if __name__ == '__main__': MyClassName = "MyClass" I can print the name of the class from within the class scope as seen above in the init, but is there any way of printing it from within the main without creating an object of the MyClass type. I need to assign the name of the class within my script, to a variable in main. Thanks, Barry. From troy.melhase at gmail.com Fri Feb 23 17:57:06 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Fri, 23 Feb 2007 13:57:06 -0900 Subject: Having multiple instances of a single application start a single instance of another one In-Reply-To: <45df6b91$0$487$cc7c7865@news.luth.se> References: <45df6400$0$489$cc7c7865@news.luth.se> <45df6b91$0$487$cc7c7865@news.luth.se> Message-ID: > Three very simple questions then. > > 1. How do I find out a running applications process ID import os mypid = os.getpid() > 2. How do I check if a process ID is bound to a running application. this is os-specific. i'm sure there's a windows api provided for it. > 3. There won't be any issues with different applications trying to read > and write the same file doing this? shouldn't be any problem: only the first app started will write to the file. From aspineux at gmail.com Thu Feb 1 17:47:34 2007 From: aspineux at gmail.com (aspineux) Date: 1 Feb 2007 14:47:34 -0800 Subject: imaplib: support for more cyrus extension : expire Message-ID: <1170370054.482202.235820@a75g2000cwd.googlegroups.com> setacl and getacl look to be already "Cyrus" specific (according the doc), why not to extend imaplib a little bit more ? Here are some code I wrote and tested to support cyrus "expire" that manage how long a message can stay into a mailbox. This is usefull for NEWS server ! The code is preceded by lot of sample. I wrote the 2 generic functions getannotation and setannotation that coul be used with any IMAP server. And use them to access the Cyrus extensions ! I tried to use http://www.potaroo.net/ietf/all-ids/draft-daboo-imap- annotatemore-00.txt but used a lot TCPDUMP to compare with cyradm :-) Any chances to see this small part of me into the official python release ? """IMAP4 Client Extend default python imaplib to include ANNOTATION as described in http://www.potaroo.net/ietf/all-ids/draft-daboo-imap-annotatemore-00.txt This extention is used by cyrus imap, for exemple to manage automatique removale of expired mail based on '/vendor/cmu/cyrus-imapd/expir' annotation """ """ Some usage >>> i.getannotation('user/alain.spineux at asxnet.loc', '"*"', '"value.shared"') >>> i.getannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '"value.shared"') ('OK', ['"user/alain.spineux at asxnet.loc" "/vendor/cmu/cyrus-imapd/ expire" ("value.shared" "44")']) >>> i.getannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '("value.shared")') ('OK', ['"user/alain.spineux at asxnet.loc" "/vendor/cmu/cyrus-imapd/ expire" ("value.shared" "44")']) >>> i.getannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '("*")') ('OK', ['"user/alain.spineux at asxnet.loc" "/vendor/cmu/cyrus-imapd/ expire" ("value.shared" "44" "content-type.shared" "text/plain" "size.shared" "2" "modifiedsince.shared" "1156264470")']) >>> i.getannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '("value.shared" "content-type.shared")') ('OK', ['"user/alain.spineux at asxnet.loc" "/vendor/cmu/cyrus-imapd/ expire" ("value.shared" "44" "content-type.shared" "text/plain")']) >>> i.setannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '("value.shared" "44")') ('OK', [None]) >>> i.setannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '("value.shared" NIL)') ('OK', [None]) >>> i.getannotation('user/alain.spineux at asxnet.loc', '/vendor/cmu/cyrus-imapd/expire', '("value.shared")') ('OK', [None]) some more >>> i=cyrusimap.CYRUSIMAP4('localhost') >>> i.login('manager', 'password') ('OK', ['User logged in']) >>> i.getcyrusexpire("user/alain.spineux at asxnet.loc") ('OK', 0) >>> i.setcyrusexpire("user/alain.spineux at asxnet.loc", 88) ('OK', [None]) >>> i.getcyrusexpire("user/alain.spineux at asxnet.loc") ('OK', 88) >>> i.setcyrusexpire("user/alain.spineux at asxnet.loc", None) ('OK', [None]) >>> i.getcyrusexpire("user/alain.spineux at asxnet.loc") ('OK', 0) """ import imaplib imaplib.Commands.update( { 'GETANNOTATION': ('AUTH', 'SELECTED'), 'SETANNOTATION': ('AUTH', 'SELECTED'), }) class CYRUSIMAP4(imaplib.IMAP4): def getannotation(self, root, entry, attrib): """Get annotation (typ, [data]) = .getannotation(self, root, entry, attrib) """ typ, dat = self._simple_command('GETANNOTATION', root, entry, attrib) return self._untagged_response(typ, dat, 'ANNOTATION') def setannotation(self, root, entry, value): """Set annotation value. (typ, [data]) = .setannotation(root, limits) """ typ, dat = self._simple_command('SETANNOTATION', root, entry, value) return self._untagged_response(typ, dat, 'ANNOTATION') def getcyrusexpire(self, root): """Get cyrus 'expire' annotation value. (typ, [data]) = .getcyrusexpire(root) """ typ, dat=self.getannotation(root, '/vendor/cmu/cyrus-imapd/ expire', '("value.shared")') if typ!='OK': return typ, dat if dat[0]==None: return typ, 0 # ['"user/alain.spineux at asxnet.loc" "/vendor/cmu/cyrus-imapd/ expire" ("value.shared" "44")']) v=int(dat[0].split(None,2)[2].strip('()').split(None,1) [1].strip('"')) return typ, v def setcyrusexpire(self, root, value): """Get cyrus 'expire' annotation value. (typ, [data]) = .setcyrusexpire(root, value) """ if value==None or value==0: v='NIL' else: v='"%d"' % (value,) return self.setannotation(root, '/vendor/cmu/cyrus-imapd/ expire', '("value.shared" %s)'%(v,)) From pete at shinners.org Tue Feb 27 18:00:35 2007 From: pete at shinners.org (shredwheat) Date: 27 Feb 2007 15:00:35 -0800 Subject: Vector, matrix, normalize, rotate. What package? In-Reply-To: <1172616572.045690.17550@k78g2000cwa.googlegroups.com> References: <1172616572.045690.17550@k78g2000cwa.googlegroups.com> Message-ID: <1172617235.644270.91570@8g2000cwh.googlegroups.com> On Feb 27, 2:49 pm, "Mattias Br?ndstr?m" wrote: > I'm trying to find what package I should use if I want to: > > 1. Create 3d vectors. > 2. Normalize those vectors. > 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in > radians. > 4. Perform matrix multiplication. You should have good luck with cgkit. If you are having trouble getting a compile of v2, there is an older v1 that is pure python. There are various implementations all around the net, but I'm not sure of anything standalone and actually released. From andrewfelch at gmail.com Tue Feb 27 17:54:11 2007 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 27 Feb 2007 14:54:11 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172615426.752353.25610@8g2000cwh.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> <1172615426.752353.25610@8g2000cwh.googlegroups.com> Message-ID: <1172616850.962166.27480@k78g2000cwa.googlegroups.com> On Feb 27, 5:30 pm, "Ziga Seilnacht" wrote: > Andrew Felch wrote: > > > Thanks Ziga. I use pickle protocol 2 and binary file types with the > > command: "cPickle.dump(obj, file, 2)" > > > I did your suggestion, i commented out the "__call__" function of > > MetaInstanceTracker and copied the text to the __new__ function of > > AutoReloader (code appended). I got a crazy recursive error message > > (also appended below). In my code, I am creating a new instance, > > rather than using the pickled object (it needs to work in both modes). > > > Thanks very much for helping me get through this. With my development > > approach, finding a solution to this problem is really important to > > me. > > Here is a version that should work. It should work with all protocols, > see InstanceTracker.__reduce_ex__. Note that all subclasses of > InstanceTracker and AutoReloader should be cautious when overriding > the > __new__ method. They must call their base class' __new__ method, > preferably by using super(), or the tracking won't work. > > # adapted fromhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > > import weakref, inspect > > class MetaInstanceTracker(type): > > def __init__(cls, name, bases, ns): > super(MetaInstanceTracker, cls).__init__(name, bases, ns) > cls.__instance_refs__ = [] > > def __instances__(cls): > instances = [] > validrefs = [] > for ref in cls.__instance_refs__: > instance = ref() > if instance is not None: > instances.append(instance) > validrefs.append(ref) > cls.__instance_refs__ = validrefs > return instances > > class InstanceTracker(object): > > __metaclass__ = MetaInstanceTracker > > def __new__(*args, **kwargs): > cls = args[0] > self = super(InstanceTracker, cls).__new__(*args, **kwargs) > cls.__instance_refs__.append(weakref.ref(self)) > return self > > def __reduce_ex__(self, proto): > return super(InstanceTracker, self).__reduce_ex__(2) > > class MetaAutoReloader(MetaInstanceTracker): > > def __init__(cls, name, bases, ns): > super(MetaAutoReloader, cls).__init__(name, bases, ns) > f = inspect.currentframe().f_back > for d in [f.f_locals, f.f_globals]: > if name in d: > old_class = d[name] > for instance in old_class.__instances__(): > instance.change_class(cls) > > cls.__instance_refs__.append(weakref.ref(instance)) > for subcls in old_class.__subclasses__(): > newbases = [] > for base in subcls.__bases__: > if base is old_class: > newbases.append(cls) > else: > newbases.append(base) > subcls.__bases__ = tuple(newbases) > break > > class AutoReloader(InstanceTracker): > > __metaclass__ = MetaAutoReloader > > def change_class(self, new_class): > self.__class__ = new_class > > Ziga I pasted the code into mine and replaced the old. It seems not to work for either unpickled objects or new objects. I add methods to a class that inherits from AutoReloader and reload the module, but the new methods are not callable on the old objects. Man! It seems we're so close, it will be huge if this ends up working. This stuff is so over my head, I wish I could help in some additional way. -Andrew From jstroud at mbi.ucla.edu Mon Feb 26 21:57:14 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 26 Feb 2007 18:57:14 -0800 Subject: Probably somewhat silly newbie question In-Reply-To: <1172544257.686173.180650@p10g2000cwp.googlegroups.com> References: <1172544257.686173.180650@p10g2000cwp.googlegroups.com> Message-ID: elgrandchignon at gmail.com wrote: > Hi all-- > > Trying to learn Python w/little more than hobbyist (bordering on pro/ > am, I guess) Perl as a background. > > My problem is, I have a list of departments, in this instance, things > like "Cheese", "Bakery", et al. (I work @ a co-op health food store). > I've populated a list, 'depts', w/these, so that their indexes match > our internal indexing (which skips a few #'s). > > Now, I'd like to simply generate-- and be able to refer to-- a bunch > of other lists-sets (for subdepartments) by iterating through this > list, and naming each of these subdepartment lists "categoryx", where > x is the index # from the master 'depts' list. And then be able to > populate & refer to these lists by accessing their variable-including > name. > > In Perl, it's a fairly trivial matter to use a string variable in > naming some other kind of variable-- not sure about Python though. My > initial, very weak stab at it (don't laugh!) went something like this: > > for i in range(len(depts)): > if depts[i]: > categorylistdeptname = 'category' + str(i) > categorylistdeptname = [] > > Not sure what that wound up doing, but it sure didn't seem to work. First, your are rebinding categorylistdeptname in the loop every time. But you probably want a dict (in python 2.4 or later): deptdict = dict((dept, []) for dept in depts)) And this gets what you want, believe it or not. Now you can populate each list: deptdict['Bakery'].append("Donuts") deptdict['Bulk'].extend(["Granola", "Rasins"]) And work witht the lists by name: for item in deptdict['Bulk']: print item # prints "Granola", "Rasins", etc. James From tinaweb at bestemselv.com Sat Feb 10 03:11:34 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sat, 10 Feb 2007 09:11:34 +0100 Subject: interacting with shell - another newbie question In-Reply-To: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> References: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> Message-ID: <0e2dnUM6nIWq41DYRVnzvA@telenor.com> James wrote: > Hello, > > I work in this annoying company where I have to autheticate myself to > the company firewall every 30-50 minutes in order to access the > internet. (I think it's a checkpoint fw). > > I have to run "telnet what.ever.ip.address 259" then it prompts me > with userid, then password, then I have to select "1". Then the > program closes itself and the internet is enabled. > > I would like to automate this process with Python and run it every 30 > miniutes so I don't have to keep typing in these userid/password > everytime. How can this be done? Is there a module I can use to > interact with the shell? (I'm running linux) > > Thank you. > > James > Sounds like the perfect way to get fired. To be sure though, remember to store your password in clear text ;) However bizarre the security measures seem it's obviously in place to make sure it's *you* sitting at the computer. Scripting the authentication process is equal to simply removing it. From zahidahmadzai at gmail.com Mon Feb 5 11:07:19 2007 From: zahidahmadzai at gmail.com (Zahid Ahmadzai) Date: Mon, 5 Feb 2007 16:07:19 +0000 Subject: No subject Message-ID: HI THERE I NEED HELP WITH THE FOLLOWING EXERSISE CAN YOU PLEASE HELP IF YOU CAN. PLEASE SEND ME THE CODE ON E-MAIL MANY THANKS For presentation to your tutor during your scheduled tutorial in the week commencing 12 February. I decided that it might be a good idea to create a suitable program to test sorting algorithms using simple integer data. Although our student record program is realistic in terms of the data it uses, integers have the advantage that they can be generated automatically (using the *rand()*function to return a random integer). To use *rand()* you need to *#include *. An outline design for a program would be much the same as the initial design for the student record program: - get the data - sort the data - display the results In this case the data will be 'generated' using the random number function (instead of reading data from a file). We need to clarify a little bit how the user interface would appear. As far as I am concerned, I have decide that the program will run interactively (keyboard input and display output) as follows: How many numbers to sort? 50 Numbers generated ... 41 467 334 500 169 724 478 358 962 464 705 145 281 827 961 491 995 942 827 436 391 604 902 153 292 382 421 716 718 895 447 726 771 538 869 912 667 299 35 894 703 811 322 333 673 664 141 711 253 868 After sorting ... 41 141 145 153 169 253 281 292 299 322 333 334 358 382 391 421 436 447 464 467 478 491 500 538 604 664 667 673 703 705 711 716 718 724 726 771 811 827 827 868 869 894 895 902 912 942 961 962 995 At the moment this only uses the bubble sort (as we have in the notes) and I have arbitrarily decided to generate random numbers between 0 and 999. The constant field width is obtained by using the *cout.width(4)* function call. Using the following data type and prototypes: typedef int intArray[]; void generate(intArray nums, int size, int low, int high); //generates size random ints between low and high inclusive void bubSort(intArray nums, int size); void displayNums(intArray nums, int size); //displays numbers nicely laid out // in this case - of width 4 digits and 15 to a line void display(int n); //displays a single integer in a fieldwidth of 4 chars bool notInOrder(int a, int b); //returns true if a and b need swapping and a *main()* function which has the following design: void main() { const int MAX_SIZE = 5000; // arbitrary int numbers[ MAX_SIZE ]; int howMany; cout << "How many numbers to sort? " ; cin >> howMany; if ( howMany > MAX_SIZE ) { howMany = MAX_SIZE; } generate( numbers, howMany, 0, 999 ); cout << "Numbers generated..." << endl; displayNums( numbers, howMany ); bubSort( numbers, howMany ); cout << "After sorting..." << endl; displayNums( numbers, howMany ); } Complete the program so that it behaves much as shown above. Notes: The bubble sort code is given in the notes (use the best version) - you need to change it (very slightly) to work with an array of integers instead of an array of students. The function *generate()* is a bit tricky. Think about how to start with a simple *stub* (i.e. don't worry initially about implementing the whole functionality - just make some numbers using simple code that can be sorted. The function *displayNums()* can also initially be implemented in a crude form (i.e. a *stub*) and improved later. Think carefully about how you test *generate()*. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Thu Feb 1 15:09:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 17:09:37 -0300 Subject: Inconsistent list/pointer problem References: Message-ID: En Thu, 01 Feb 2007 10:23:16 -0300, Doug Stell escribi?: > I am having a problem with the corruption of a list. It occurs only > the first time that I call a function and never happens on subsequent > calls. Any suggestions would be appreciated. > > I call the function, passing in a list as the input data. The function > must manipulate and operate on a copy of that list's data, without > altering the list in the calling routine. > > def myFunc(listA): > listB = listA > work on & modify listB > return(listB) This article will help you understanding this behavior: http://effbot.org/zone/python-objects.htm -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun Feb 25 20:43:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 22:43:03 -0300 Subject: Nested Parameter Definitions References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> Message-ID: En Sun, 25 Feb 2007 15:00:31 -0300, Paddy escribi?: >>>> def x ((p0, p1), p2): > ... return p0,p1,p2 The first time I saw it used was in Zope, a long time ago. And I like it. Of course it only has any sense if you expect the tuple (p0,p1) to exist *before* the function is called; by example, when it's the return value of some other function. -- Gabriel Genellina From grante at visi.com Wed Feb 21 21:26:08 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 22 Feb 2007 02:26:08 -0000 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172103048.160783.309470@l53g2000cwa.googlegroups.com> Message-ID: <12tpvq0t909l616@corp.supernews.com> On 2007-02-22, Harlin Seritt wrote: >> Try opening your file in the 'wb' mode. > I tried doing this: > > text = 'supercalifragilisticexpialidocius' > > open('sambleb.conf', 'wb').write(text) > > Afterwards, I was able to successfully open the file with a text > editor and it showed: > 'supercalifragilisticexpialidocius' Of course it did. > I am hoping to have it show up some weird un-readable text. > And then of course be able to convert it right back to a > string. Is this even possible? Sure. That's what is called "encryption". There are a bunch of encryption libraries for Python. http://www.amk.ca/python/code/crypto http://www.freenet.org.nz/ezPyCrypto http://www.example-code.com/python/encryption.asp http://www.chilkatsoft.com/python-encryption.asp -- Grant Edwards grante Yow! Two with FLUFFO, at hold th' BEETS...side of visi.com SOYETTES! From nagle at animats.com Tue Feb 6 15:24:17 2007 From: nagle at animats.com (John Nagle) Date: Tue, 06 Feb 2007 12:24:17 -0800 Subject: Trouble fixing a broken ASCII string - "replace" mode in codec not working. Message-ID: I'm trying to clean up a bad ASCII string, one read from a web page that is supposedly in the ASCII character set but has some characters above 127. And I get this: File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch sitetext = sitetext.encode('ascii','replace') # force to clean ASCII UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151: ordinal not in range(128) Why is that exception being raised when the codec was told 'replace'? (And no, just converting it to Unicode with "sitetext = unicode(sitetext)" won't work either; that correctly raises a Unicode conversion exception.) [Python 2.4, Win32] JohnNagle From bruno.desthuilliers at gmail.com Wed Feb 28 02:48:49 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 27 Feb 2007 23:48:49 -0800 Subject: database without installation again In-Reply-To: References: Message-ID: <1172648929.821762.294820@t69g2000cwt.googlegroups.com> On 28 f?v, 00:06, "andrew_s" wrote: > Hi! > > I'm looking for any database which I could use without need of instalation. > I've read some threads here but I couldn't find any complete answer. > On my ISP's server I can use Python throu cgi only. There is Python 2.4.3 > and it has only standard library modules and no possibility to oficially > install anything else. Can't you install additional stuff in your own directory, then correct your PYTHONPATH as needed ? > Any ideas? Maybe is it possible to "install" by myself something like SQLite > or MySQLdb in my cgi-bin directory? I've tried it putting files from MySQLdb > module, but there was errors with missing libssl.so or sth. MySQL is a server software. You cannot just drop some files and expect the whole thing to work. > I think, the > best solution would be db stored in binary file with interface in based on > standard Python library, but is there anything like that?? SQLite ? Gadfly ? From fatwallet961 at yahoo.com Fri Feb 2 23:12:09 2007 From: fatwallet961 at yahoo.com (fatwallet961 at yahoo.com) Date: Fri, 02 Feb 2007 20:12:09 -0800 Subject: from... import... Message-ID: <9s28s29864vgkdbtevi8fna5h1r04ekgr9@4ax.com> what's the from ... import keyword use for? for example - from contenttype import getContentType import os import sys import getopt import types import re import pprint import logging from contenttype import getContentType In Java what kind of statement is similar this? thanks From JStoneGT at aol.com Tue Feb 13 21:16:29 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Tue, 13 Feb 2007 21:16:29 EST Subject: Newbie question about Class Message-ID: Thanks a lot.I've got it. En Tue, 13 Feb 2007 13:01:59 -0300, escribi?: > But I'm still confused that what's the "real dictionary"?I can't know > this > point.Please help and thanks again. I'm talking about a Python dictionary (a "real" one, as opposed to UserDict, which is a "fake" dictionary; it looks and acts like a dictionary but it's not). py> from UserDict import UserDict py> d = {"a": 1, "b": 2, "c": 3} # This is a "real" dictionary # I create an UserDict instance, its initial contents come from a dictionary py> ud1 = UserDict(d) py> ud1 {'b': 2, 'a': 1, 'c': 3} # Now I create a second UserDict instance, its initial contents come from the UserDict instance py> ud2 = UserDict(ud1) py> ud2 {'b': 2, 'a': 1, 'c': 3} -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Feb 8 10:27:35 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Feb 2007 16:27:35 +0100 Subject: help on packet format for tcp/ip programming References: Message-ID: <530tr7F1o4vrhU1@mid.uni-berlin.de> > Grant had the right idea, I think, but he failed to actually include a > byte length in his format. :) So there's nothing to peek at. If the > packing is done like this, instead.. > > > struct.pack('!IIL', len(buffer), count, offset) + buffer > > Then it is a simple matter to unpack it once the receiving side, by > waiting for struct.calcsize('!IIL') bytes, using struct to get > len(buffer), count, and offset: > > length, count, offset = struct.unpack('!IIL', bytes) > > And then waiting for `length' more bytes, which will be the buffer. That was my intention, yes - I thought the header information of the OP contained a byte count already. > I'm not sure what the original use-case was here. XML-RPC isn't a good > transport for arbitrary binary data. If `buffer' contains text, though, > that might be a good suggestion. Certainly XMLRPC isn't too good - and Pyro in many aspects better. AFAIK it uses pickle, and that means that things should be comparably compact. Diez From jeff.templon at gmail.com Tue Feb 20 11:49:10 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 08:49:10 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> Message-ID: <1171990150.797668.19770@p10g2000cwp.googlegroups.com> Yo, On Feb 16, 6:07 am, Steven Bethard wrote: > Python 3.0 is determined not to be hampered by backwards incompatibility > concerns. It's not even clear yet that your average 2.6 code will work Then Python is pretty much determined to remove itself from consideration from various kinds of international projects like the one I work on. We're already catching flack from people due to a few things that were valid in 2.2 that are not valid in 2.3 (I don't have the details but could scare them up). The project we work on contains code from many different people and has to run on thousands of computers all over the world. The installed base at the moment is a mix of RHEL 3, RHEL 4, and Debian, with a few other machines thrown in. The relevant Python versions at this moment IIRC are 2.2.3 and 2.3.4, because these are the native versions on those platforms. We are estimating, due to the speed at which our applications follow OS releases, that we can drop RHEL 3 (and hence Python 2.2) support a year from now. Go figure when you think we might be ready to require that all programs run on python 3.0. If it's not backwards compatible, meaning if 2.4 code doesn't run on 3.0, it's rather likely that strong pressure will be applied to port *away* from Python into something less capricious. Bottom line: practicality and beauty is always a tradeoff. Oberon is the most beautiful language I ever saw, but there is almost nobody using it any more. Too many beauty contests over who had the best proposal for a standard library. From skip at pobox.com Thu Feb 8 19:31:18 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 8 Feb 2007 18:31:18 -0600 Subject: Looking for a MoinMoin guru - MoinMoin+SpamBayes == no wiki spam? Message-ID: <17867.49366.409452.776005@montanaro.dyndns.org> I have this idea that I should be able to write a security policy for MoinMoin which uses SpamBayes to judge the appropriateness of any given submission. It would be more accurate and faster than the current default security policy in MoinMoin. I started to work on it and have something that seems to be working on the SpamBayes side of things, but I can't get the MoinMoin side of the equation to balance. My messages to the moin-user mailing list have so far fallen on blind eyes, so I'm broadening my search for a MoinMoin expert who would like to help me finish off this demonstration. If you're interested in pursuing this idea here are a couple URLs: * The current code: http://spambayes.cvs.sourceforge.net/spambayes/spambayes/spambayes/MoinSecurityPolicy.py?view=log * My messages to moin-user: http://article.gmane.org/gmane.comp.web.wiki.moin.general/4381/match=spambayes http://article.gmane.org/gmane.comp.web.wiki.moin.general/4488/match=spambayes The motivation for the concept is in the docstring of the module as well as in the messages, so I won't belabor the point here. As one of the current "editors" of the Python wiki I can tell you the current scheme of using lists of "naughty words" to identify potential wiki spam is far from perfect. There's also the motivation found here: http://www.publicradio.org/columns/futuretense/ Scroll down and listen to the February 1st episode. Thanks, Skip From arkanes at gmail.com Mon Feb 26 16:20:00 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 26 Feb 2007 15:20:00 -0600 Subject: 2.4->2.5 current directory change? In-Reply-To: <1172523655.177915.94840@s48g2000cws.googlegroups.com> References: <1172523655.177915.94840@s48g2000cws.googlegroups.com> Message-ID: <4866bea60702261320h658b60d4ue14c35ebc57f9aca@mail.gmail.com> On 26 Feb 2007 13:00:55 -0800, Ziga Seilnacht wrote: > On Feb 26, 7:44 pm, "Chris Mellon" wrote: > > This appears to be a change in behavior from Python 2.4 to Python 2.5, > > which I can't find documented anywhere. It may be windows only, or > > related to Windows behavior. > > > > In 2.4, the current directory (os.curdir) was on sys.path. In 2.5, it > > appears to be the base directory of the running script. For example, > > if you execute the file testme.py in your current working directory, > > '' is on sys.path. If you execute c:\Python25\Scripts\testme.py, '' is > > *not* on sys.path, and C:\Python25\Scripts is. > > > > That means if you run a Python script located in another directory, > > modules/etc in your current working directory will not be found. This > > makes .py scripts in the PYTHONHOME\Scripts file moderately useless, > > because they won't find anything in the current working directory. > > > > I first noticed this because it breaks Trial, but I'm sure there are > > other scripts affected by it. Is this desirable behavior? Is there > > anything to work around it except by pushing os.curdir onto sys.path? > > > The change was intentional and is mentioned in the NEWS file: > > - Patch #1232023: Stop including current directory in search path > on Windows. > > This unifies Python's behaviour across different platforms; the > docs always said that the current directory is inserted *only* > if the script directory is unavailable: > > As initialized upon program startup, the first item of this list, > path[0], is the directory containing the script that was used to > invoke the Python interpreter. If the script directory is not > available (e.g. if the interpreter is invoked interactively or > if the script is read from standard input), path[0] is the empty > string, which directs Python to search modules in the current > directory first. Notice that the script directory is inserted > before the entries inserted as a result of PYTHONPATH. > > The old behaviour was never intentional and wasn't desired, > because users could break an application simply by running it > from a directory that contained inappropriately named files. > > For details see the bug report and patch submission: > http://www.python.org/sf/1526785 > http://www.python.org/sf/1232023 > > Ziga > Considering that it's a backwards incompatible breaking change (although I understand why it was done), you'd think it deserved mention in the more prominent "Whats new in Python 2.5" section on the website, in addition to a one-liner in the NEWS file. Ah well, while I'm sure I'm not the only one who ran into it, it doesn't seem to be causing mass calamity and I know now. From horpner at yahoo.com Sun Feb 11 09:01:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sun, 11 Feb 2007 14:01:12 GMT Subject: gvim: doc string editing References: <1171201896.897644.60000@p10g2000cwp.googlegroups.com> Message-ID: On 2007-02-11, jm.suresh at no.spam.gmail.com wrote: > Hi, I am using gvim, and am looking for a way to tell gvim to > automatically wrap long lines into multiple lines ( by > automatically inserting the newline character) when I edit doc > strings. I am sure somebody must have done this. If tw (textwidth) is set to some apposite number, then it should just work (unfortunately, this will also cause your code to wrap unless you set up the comment strings properly for Python). Alternatively, you can use the gq formatting command to wrap the comment after it is composed. Do :h format_comments for the full dope. -- Neil Cerutti From steven.klass at gmail.com Tue Feb 27 13:59:02 2007 From: steven.klass at gmail.com (rh0dium) Date: 27 Feb 2007 10:59:02 -0800 Subject: Tackling setup.py - A bug?? Message-ID: <1172602742.449776.115830@q2g2000cwa.googlegroups.com> Hi Folks, I use p4python for all of my perforce and python related needs. I'm on a Mac (OSX 10.4). p4python relies on a perforce provided API which gets compiled when I run the setup.py. The setup.py by default does not support macs so I figured what better way to spend a night than to figure out how to add in the neccesary hooks for mac support... So the problem I am seeing is when I do an import of the module I get the following error: >>> import p4 Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/site-packages/p4.py", line 17, in import P4Client ImportError: dlopen(/usr/local/lib/python2.5/site-packages/ P4Client.so, 2): Symbol not found: _CFStringCompare Referenced from: /usr/local/lib/python2.5/site-packages/P4Client.so Expected in: dynamic lookup First I figured out how to compile the thing at the command line so it worked. ( No the default did not - I tried various derivations on it to no avail. However at long last I was able to manually compile and link this so it did work. To get it to compile I used the following two lines (compile / link) > g++ -c -o build/temp.macosx-10.3-ppc-2.5/P4Clientmodule.o - DCASE_INSENSITIVE \ -fpascal-strings -isysroot/Developer/SDKs/MacOSX10.4u.sdk -arch ppc -DCASE_INSENSITIVE \ -O2 -DOS_MACOSX -DOS_MACOSX104 -DOS_MACOSXPPC -DOS_MACOSX104PPC \ -Ip4api6.1 -I/usr/local/include/python2.5 P4Clientmodule.cc # Followed by linking using: > g++ -bundle -undefined dynamic_lookup -Wl,-syslibroot,/ Developer/SDKs/MacOSX10.4u.sdk \ -arch ppc \ -o build/lib.macosx-10.3-ppc-2.5/P4Client.so build/ temp.macosx-10.3-ppc-2.5/P4Clientmodule.o\ -Lp4api6.1 p4api6.1/libclient.a p4api6.1/librpc.a p4api6.1/ libsupp.a -framework Carbon And this followed by an setup.py install seemed to work just fine. Ok so now I need to backport these options into setup.py. Here is what I came up with.. elif os.name == "posix": setup(name=NAME, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, license=LICENSE, url=URL, keywords=KEYWORDS, classifiers = filter(None, classifiers.split("\n")), long_description = "\n".join(doclines[2:]), py_modules=PY_MODULES, ext_modules=[Extension("P4Client", ["P4Clientmodule.cc"], include_dirs=[p4_api_dir], library_dirs=[p4_api_dir], libraries=["client", "rpc", "supp"], # P4API libs extra_compile_args=["-DCASE_INSENSITIVE", "-fpascal-strings", "-isysroot/Developer/ SDKs/MacOSX10.4u.sdk", "-DOS_MACOSX", "- DOS_MACOSX104", "-DOS_MACOSXPPC", "- DOS_MACOSX104PPC" ,"-D%s" % p4_api_ver], extra_link_args=[ "-Wl,-syslibroot,/ Developer/SDKs/MacOSX10.4u.sdk", "-arch ppc", "-framework Carbon" ], )]) But low and behold it didn't work... In the course of debugging I found that the compile works. The linking appears to be a problem. In the link stage I see the command which is being run looks very similar to my command g++ -bundle -undefined dynamic_lookup build/temp.macosx-10.3-ppc-2.5/ P4Clientmodule.o \ -Lp4api6.1 -lclient -lrpc -lsupp -o build/lib.macosx-10.3-ppc-2.5/ P4Client.so \ -Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk -arch ppc -framework Carbon Not quite the same but close enough. HERE is where the bug shows up........ If I rerun this same EXACT command at the command line - followed by a setup.py install it works. Can someone with a larger python brain than mine please help me figure this out? It's bugging the crap out fo me... ARGGGGHHHHH!!! From jeff.templon at gmail.com Tue Feb 20 14:26:59 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 11:26:59 -0800 Subject: How to test if one dict is subset of another? In-Reply-To: <7x3b50d8ri.fsf@ruckus.brouhaha.com> References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> <1171990539.710698.276050@v45g2000cwv.googlegroups.com> <1171992831.871231.86450@h3g2000cwc.googlegroups.com> <7x3b50d8ri.fsf@ruckus.brouhaha.com> Message-ID: <1171999619.755238.294080@m58g2000cwm.googlegroups.com> On Feb 20, 6:44 pm, Paul Rubin wrote: > They are sets, not lists. > > from sets import Set as set # use in 2.3 and earlier > > l1= set([3, 4, 7, 2]) > l2 = set([2, 3]) > l2 = set([2, 3, 99]) > print l1 & l2 Thanks Paul, but: bosui:~> python Python 2.2.3 (#1, Oct 26 2003, 11:49:53) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-20)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sets import Set as set Traceback (most recent call last): File "", line 1, in ? ImportError: No module named sets From tbryan at python.net Fri Feb 16 08:57:02 2007 From: tbryan at python.net (Tom Bryan) Date: Fri, 16 Feb 2007 08:57:02 -0500 Subject: starship.python.net is down Message-ID: <1171634223.13643@sj-nntpcache-2.cisco.com> One of the system administrators had to reboot starship.python.net last night, but it appears that the machine did not come back up properly. starship.python.net is currently down while we investigate. ---Tom From practicalperl at gmail.com Sun Feb 11 23:36:10 2007 From: practicalperl at gmail.com (Jm lists) Date: Mon, 12 Feb 2007 12:36:10 +0800 Subject: About getattr() Message-ID: Hello, Since I can write the statement like: >>> print os.path.isdir.__doc__ Test whether a path is a directory Why do I still need the getattr() func as below? >>> print getattr(os.path,"isdir").__doc__ Test whether a path is a directory Thanks! From lbates at websafe.com Tue Feb 20 10:00:56 2007 From: lbates at websafe.com (Larry Bates) Date: Tue, 20 Feb 2007 09:00:56 -0600 Subject: Sorting directory contents In-Reply-To: References: Message-ID: <45DB0D28.6060608@websafe.com> Wolfgang Draxinger wrote: > Jussi Salmela wrote: > >> I'm not claiming the following to be more elegant, but I would >> do it like this (not tested!): >> >> src_file_paths = dict() >> prefix = sourcedir + os.sep >> for fname in os.listdir(sourcedir): >> if match_fname_pattern(fname): >> fpath = prefix + fname >> src_file_paths[os.stat(fpath).st_mtime] = fpath >> for ftime in src_file_paths.keys().sort(): >> read_and_concatenate(src_file_paths[ftime]) > > Well, both versions, mine and yours won't work as it was written > down, as they neglegt the fact, that different files can have > the same st_mtime and that .sort() doesn't return a > sorted list. > > However this code works (tested) and behaves just like listdir, > only that it sorts files chronologically, then alphabetically. > > def listdir_chrono(dirpath): > import os > files_dict = dict() > for fname in os.listdir(dirpath): > mtime = os.stat(dirpath+os.sep+fname).st_mtime > if not mtime in files_dict: > files_dict[mtime] = list() > files_dict[mtime].append(fname) > > mtimes = files_dict.keys() > mtimes.sort() > filenames = list() > for mtime in mtimes: > fnames = files_dict[mtime] > fnames.sort() > for fname in fnames: > filenames.append(fname) > return filenames > > Wolfgang Draxinger Four suggestions: 1) You might want to use os.path.join(dirpath, fname) instead of dirpath+os.sep+fname. 2) You may be able to use glob.glob() to filter the files more easily. 3) You didn't handle the possibility that there is s subdirectory in the current directory. You need to check to make sure it is a file you are processing as os.listdir() returns files AND directories. 4) If you just put a tuple containing (mtime, filename) in a list each time through the loop you can just sort that list at the end it will be sorted by mtime and then alphabetically. Example (not tested): def listdir_chrono(dirpath): import os # # Get a list of full pathnames for all the files in dirpath # and exclude all the subdirectories. Note: This might be # able to be replaced by glob.glob() to simplify. I would then # add a second optional parameter: mask="" that would allow me # to pass in a mask. # # List comprehensions are our friend when we are processing # lists of things. # files=[os.path.join(dirpath, x) for x in os.listdir(dirpath) if not os.path.isdir(os.path.join(dirpath, x)] # # Get a list of tuples that contain (mtime, filename) that # I can sort. # flist=[(os.stat(x).st_mtime, x) for x in files] # # Sort them. Sort will sort on mtime, then on filename # flist.sort() # # Extract a list of the filenames only and return it # return [x[1] for x in flist] # # or if you only want the basenames of the files # #return [os.path.basename(x[1]) for x in flist] -Larry Bates From __peter__ at web.de Thu Feb 15 17:43:06 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 15 Feb 2007 23:43:06 +0100 Subject: filecmp.cmp() cache References: <1171554885.517477.316470@s48g2000cws.googlegroups.com> <1171577045.892167.46580@p10g2000cwp.googlegroups.com> Message-ID: Mattias Br?ndstr?m wrote: > On Feb 15, 5:56 pm, Peter Otten <__pete... at web.de> wrote: >> You can clear the cache with >> >> filecmp._cache = {} >> >> as a glance into the filecmp module would have shown. > > You are right, a quick glance would have enlighten me. Next time I > will RTFS first. :-) > >> If you don't want to use the cache at all (untested): >> >> class NoCache: >> def __setitem__(self, key, value): >> pass >> def get(self, key): >> return None >> filecmp._cache = NoCache() >> > > Just one small tought/question. How likely am I to run into trouble > because of this? I mean, by setting _cache to another value I'm > mucking about in filecmp's implementation details. Is this generally > considered OK when dealing with Python's standard library? I think it's a feature that Python lends itself to monkey-patching, but still there are a few things to consider: - Every hack increases the likelihood that your app will break in the next version of Python. - You take some responsibility for the "patched" code. It's no longer the tried and tested module as provided by the core developers. - The module may be used elsewhere in the standard library or third-party packages, and failures (or in the above example: performance degradation) may ensue. For a script and a relatively obscure module like 'filecmp' monkey-patching is probably OK, but for a larger app or a module like 'os' that is heavily used throughout the standard lib I would play it safe and reimplement. Peter From stuart at bmsi.com Sat Feb 3 17:52:42 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sat, 03 Feb 2007 17:52:42 -0500 Subject: Debugging SocketServer.ThreadingTCPServer References: Message-ID: On Tue, 16 Jan 2007 09:11:38 -0500, Jean-Paul Calderone wrote: > On Tue, 16 Jan 2007 00:23:35 -0500, "Stuart D. Gathman" > wrote: >>I have a ThreadingTCPServer application (pygossip, part of >>http://sourceforge.net/projects/pymilter). It mostly runs well, but >>occasionally goes into a loop. How can I get a stack trace of running >>threads to figure out where the loop is? Is there some equivalent of >>sending SIGQUIT to Java to get a thread dump? If needed, I can import >>pdb and set options at startup, but there needs to be some external way >>of triggering the dump since I can't reproduce it at will. > > Grab the gdbinit out of Python SVN Misc/ directory. Apply this patch: > > http://jcalderone.livejournal.com/28224.html > > Attach to the process using gdb. Make sure you have debugging symbols > in your build of Python. Run 'thread apply all pystack'. Did this. gdb displays main thread fine (waiting on accept(), duh). But gdb goes into a loop displaying the first worker thread. There are no extension modules other than the batteries included ones. In this application, I believe, only _socket. (I.e. a pure python server.) I will try for a C stack trace next time it loops. Also, the looping server needs kill -9. SIGTERM and SIGINT won't stop it. And after it dies with SIGKILL, the port is still in use for 5 minutes or so (and the server cannot be restarted). This is really making me appreciate Java. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From B.Ogryczak at gmail.com Thu Feb 1 09:41:16 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 1 Feb 2007 06:41:16 -0800 Subject: SWIG overhead In-Reply-To: <52e2bsF1nlgutU1@mid.uni-berlin.de> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> <1170328902.611668.271550@k78g2000cwa.googlegroups.com> <52e2bsF1nlgutU1@mid.uni-berlin.de> Message-ID: <1170340876.890010.184840@a75g2000cwd.googlegroups.com> On Feb 1, 12:48 pm, "Diez B. Roggisch" wrote: > > Yeah, found that one googling around. But I haven?t fund anything more > > up to date. I imagine, that the performance of all of these wrappers > > has been improved since then. But the performance of Python/C API > > would too? > > Anyways, it?s not about exact number, it?s more about taking decision > > if doing rewrite is worth it?s time. > > The wrappers essentially create the boilerplate-code that invokes the Python > C-API. So whatever improvements the latter has been developed, the wrappers > will benefit from it. Without doubt it?s true in case of SWIG, but if I understand Python.Boost documentation correctly, it does *not* use Python/C API. > I doubt that there are major performance penalties associated with any of them. Take a look at pages 23 and 24 of http://people.web.psi.ch/geus/talks/ europython2004_geus.pdf > More important for a wrapper-decision is the question how easy they are to use. Well, SWIG is easy to use. But I?ve gotta make hundreds of millions of calls, which do tasks as simple, as getting one int from an array and returning it. With functions that simple SWIG?s overhead seems to be a problem. From pete at shinners.org Tue Feb 27 13:54:57 2007 From: pete at shinners.org (shredwheat) Date: 27 Feb 2007 10:54:57 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <54ijbdF1urdo2U1@mid.uni-berlin.de> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> <1172573562.215310.76760@8g2000cwh.googlegroups.com> <54ih3nF2143jeU2@mid.uni-berlin.de> <1172574041.569357.127440@q2g2000cwa.googlegroups.com> <54ijbdF1urdo2U1@mid.uni-berlin.de> Message-ID: <1172602497.566766.79250@p10g2000cwp.googlegroups.com> On Feb 27, 3:35 am, "Diez B. Roggisch" wrote: > I don't see any QPaintDevice here. Where does that come from? You need to > give more information, a stack trace and a reduced example exhibiting the > behaviour. QWidget is derived from QPaintDevice, under Qt, no widgets can be instantiated before the QApplication. This source snippet looks like it should be working. If the exception is happening inside Optimizer() than something really unsusual is happening. I suspect there is python code somewhere else happening at import time that is creating a widget. The exception traceback should show you right where that would be. From nilsoveras at yahoo.no Fri Feb 2 06:54:23 2007 From: nilsoveras at yahoo.no (Nils Overas Bergen) Date: 2 Feb 2007 03:54:23 -0800 Subject: Interpreter window Message-ID: <1170417263.849798.151010@k78g2000cwa.googlegroups.com> I have created a Python application in Windows XP which uses WxWidgets. When I start the application from the Python interpreter I get one empty interpreter window in addition to the application window. Is there a way to close the interpreter window without closing the application? Or, can I start the interpreter and the application script without starting the interpreter window? From __peter__ at web.de Fri Feb 2 12:22:44 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Feb 2007 18:22:44 +0100 Subject: from __future__ import absolute_import ? References: Message-ID: Ron Adam wrote: > > from __future__ import absolute_import > > Is there a way to check if this is working? I get the same results with > or without it. > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) > [MSC v.1310 32 bit (Intel)] on win 32 If there are two modules 'foo', one at the toplevel and the other inside a package 'bar', from __future__ import absolute_import import foo will import the toplevel module whereas import foo will import bar.foo. A messy demonstration: $ ls bar absolute.py foo.py __init__.py relative.py $ cat bar/absolute.py from __future__ import absolute_import import foo $ cat bar/relative.py import foo $ cat foo.py print "toplevel" $ cat bar/foo.py print "in bar" $ python2.5 -c 'import bar.absolute' toplevel $ python2.5 -c 'import bar.relative' in bar Another example is here: http://mail.python.org/pipermail/python-list/2007-January/422889.html Peter From tubby at bandaheart.com Tue Feb 27 21:05:51 2007 From: tubby at bandaheart.com (tubby) Date: Tue, 27 Feb 2007 21:05:51 -0500 Subject: threading a thread In-Reply-To: <54k0v7F1nt481U1@mid.individual.net> References: <54jm2pF20dq64U2@mid.individual.net> <54k0v7F1nt481U1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > tubby wrote: > >> Have you tried it? Nmap is sequential. > > RTFM? I urge you to actually try it and see for yourself. From my experience, it sucks... even when only doing 1 port it takes hours regarless of what the man page implies. I'll figure it out, thanks, Tubby. From steve at REMOVEME.cybersource.com.au Wed Feb 14 20:51:30 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 12:51:30 +1100 Subject: f---ing typechecking References: Message-ID: On Wed, 14 Feb 2007 13:25:21 -0800, James Stroud wrote: > But then again, the unimaginative defense would be that it wouldn't be > python if you could catentate a list and a tuple. Since lists and tuples are completely different objects with completely different usages, what should concatenating a list and a tuple give? Should it depend on the order you pass them? 1.0 + 1 == 1 + 1.0 for very good reasons: we consider (for pragmatic reasons to do with loss of significant digits) that floats coerce ints into floats rather than the other way around. But what should lists and tuples do? >From the Zen of Python: "In the face of ambiguity, refuse the temptation to guess." -- Steven D'Aprano From marco at waven.com Wed Feb 7 06:40:48 2007 From: marco at waven.com (Marco) Date: Wed, 7 Feb 2007 19:40:48 +0800 Subject: mplayer bug or python bug? Message-ID: <5c62a320702070340g7985cad7ue56175c88f736177@mail.gmail.com> The following code is my test program for control mplayer. in movies/ there are about 20 movies, the code plays them in circle, but mplayer will crash silently after a circle, the "sliently" means I can handle popen2 without except, but no movie. I have no idea about it... Can you help me? class SimplePlayer( myobject ): def __init__(self): self.debug('simple player init ready') self.is_open = False self.wfd = None self.rfd = None def play(self, file): if self.is_open: self.wfd.write('loadfile %s\n' %(file)) self.wfd.flush() else: self.wfd, self.rfd = os.popen2('mplayer -loop 0 -slave -quiet -ao null %s 2> /dev/null' %(file)) self.is_open = True ################## if __name__ == '__main__': player = SimplePlayer() all = os.listdir('movies/') print all while True: for current in all: print current player.play('movies/' + current) time.sleep(3) -- LinuX Power From david at boddie.org.uk Wed Feb 28 19:54:42 2007 From: david at boddie.org.uk (David Boddie) Date: Thu, 01 Mar 2007 01:54:42 +0100 Subject: How do I Color a QTableView row in PyQt4 References: <1172685355.820708.149990@q2g2000cwa.googlegroups.com> <29fbf$45e61974$54d1d767$18593@news.chello.no> Message-ID: <6caca$45e62453$54d1d767$28389@news.chello.no> [Following up my own post.] On Thursday 01 March 2007 01:08, David Boddie wrote: > It's interesting to see that you subclassed QSqlQueryModel instead of > using a custom delegate to display the data. It's usually recommended > that you subclass QItemDelegate if you want to customize the way items > are represented, but you can also customize the model if you want. On reflection, I think subclassing the model is probably the right thing to do here. Delegates are much more useful if you want to substantially alter the appearance of items, but that's not what you're trying to do here. David From lbates at websafe.com Thu Feb 22 11:30:59 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 22 Feb 2007 10:30:59 -0600 Subject: paths in modules In-Reply-To: References: Message-ID: <_YOdnU50mqTXWEDYnZ2dnUVZ_qfinZ2d@comcast.com> Brandon Mintern wrote: > I am developing a project in Python which uses several external utilities. > For convenience, I am wrapping these accesses in a module. The problem is > that I cannot be sure where these modules are imported from, so I am > trying to figure out how to reliably execute e.g. a popen call. Example > layout: > > toplevel_dir > +-main script > +-wrapper_dir > +-some_wrapper > +-utility_dir > +-some_external_utility > > So in my main script, I might say: > > from wrapper_dir import some_wrapper > > some_wrapper.use_external_utility() > > > And then in some_wrapper, I would have code like: > > import os > > def use_external_utility(): > f = os.popen('utility_dir/some_external_utility') > lines = f.readlines() > f.close() > return lines > > > Of course, the problem with that approach is that it fails because there > is no utility_dir in the CWD, which is actually top_level_dir. So my > question is whether there is any way to specify that specified paths are > relative to the module's directory rather than the importing file's > directory. I would really like to avoid kludging together some solution > that involves passing variables or having knowledge of where my module is > being imported from. > > I am hoping that there is some simple solution to this problem that I > simply haven't found in my searches so far. If so, I will humbly accept > any ridicule that comes along with said simple solution :-). > > Thanks in advance, > Brandon Normally this would be: f = os.popen('./wrapper_dir/utility_dir/some_external_utility') -Larry From ruka_at_ at fastmail.fm Fri Feb 16 06:28:59 2007 From: ruka_at_ at fastmail.fm (ruka_at_ at fastmail.fm) Date: 16 Feb 2007 03:28:59 -0800 Subject: KeyboardInterrupt not caught In-Reply-To: <1171624561.583112.89230@m58g2000cwm.googlegroups.com> References: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> <1171624561.583112.89230@m58g2000cwm.googlegroups.com> Message-ID: <1171625339.816194.74420@q2g2000cwa.googlegroups.com> On 16 Feb., 12:16, ruka_... at fastmail.fm wrote: > On 16 Feb., 11:44, "Gabriel Genellina" wrote: > > I've tried it in cygwin, result: $ python.exe c:/work/py_src/ctrl_test.py kbd-interr,SystemExit normal end br Rudi From fonnesbeck at gmail.com Thu Feb 1 13:53:43 2007 From: fonnesbeck at gmail.com (Chris) Date: Thu, 1 Feb 2007 18:53:43 +0000 (UTC) Subject: Overloading the tilde operator? Message-ID: I am trying to overload the __invert__ operator (~) such that it can take a second argument, other than self, so that I can express: x ~ y by using: def __invert__(self, other): for example. Is this possible? Thanks in advance, From aboudouvas at panafonet.gr Mon Feb 26 12:54:18 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 26 Feb 2007 09:54:18 -0800 Subject: NetUseAdd mystery In-Reply-To: References: <1172508987.854983.162370@j27g2000cwj.googlegroups.com> Message-ID: <1172512458.158528.287920@m58g2000cwm.googlegroups.com> > I think your problem is that C$ is a "special" share. Try creating > a share and connect to it instead. It is either that your your userid/ > password are in fact incorrect. > > -Larry No, my credentials are absolutely correct. As for the "$", what is the possible problem with that ?? Net use is working great and i think that also the net functions of win32api are working correct. The problem must be in some other point... From http Sat Feb 10 07:55:26 2007 From: http (Paul Rubin) Date: 10 Feb 2007 04:55:26 -0800 Subject: [off-topic] Maximum TCP Server Connections References: Message-ID: <7xabzmp3y9.fsf@ruckus.brouhaha.com> Steve Holden writes: > Sorry this question isn't strictly Python-related. Does any one know > how many simultaneous TCP connections it's practical to expect a > TCP-based server application to support (on the OS of your choice)? > I'm looking for the restrictions imposed by the operating environment > rather than the application itself. http://www.kegel.com/c10k.html From mail at timgolden.me.uk Mon Feb 12 08:45:06 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 12 Feb 2007 13:45:06 +0000 Subject: WindowsNT user authentication In-Reply-To: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> Message-ID: <45D06F62.40109@timgolden.me.uk> billie wrote: > Hi there, > I would like to submit a username/password pair to a Windows NT > workstation and find out if it's valid. > Moreover I would like to get the user's home directory given the > username. > Does it is possible to do that by using pywin32 extension? http://timgolden.me.uk/python/win32_how_do_i/check-a-users-credentials.html There are a few caveats (and there are other ways, too). This one is pretty simple, though. HTH TJG From david.wishnie at gmail.com Mon Feb 19 22:51:06 2007 From: david.wishnie at gmail.com (David Wishnie) Date: Tue, 20 Feb 2007 07:51:06 +0400 Subject: Found a product for running Python-based websites off CDROM -have anybody tried it? Message-ID: Hello, Recently I've found a product that allows to create CDs or DVDs with mod_python -based websites (and CGI python of course) so that apache-based webserver, python and mod_python are run directly off CD on Windows, MacOS X and Linux at the same time (also it seems to support perl, java, php and mysql + SQLite as databases). http://www.stunnix.com/prod/aws/overview.shtml Have anybody tried it? I'm considering to use it for several projects. Thanks, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From n00b at n00b.n00b.n00b Fri Feb 2 15:26:05 2007 From: n00b at n00b.n00b.n00b (Mister Newbie) Date: Fri, 02 Feb 2007 15:26:05 -0500 Subject: Is Python Right for Me? References: Message-ID: "Terry Reedy" wrote in news:mailman.3475.1170447779.32031.python-list at python.org: > > "Mister Newbie" wrote in message > news:Xns98CB9A2CC9C3Bn00b at 208.49.80.253... >|I want to make small, 2D games. I have no programming experience. Is > Python >| a good choice? > > Possibly. There is an add-on package called pygame that is, I > believe, 2d oriented. See www.pygame.org > There is also an associated mailing list, which you can also read via > news.gmane.org as newsgroup gmane.comp.python.pygame. > > tjr > > > > Thanks for the reply. I'll check it out. From steve at REMOVEME.cybersource.com.au Mon Feb 12 01:13:00 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 12 Feb 2007 17:13:00 +1100 Subject: randomly generate n of each of two types References: <3YOzh.1133$yg7.205@trnddc08> Message-ID: On Mon, 12 Feb 2007 00:57:35 +0000, Alan Isaac wrote: > "Stargaming" wrote in message > news:eqo184$2u7e$1 at ulysses.news.tiscali.de... >> ... types *= n >> ... shuffle(types) > > This again has the "costs" I referred to: > creating a potentially large sequence, > and shuffling it. (Additionally, shuffle > cannot achieve many of the possible > shuffles of a large list, but I doubt this > is easily evaded.) Whether that second issue is a problem or not really depends on what you intend doing with the random objects. But notice that Python uses the Mersenne Twister PRNG, which has a period of 2**19937-1. That's *roughly* equivalent to the number of permutations of a list with 2080 items. If you really care about shuffling large lists, you can chain PRNGs. For instance, you might use shuffle() to generate a random batch of items, then use a completely different PRNG to shuffle the list again. As for the first issue: def random_values(n, valuelist=[True, False]): for _ in range(n): values = valuelist[:] random.shuffle(values) for item in types: yield item Notice that the default objects in the list aren't types, so the name random_types is inappropriate. The user can pass any objects they like, not just a list of types like [int, str]. Note also that this code isn't limited to lists of just two objects. You can pass as many or as few as you like. It also doesn't build a large list, but any regularities in the shuffle algorithm will show up in here. Unless you're doing cryptography, that probably doesn't matter. If you want to avoid shuffle, here's an alternative: def random_values(n, valuelist=[True, False]): N = len(valuelist) for _ in range(N*n): yield valuelist[random.randrange(0, N)] -- Steven D'Aprano From deets at nospam.web.de Thu Feb 15 07:46:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 15 Feb 2007 13:46:20 +0100 Subject: A problem of using pyfort References: <1171508458.876894.17290@s48g2000cws.googlegroups.com> Message-ID: <53j30sF1snp4dU2@mid.uni-berlin.de> > > I didn't find any solutions via internet. So I really > need your help. The OS on my computer is Fedora Core 5. Thanks in > advance. Really? Entering the error-message and fedora core 5 brings this up as first result in google: http://www.bo.infn.it/alice/alice-doc/mll-doc/ali-inst/node40.html So - you certainly need to improve your googling-skillz. Diez From danilo.horta at gmail.com Fri Feb 9 06:11:13 2007 From: danilo.horta at gmail.com (Horta) Date: 9 Feb 2007 03:11:13 -0800 Subject: A little more advanced for loop In-Reply-To: References: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> Message-ID: <1171019473.527988.206610@l53g2000cwa.googlegroups.com> On Feb 9, 9:00 am, Stephan Diehl wrote: > Horta wrote: > > Hi folks, > > > Suppose I have to loop over 3 lists being the same size at the same > > time and order. How can I do that without using the range() function > > or whatever indexing? > > > Example using range: > > > a = ['aaa', 'aaaa'] > > b = ['bb', 'bbbb'] > > c = ['c', 'cccc'] > > > for i in range(len(a)): > > # using a[i], b[i], and c[i] > > > I'm sure there's a elegant way to do that... > > > Thanks in advance. > > Sure, there is: > > for a_item, b_item , c_item in zip(a,b,c): > # do something Thanks guys! From techtonik at gmail.com Sat Feb 10 04:03:40 2007 From: techtonik at gmail.com (techtonik) Date: 10 Feb 2007 01:03:40 -0800 Subject: Need a cross-platform way to execute binary Message-ID: <1171098220.101483.138910@q2g2000cwa.googlegroups.com> Hello, everyb. Does anybody know simple cross-platform method of probing if executable binary is available and launching it. Problem no.1: test if executable file is available I'll take windows platform as the most relevant in this case. os.access() doesn't handle env PATHEXT and can't detect if a given path would be executable or not. Here "executable" means file that could be be launched by system() (if there are any other ways - I'd be happy to know them) Suppose I have "ufo2exe" executable two directories up. >>> os.access("../../ufo2map.exe", os.X_OK) True However... >>> os.access("../../ufo2map", os.X_OK) False But... >>> os.system("..\..\ufo2map") ---- ufo2map 1.0 ---- 0 Problem no.2: launch executable file The same windows platform again. All python commands are using forward slashes for paths, but system doesn't handle this situation (it could at least try to convert immediate forward slashes to backwards) os.access() thinks this file is executable, but os.system() fails ... >>> os.access("../../ufo2map.exe", os.X_OK) True >>> os.system("../../ufo2map.exe") '..' is not recognized as an internal or external command, operable program or batch file. 1 the contrary - access() fails to tell this path can be launched, but file Is executable, ... >>> os.access("..\..\ufo2map", os.X_OK) False >>> os.system("..\..\ufo2map") ---- ufo2map 1.0 ---- 0 Is there any workaround in Python or I have to stick with platforms- specific quirks? I'm using Python 2.4.2 Thanks!. -- --t. From arkanes at gmail.com Fri Feb 2 14:34:35 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 2 Feb 2007 13:34:35 -0600 Subject: Python does not play well with others In-Reply-To: <7xtzy48jg3.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60702021134x65a06edawb2f25e8ced453cfd@mail.gmail.com> On 02 Feb 2007 11:10:04 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Paul Boddie" writes: > > If the hosting provider doesn't want to install MySQLdb then it may > > not be a technical issue - perhaps they just can't be bothered to > > install it, possibly because there's no demand or benefit to the > > bottom line in doing so. > > Why should the hosting provider need to devote attention to something > like that? MySQLdb or something like it should be included with > Python, not added separately by the hosting provider. Python is > really making more demands on hosting providers than comparable > languages do. PHP hosting providers don't have to install a separate > PHP to MySQL interface gizmo as far as I know. > -- How about because thats what you pay them for? Seriously. Do you even think about what you're saying? Python needs to move MySQL (and only MySQL, of course) into the core because installing packages is too much of a burden for hosting companies? Christ. There are a number of languages which are primarily used for "web development". PHP is the *only* one that ships with MySQL client access. Ruby doesn't (only primarily web development because of rails) ASP, either .NET or classic, doesn't. Java (in any form I'm aware of) doesn't. Cold Fusion doesn't. Perl doesn't. Who wants to host at a company that can't install packages anyway? And who wants to be "comparable" to PHP? From newsuser at stacom-software.de Fri Feb 2 13:03:43 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Fri, 02 Feb 2007 19:03:43 +0100 Subject: Build Python 2.5 wit VC6.0 ? Message-ID: Hi everybody, does somebody have experience in building with VC6.0. On my first try there where missing C-Modules. Is that true. VC6.0 is not supported? Thanks a lot. Regards Alexander PC: What Python version supports VC6.0? From rw at smsnet.pl Wed Feb 14 16:53:03 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 14 Feb 2007 22:53:03 +0100 Subject: rot13 in a more Pythonic style? References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: <87bqjwz9s0.fsf@smsnet.pl> "Andy Dingley" writes: > I'm trying to write rot13, but to do it in a better and more Pythonic > style than I'm currrently using. What would you reckon to the > following pretty ugly thing? How would you improve it? In > particular, I don't like the way a three-way selection is done by > nesting two binary selections. Also I dislike stating the same > algorithm twice, but can't see how to parameterise them neatly. It looks to me like a good place to use closure and dictionaries. I would write it this way: def rot(step): import string rot_char = lambda a,c,step=step: chr((((ord(c) - ord(a)) + step) % 26) + ord(a)) make_dict = lambda a,s: dict([(x, rot_char(a, x)) for x in s]) d = make_dict('a', string.ascii_lowercase) d.update(make_dict('A', string.ascii_uppercase)) def f(s): return "".join([d.get(c) or c for c in s]) return f >>> rot13 = rot(13) >>> rot13('Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt') 'Florix Grabundae, Splundig vur thrigg' >>> rot_13 = rot(-13) >>> rot_13('Florix Grabundae, Splundig vur thrigg') 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' -- HTH, Rob From jordan.taylor2 at gmail.com Tue Feb 13 12:55:22 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 13 Feb 2007 09:55:22 -0800 Subject: Download parts not whole file in ones In-Reply-To: <1171389094.849308.170410@k78g2000cwa.googlegroups.com> References: <1171389094.849308.170410@k78g2000cwa.googlegroups.com> Message-ID: <1171389321.712992.252790@m58g2000cwm.googlegroups.com> On Feb 13, 12:51 pm, "Jordan" wrote: > On Feb 13, 8:09 am, NOSPAM plz wrote: > > > > > Hey, > > > My problem is, is it possible to download parts of a file while. i think > > is it is called threading > > > My code thats download the whole webpage, and stunds the app while is is > > downloading: > > > -----------CODE----------- > > import urllib > > # the heavy file to download > > f = urllib.urlopen("http://da.wikipedia.org/wiki/Wiki") > > # This was supposed to print the file while it downloads > > while 1: > > print f.read(100) > > -----------/CODE----------- > > > In my example it just download the whole file, and then print it. > > > Any suggestions? > > > Regards > > Andreas > > That's because urllib.urlopen() is not a low enough level function to > allow what you want, it will simply open the . Take a look inside of > urllib.py and maybe you'll find a way to subclass the urllopen() > function to do what you want. > > Cheers, > Jordan Sorry, my previous msg got mangled. I meant to say that urllib.urlopen() will simply open the webpage, you can't interrupt it to print out what's already been downloaded. From dingbat at codesmiths.com Mon Feb 5 05:52:15 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 5 Feb 2007 02:52:15 -0800 Subject: How can I access data from MS Access? In-Reply-To: <1170517420.026596.74880@s48g2000cws.googlegroups.com> References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> Message-ID: <1170672735.355295.141340@a75g2000cwd.googlegroups.com> On 3 Feb, 15:43, Finger.Octo... at gmail.com wrote: > How to access data from MS Access? Can you access Access from Access ? from Excel / Visual Basic / SQL Query? First of all check that the DSN is working and connects to the back end MDB. This might not be Python's problem. Secondly check whatever errors you're being returned. From aspineux at gmail.com Sat Feb 3 19:11:15 2007 From: aspineux at gmail.com (aspineux) Date: 3 Feb 2007 16:11:15 -0800 Subject: result of os.times() is different with 'time' command In-Reply-To: References: <1170441001.097986.294510@h3g2000cwc.googlegroups.com> <1170446796.156141.201960@v33g2000cwv.googlegroups.com> Message-ID: <1170547875.149037.73030@q2g2000cwa.googlegroups.com> Your analysis looks great, maybe the good arguments to report a bug ? On 3 f?v, 04:27, see at signature.invalid (Douglas Wells) wrote: > [various posting problems corrected and response interspersed in > previous post for purposes of coherent response] > > In article <1170446796.156141.201960 at v33g2000cwv.googlegroups.com>, > > > > "aspineux" writes: > > On 2 Feb, 19:30, kwa... at gmail.com wrote: > > > Hi, > > > > I have a question about os.times(). > > > os.times() returns a tuple containing user time and system time, > > > but it is not matched to the result of 'time' command. > > > For example, os.times() reports that user time is 39.85 sec, > > > but 'time' command reports that user time is 28.55sec. > > > (machine: Python2.5, MacOS X 10.4 Tiger, MacBook 1.83GHz intel core > > > duo) > > > > [ source elided ] > > > I dont see anything wrong ! > > Did you try to measure time with your watch ? > > Did you try a simple python test.py without the time command ? > > Maybe python is 'disturbed' by the intel core > > > can you try this ? > > > # strace python test.py 2>&1 | grep time > > times({tms_utime=1, tms_stime=1, tms_cutime=0, tms_cstime=0}) = > > 430217777 > > times({tms_utime=2238, tms_stime=2, tms_cutime=0, tms_cstime=0}) = 430220049 > > write(1, "n=35, v=14930352\nutime=22.37, st"..., 41n=35, v=14930 52 > > utime=22.37, stime=0.01 > > Note that this likely won't work. First, strace is not native to > OS X; ktrace is the analogous native command. Second, OS X almost > certainly implements the times system call in terms of getrusage. > > > > > > Result: > > > ==================== > > > $ python -V > > > Python 2.5 > > > $ time python ostimetest.py > > > n=35, v=14930352 > > > utime=39.85, stime=0.216666666667 > > > real 0m28.554suser 0m23.938ssys 0m0.177s > > > ==================== > > > > This shows that os.times() reports that user time is 39.85sec, > > > but time command shows that user time is 23.938sec. > > > Why os.times() reports wrong result? Do I have any mistake? > > > > -- > > > kwatch > > Yes, I can reproduce this on my FreeBSD system. No, I do not believe > that you have made a mistake. Yes, I believe that you have uncovered > a bug in the Python os/posix modules. > > Here's my analysis (although I should note that I've not looked > at the source of Python previously). I'm looking at Python 2.4.3, > but this looks like a long existing bug: > > The following code exists in the source code module > Modules/posixmodule.c @ posix_times: > struct tms t; > clock_t c; > [ ... ] > c = times(&t); > [ ... ] > return Py_BuildValue("ddddd", > (double)t.tms_utime / HZ, > (double)t.tms_stime / HZ, > (double)t.tms_cutime / HZ, > (double)t.tms_cstime / HZ, > (double)c / HZ); > This is incorrect. It should not be dividing by HZ, but by the > result of the dynamic value 'sysconf (_SC_CLK_TCK)'. Even if > it were to use a compile time value, the proper value would be > CLK_TCK, not HZ. > > So here's what's happening. Neither my FreeBSD nor the OP's Mac > defines HZ as a compile time variable, but the same source module > also contains the following code: > #ifndef HZ > #define HZ 60 /* Universal constant :-) */ > #endif /* HZ */ > So, the Python posix module is using 60 instead of the proper > value, which happens to be 128 on my FreeBSD, and 100 on the OP's > OS X(*). (BTW, this sort of historic code is exactly why POSIX > no longer defines HZ.) > > In support of this, I note that the following ratios exist: > user time from os.times / user time from time command > 39.85 / 23.938 => 1.665 > CLK_TCK / HZ > 100 / 60 => 1.667 > which are in reasonably close agreement! > > - dmw > > [*] I've actually only looked at OS X for the PPC platform, not > for the User's Intel platform, but I'm fairly certain that the > CLK_TCK value is the same on both. > > -- > . Douglas Wells . Connection Technologies . > . Internet: -sp9804- -at - contek.com- . From tiarno at sas.com Fri Feb 23 12:17:46 2007 From: tiarno at sas.com (Tim Arnold) Date: Fri, 23 Feb 2007 12:17:46 -0500 Subject: Finding non ascii characters in a set of files References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: "Peter Bengtsson" wrote in message news:1172243566.906121.189930 at h3g2000cwc.googlegroups.com... > On Feb 23, 2:38 pm, b... at yahoo.com wrote: >> Hi, >> >> I'm updating my program to Python 2.5, but I keep running into >> encoding problems. I have no ecodings defined at the start of any of >> my scripts. What I'd like to do is scan a directory and list all the >> files in it that contain a non ascii character. How would I go about >> doing this? >> > > How about something like this: > content = open('file.py').read() > try: > content.encode('ascii') > except UnicodeDecodeError: > print "file.py contains non-ascii characters" > Here's what I do (I need to know the line number). import os,sys,codecs def checkfile(filename): f = codecs.open(filename,encoding='ascii') lines = open(filename).readlines() print 'Total lines: %d' % len(lines) for i in range(0,len(lines)): try: l = f.readline() except: num = i+1 print 'problem: line %d' % num f.close() From gagsl-py at yahoo.com.ar Mon Feb 19 20:05:04 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 22:05:04 -0300 Subject: Getting a class name References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> <1171818881.871094.295870@v33g2000cwv.googlegroups.com> <45d8df9d$0$28886$426a74cc@news.free.fr> <1171843008.635203.50290@v45g2000cwv.googlegroups.com> <1171916756.796893.133000@v45g2000cwv.googlegroups.com> Message-ID: En Mon, 19 Feb 2007 17:25:56 -0300, Fuzzyman escribi?: > On Feb 19, 5:11 am, "Gabriel Genellina" wrote: >> En Sun, 18 Feb 2007 20:56:48 -0300, Fuzzyman >> escribi?: >> > [somebody] wrote: >> >> >>> > def getCodeName(deap=0): >> >> >>> > return sys._getframe(deap+1).f_code.co_name >> >> >> This might be useful to avoid metaclass hacks when trying to >> initialize >> >> a class attribute that would require the class name. (my 2 cents) >> >> > It's still an ugly hack. :-) >> > (But a nice implementation detail to know about none-the-less.) >> >> Having class decorators would be nice... > > Yes - and Guido said he wouldn't be opposed to the idea when it was > poitned out that they would be very useful for both IronPython and > Jython to implement features of their underlying platforms. > > I haven't heard anyone (other than you) mention them recently > though... Maybe it's a sign that actually nobody cares about class decorators :( -- Gabriel Genellina From attn.steven.kuo at gmail.com Wed Feb 28 16:33:56 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 28 Feb 2007 13:33:56 -0800 Subject: Extract String From Enclosing Tuple In-Reply-To: References: Message-ID: <1172698436.159985.30360@p10g2000cwp.googlegroups.com> On Feb 28, 12:40 pm, rshep... at nospam.appl-ecosys.com wrote: > I'm a bit embarrassed to have to ask for help on this, but I'm not finding > the solution in the docs I have here. > > Data are assembled for writing to a database table. A representative tuple > looks like this: > > ('eco', "(u'Roads',)", 0.073969887301348305) > > Pysqlite doesn't like the format of the middle term: > pysqlite2.dbapi2.InterfaceError: Error binding parameter 1 - probably > unsupported type. > > I want to extract the 'Roads', part from the double-quoted enclosing > tuple. (snipped) Perhaps something like: >>> t = ('eco', "(u'Roads',)", 0.073969887301348305) >>> t2 = eval(t[1], { '__builtins__' : {} }, {} ) >>> t2 (u'Roads',) >>> t2[0].encode('ascii') 'Roads' >>> import itertools >>> tuple(itertools.chain((t[0], t2[0].encode('ascii')), t[2:])) ('eco', 'Roads', 0.073969887301348305) >>> tuple(itertools.chain((t[0], (t2[0].encode('ascii'),)), t[2:])) ('eco', ('Roads',), 0.073969887301348305) -- Hope this helps, Steven From skip at pobox.com Sat Feb 10 08:13:25 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 10 Feb 2007 07:13:25 -0600 Subject: pygame and python 2.5 In-Reply-To: <1171057226.754537.262220@h3g2000cwc.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171052486.043598.239470@p10g2000cwp.googlegroups.com> <1171057226.754537.262220@h3g2000cwc.googlegroups.com> Message-ID: <17869.50421.121717.396393@montanaro.dyndns.org> >> Python used to work that way. You'd then silently get errors if the >> API changed between version A and version B and you neglected to >> recompile the extensions you compiled against version A. bearophile> Can't the compiled module have one or more test functions bearophile> that can be used during linking to see if the compiled bearophile> module respects the expected standard? Given the complexity of the formal API how would you test to see if the extension violated a particular aspect of the API? What if one of the API bits used is implemented as a C macro (as parts are) and it was changed simply to fix a bug. Wouldn't you want to know with a high degree of certainty that you should recompile? How would a test function tell you that? A simple API versioning scheme does that. It means you have to recompile when a new version of Python comes out. In fact, you can think of it as the test function you suggest. It's just that it's noted at the time a module is imported, not strictly speaking at link time. It tells you, "Hey buddy. You're using an outdated version of the API." What it can't tell you is if the parts of the API your particular module uses are used incorrectly. Skip From gagsl-py at yahoo.com.ar Thu Feb 15 20:03:04 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 22:03:04 -0300 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded References: <1171305876.030471.59470@s48g2000cws.googlegroups.com> <1171564971.279097.151370@p10g2000cwp.googlegroups.com> <1171571229.141330.250700@m58g2000cwm.googlegroups.com> <1171586996.509170.162020@a34g2000cwb.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 21:49:56 -0300, escribi?: > After installing activestate python 2.4 and ctypes-1.0.1.win32- > py2.4.exe, everything just worked. So, I decided to stay with 2.4 > since I don't have time to figure out the problem. Glad to see it worked, at least on 2.4 -- Gabriel Genellina From kwatch at gmail.com Sun Feb 4 15:34:41 2007 From: kwatch at gmail.com (kwatch at gmail.com) Date: 4 Feb 2007 12:34:41 -0800 Subject: pyYaml community In-Reply-To: <45c45d6f$0$5815$426a34cc@news.free.fr> References: <45c45d6f$0$5815$426a34cc@news.free.fr> Message-ID: <1170621280.949974.155830@v33g2000cwv.googlegroups.com> you should subscribe yaml-core mailing list. mailto:yaml-core at lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/yaml-core this is what you want. -- kwatch Imbaud Pierre wrote: > I began using pyYaml. > I found no place where pyYaml users exchange ideas, know-how, etc > (as here for python). > There is a wiki, a bug tracker, documentation, but such a place > (mailing list, newsgroup, forum, or even IRC) is a must (IMHO) to smooth > the learning curve. > Does someone know better? > > My concern: yaml allows "complex data" as keys to dicts. > I need tuples as keys, pyYaml turns my yaml sequences into lists, > and then yells list cant be used as keys. No way to turn my yaml > sequences into tuples? > Oh, I found! RTFM, as usual! > (the first question sticks) From S.Mientki-nospam at mailbox.kun.nl Mon Feb 12 12:48:06 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 12 Feb 2007 18:48:06 +0100 Subject: Newbie Question In-Reply-To: References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> Message-ID: Ed Leafe wrote: > On Feb 12, 2007, at 9:59 AM, Stef Mientki wrote: > >> but to be honest ... >> ... I never even tried to write a GUI in Python, ... >> ... just looked at others examples, >> ... and still not seen what I can perform in Delphi ;-) > > You should definitely look at our product: Dabo. Both myself and my > partner come from a desktop application background in which GUI tools > made it easy to focus on what the app was doing instead of worrying > about if it would look like you think it will look when writing the UI > in code. > > Dabo is still a work in progress; we have most of the individual > tools working well, and are just beginning to put them all together in a > full IDE. > > Take a look at our screencasts to see Dabo in action; I'd recommend > the more recent ones, as they show the current state of the tools: > > Building a Database Application using the Dabo Class Designer (Parts 1 & 2) > http://leafe.com/screencasts/dataenvironment1.html > http://leafe.com/screencasts/dataenvironment2.html > > Populating a Grid Using Business Objects > http://leafe.com/screencasts/populategrid.html > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com > > looks very good, I'll certainly investigate that further in the near future. For the moment I'm just interested in signal analysis, and as I want to "be finished tomorrow", I'll keep myself to Delphi. thanks & cheers, Stef Mientki From bearophileHUGS at lycos.com Wed Feb 28 02:25:05 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Feb 2007 23:25:05 -0800 Subject: Yet another unique() function... In-Reply-To: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> Message-ID: <1172647505.784091.193710@q2g2000cwa.googlegroups.com> MonkeeSage: > Here's yet another take on a unique() function for sequences. It's > more terse than others I've seen and works for all the common use > cases (please report any errors on the recipe page): It's more terse, but my version is built to be faster in the more common cases of all hashable or/and all sortable items (while working in other cases too). Try your unique on an unicode string, that's probably a bug (keepstr is being ignored). Version by Paul Rubin is very short, but rather unreadable too. Bye, bearophile From skip at pobox.com Thu Feb 1 15:37:01 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Feb 2007 14:37:01 -0600 Subject: Newbie question: replacing nulls in CSV with preceding value In-Reply-To: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> References: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> Message-ID: <17858.20333.457320.332756@montanaro.dyndns.org> Matt> I have a CSV file, exported from Excel, that has blank records in Matt> it, and I need to fill them in with the values from the record Matt> just above it until it hits a non-blank value. Try something like: #!/usr/bin/env python import sys import csv last = {} reader = csv.DictReader(open("test1.csv", "rb")) writer = csv.DictWriter(open("test2.csv", "wb"), sys.stdout, fieldnames="Zone City Event".split()) for row in reader: for key in row: if not row[key]: row[key] = last.get(key, "") writer.writerow(row) last = row Skip From rory at campbell-lange.net Thu Feb 22 05:31:51 2007 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Thu, 22 Feb 2007 10:31:51 +0000 Subject: Local class variables? (mod_python problem) Message-ID: <20070222103151.GA12437@campbell-lange.net> We have a set of classes using static methods to retain reference variables between operations. The problem is that the static variables are not reset between operations when used through mod_python. Although it is possible to reset the class variables between invocations of the system, this has the potential of 'wiping out' these variables when another user is using the system. Is there a way of getting the equivalent of 'local class variables'? In other words, a way of making 'print a' and 'print b' below provide the same output? Regards Rory class TryMe(object): x = 0 y = 0 def __init__(self): self.a = 0, self.b = 0 @staticmethod def incrementer(): TryMe.x += 1, TryMe.y += 1 def addone (self): TryMe.x += 1, TryMe.y += 1 self.a , += 1 self.b += 1 def __repr__(self): return """ TryMe.x = %d TryMe.y = %d self.a = %d self.b = %d """ % (TryMe.x, TryMe.y, self.a, self.b) if __name__ == '__main__': a = TryMe() a.incrementer() a.addone() b = TryMe() b.incrementer() b.addone() print 'a:', a print 'b:', b -- Rory Campbell-Lange From rzantow at gmail.com Fri Feb 2 07:38:43 2007 From: rzantow at gmail.com (rzed) Date: Fri, 02 Feb 2007 07:38:43 -0500 Subject: How do I print out in the standard output coloured lines References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> <1170419225.989358.311600@h3g2000cwc.googlegroups.com> Message-ID: cniharral at gmail.com wrote in news:1170419225.989358.311600 at h3g2000cwc.googlegroups.com: > On Feb 2, 1:16 pm, rzed wrote: >> cnihar... at gmail.com wrote >> innews:1170417631.268771.108090 at v45g2000cwv.googlegroups.com: >> >> > Hi, >> >> > I'm interested in printing out coloured lines of my >> > application and >> > I don't know what to use. Can anybody give me an idea?? >> >> You could speed up the process if you explain what your >> application is and what you mean by colored lines. Does your >> application emit output to a plotter, an ink-jet printer, or a >> color laser printer? Is it a drawing program? An editor in >> which you want lines colored to highlight context? It might be >> useful to know what system you are running as well. Just a >> little detail here. >> >> -- >> rzed > > Well, yes, it's a program that prints out lines to the standard > output with a print command, and I want to print them coloured. > For example: > > print "Hello World!!" > > I want it in red colour. > > That's all. > > If you're on Linux, you could use the curses module. There may be a precompiled Windows version compatible with your Python version, or maybe not, but the Windows source is available, and you may be able to get it to work with your Python with some effort. Linux distros include curses, I think. For Windows curses, take a look at . You will understand why the phrase "Windows curses" is used, I expect. -- rzed From bdesth.quelquechose at free.quelquepart.fr Sun Feb 25 16:12:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 25 Feb 2007 22:12:52 +0100 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: <45e1f41d$0$25582$426a74cc@news.free.fr> Steven W. Orr a ?crit : > I understand that two leading underscores in a class attribute make the > attribute private. Nope. It doesn't make it "private", it mangles the attribute name with the class name (ie : Bar.__mangled will become Bar._Bar__mangled everywhere except inside Bar). This is only useful when you want to make sure an attribute will not be *accidentally* accessed by a child class. FWIW, I've found it of very limited use so far... > But I often see things that are coded up with one > underscore. Unless I'm missing something, there's a idiom going on here. Yes. Single leading underscore means "this is implementation, don't mess with it or your on your own". It's the equivalent of "private". From maric at aristote.info Wed Feb 14 01:33:14 2007 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Feb 2007 07:33:14 +0100 Subject: threading and multicores, pros and cons In-Reply-To: <7xodnx2vir.fsf@ruckus.brouhaha.com> References: <7xodnx2vir.fsf@ruckus.brouhaha.com> Message-ID: <200702140733.15720.maric@aristote.info> Le mercredi 14 f?vrier 2007 05:49, Paul Rubin a ?crit?: > Basically Python applications are usually not too CPU-intensive; there > are some ways you can get parallelism with reasonable extra effort; Basically, while not CPU intensive, application server needs to get benefit of all resources of the hardware. When a customer comes with his new beautiful dual-core server and get a basic plone install up and running, he will immediately compare it to J2EE and wonder why he should pay a consultant to make it work properly. At this time, it 's not easy to explain him that python is not flawed compared to Java, and that he will not regret his choice in the future. First impression may be decisive. The historical explanation should be inefficient here, I'm afraid. What about the argument that said that multi threading is not so good for parallelism ? Is it strong enough ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 Mobile: +33 632 77 00 21 From mail at timgolden.me.uk Thu Feb 15 05:11:01 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 15 Feb 2007 10:11:01 +0000 Subject: how do "real" python programmers work? In-Reply-To: <0EC8A68FD54CDD4FB6B92EE7B713ED3601331455@SAN-THC-NODE02.lbcamden.net> References: <0EC8A68FD54CDD4FB6B92EE7B713ED3601331455@SAN-THC-NODE02.lbcamden.net> Message-ID: <45D431B5.3080107@timgolden.me.uk> Tyrrell, Wendy wrote: (Well, nothing) Was that all your question, Wendy, or did you accidentally hit the Send button too soon? You're welcome to ask here or on the tutor list http://mail.python.org/mailman/listinfo/tutor if you want to find out about Python. Or just look at the website: http://python.org Your organisation seems to deal with partnerships between business and education; are you looking to promote the use of programming in schools? Or is there something else you're after? (I'm above-averagely curious because I work in Camden and I'm involved in Youth work in Ealing). Tim Golden From g.brandl at gmx.net Wed Feb 14 16:18:48 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Wed, 14 Feb 2007 22:18:48 +0100 Subject: ANN: Pygments 0.7 "Faschingskrapfn" released Message-ID: <45D37CB8.9020003@gmx.net> I'm very pleased to announce the third public release of Pygments, the generic Python syntax highlighter. Download it from , or look at the demonstration at . News ---- The new features since 0.6 include: * New lexers for * OCaml * Dylan * Java Server Pages * Windows batch files * Trac Wiki markup * Python tracebacks * ReStructuredText * sources.list * Mako templates * and the Befunge esoteric programming language (yay!) * Token stream filters, which can e.g. highlight certain names or code tags. * An HTML formatter that is easily subclassable. * An option to control the command prefix for the LaTeX formatter. * A MoinMoin parser plugin to easily get Pygments highlighting in Moin. * ... and many little changes and fixes that are listed in the detailed changelog. About ----- Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a wide range of common languages and markup formats is supported * special attention is paid to details increasing quality by a fair amount * support for new languages and formats are added easily * a number of output formats is available, presently HTML, LaTeX, RTF and ANSI sequences * it is usable as a command-line tool and as a library * ... and it highlights even Brainf*ck! The home page is at . Read more in the FAQ list or look at the documentation . regards and happy Valentine's day, Georg From mituller at gmail.com Sat Feb 10 18:03:36 2007 From: mituller at gmail.com (mtuller) Date: 10 Feb 2007 15:03:36 -0800 Subject: Parsing HTML Message-ID: <1171148616.780656.13230@m58g2000cwm.googlegroups.com> Alright. I have tried everything I can find, but am not getting anywhere. I have a web page that has data like this: LETTER 33,699 1.0 What is show is only a small section. I want to extract the 33,699 (which is dynamic) and set the value to a variable so that I can insert it into a database. I have tried parsing the html with pyparsing, and the examples will get it to print all instances with span, of which there are a hundred or so when I use: for srvrtokens in printCount.searchString(printerListHTML): print srvrtokens If I set the last line to srvtokens[3] I get the values, but I don't know grab a single line and then set that as a variable. I have also tried Beautiful Soup, but had trouble understanding the documentation, and HTMLParser doesn't seem to do what I want. Can someone point me to a tutorial or give me some pointers on how to parse html where there are multiple lines with the same tags and then be able to go to a certain line and grab a value and set a variable's value to that? Thanks, Mike From gherron at digipen.edu Sat Feb 17 13:57:08 2007 From: gherron at digipen.edu (Gary Herron) Date: Sat, 17 Feb 2007 10:57:08 -0800 Subject: Importing from upper directory In-Reply-To: <1171734956.679327.9550@a75g2000cwd.googlegroups.com> References: <1171734956.679327.9550@a75g2000cwd.googlegroups.com> Message-ID: <45D75004.8000404@digipen.edu> Harlin Seritt wrote: > I have a script that I want to import called upper.py. It is 2 > directories above the script that will call it - i'll call that one > main.py. How am I able to import a script in a directory that is above > it? > > Thanks, > > Harlin > You can control the directories from which Python imports by modifying the sys.path attribute. Something like this: import sys sys.path.append("../..") #That's two directories up from the current directory import upper If you're unsure what the current working directory is, try: import os print os.getcwd() # The current working directory If it's not the current directory, but rather the directory containing the original script you want, then import sys, os path = sys.argv[0] #Initial script name path0 = os.path.split(path)[0] #Initial script path path1 = os.path.split(path0)[0] # Up one path2 = os.path.split(path1)[0] # Up two sys.append(path2) Gary Herron From franz.steinhaeusler at gmx.at Tue Feb 27 01:44:53 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 27 Feb 2007 07:44:53 +0100 Subject: wxPython - 2 x foldpanelbar with tree... References: <1172501410.183507.4300@p10g2000cwp.googlegroups.com> Message-ID: On 26 Feb 2007 06:50:11 -0800, "w.p." wrote: >Hello! >I have some trouble with my GUI. I have left panel with foldpanelbar, >but i need one item but not collapsed - simple button. I split my left >panel into two foldpanelbars with one button between. >But a have trouble... >Sorry for english :/ > > Sorry, no answer. Only the chance is much bigger you get one asking in the wxpython mailing list. From jeff.templon at gmail.com Tue Feb 20 15:44:53 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 12:44:53 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> Message-ID: <1172004293.184392.277510@h3g2000cwc.googlegroups.com> Hi, On Feb 20, 8:59 pm, Steven Bethard wrote: > You snipped the rest of that comment: > > "It's not even clear yet that your average 2.6 code will work on 3.0 -- > though there's a pretty large contingent trying to make this true." Thanks for pointing this out. I voted for the comp.lang.python newsgroup back in the early 90's, my active days of python 'development' are over, it's all i can do to hang on to the code i've been posting about. > have 2.6/3.0 compatible code) by late 2011. Sure, it's a long way off, > but you're writing 2.2 compatible code *now*. Is it really that bad to > wait four years for Python 3.0? As long as when python 3.0 shows up, i don't have to do a massive rewrite. I think I've really only had to change two or three things over the years .. one was that I used to use words like "dict" and "list" in my code, which broke in subtle ways when d = dict() became legal. I just dug out some code laying around on disk from 1994, and ran it, unchanged, under python 2.3.5. If I can achieve this (running 2007 code under python3.0 in 2011 with no modifications), that'd be OK. JT From cjw at sympatico.ca Wed Feb 21 19:02:17 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 21 Feb 2007 19:02:17 -0500 Subject: Convert to binary and convert back to strings In-Reply-To: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <45DCDD89.70609@sympatico.ca> Harlin Seritt wrote: > Hi... > > I would like to take a string like 'supercalifragilisticexpialidocius' > and write it to a file in binary forms -- this way a user cannot read > the string in case they were try to open in something like ascii text > editor. I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is there any > way to do this in Python? > > Thanks! > > Harlin > Try opening your file in the 'wb' mode. Colin W. From silverburgh.meryl at gmail.com Sat Feb 10 15:29:52 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 10 Feb 2007 12:29:52 -0800 Subject: Question about strftime Message-ID: <1171139392.261505.9350@l53g2000cwa.googlegroups.com> Hi, I have question about strftime. I am trying to print the current time in this format: date = strftime("%Y%m%d_%H%M%S", gmtime()) print date I run the script at 2:18 pm, but I get this: 20070210_201837 Can you please tell me why I get '20'? instead of '14' (which is 2:00 pm)? Thank you. From MonkeeSage at gmail.com Tue Feb 27 22:03:45 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 27 Feb 2007 19:03:45 -0800 Subject: Yet another unique() function... In-Reply-To: <7xzm6z6lf4.fsf@ruckus.brouhaha.com> References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <7x8xej80a5.fsf@ruckus.brouhaha.com> <7xzm6z6lf4.fsf@ruckus.brouhaha.com> Message-ID: <1172631825.777298.257980@j27g2000cwj.googlegroups.com> On Feb 27, 8:55 pm, Paul Rubin wrote: > Paul Rubin writes: > > def unique(seq, keepstr=True): > > t = type(seq) > > if t==str: > > t = (list, ''.join)[bool(keepstr)] > > seen = [] > > return t(c for c in seq if (c not in seen, seen.append(c))[0]) > > Preferable: > > def unique(seq, keepstr=True): > t = type(seq) > if t==str: > t = (list, ''.join)[bool(keepstr)] > seen = [] > return t(c for c in seq if not (c in seen or seen.append(c))) Wow, nice! Very cool. :) Regards, Jordan From skip at pobox.com Thu Feb 1 11:00:50 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Feb 2007 10:00:50 -0600 Subject: Problem saving changes in MoinMoin pages In-Reply-To: <1cu3s21tl6lml00k991g20358mjh6m733r@4ax.com> References: <1cu3s21tl6lml00k991g20358mjh6m733r@4ax.com> Message-ID: <17858.3762.274704.113040@montanaro.dyndns.org> Dan> When I edit a page and click 'Save', the next page that displays is Dan> an 'HTTP 500' error. I have to refresh the page to see the changes. ... Dan> I'm currently perusing the source code to see if I can figure it Dan> out, but any pre-help will be gladly accepted. You might check your web server error log for Python traceback or error info. Skip From larry.bates at websafe.com Thu Feb 1 18:13:29 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Feb 2007 17:13:29 -0600 Subject: python executing windows exe In-Reply-To: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> References: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> Message-ID: <45C27419.6060204@websafe.com> Kiran wrote: > Hi everybody, > I am making python run an executable using the os module. Here is > my question. The executable, once it is running, asks the user to > input a filename that it will process. Now, my question is how do i > automate this. let me make this clear, it is not an argument you pass > in when you type in the exe. An example below illustrates: > > THIS IS NOT WHAT YOU DO: > nec2d.exe couple1.nec # couple1.nec is the > file you want to prcess > > rather, what you do is in windows cmd: > > nec2d.exe > **** PROGRAM PRINTS OUT STUFF***** > **** PROGRAM PRINTS OUT STUFF***** > **** PROGRAM PRINTS OUT STUFF***** > **** PROGRAM PRINTS OUT STUFF***** > Please enter input file: <--------- THIS IS WHERE THE USER IS ASKED > TO TYPE IN THE FILENAME > > everybody thanks for your help > -- Kiran > Not exactly a Python question, but here goes. Normally I do this by piping the response into the executable. Something like: nec2d.exe Message-ID: On 2007-02-15, Gabriel Genellina wrote: > En Wed, 14 Feb 2007 10:41:53 -0300, Neil Cerutti > escribi?: >> So the effect is that mutual recursion isn't actually any >> harder. > > But some kind of language support is required in this case. At > least I don't know how to handle mutual recursion (apart from > inlining one function inside the other...). But I'm certainly > not a "program transformation guru" (neither a novice!) so I > would not be surprised if someone says it can be done... What happens (using the model of an imaginary virtual machine, perhaps like the Python interpreter) is the following. A normal function call pushes a call-frame onto a stack. The call-frame contains information necessary for returning from the function, and usually a place to store its local variables and parameters. A function called in "tail" position simply overwrites the current call-frame with the new one instead of pushing it onto the stack. -- Neil Cerutti The church will host an evening of fine dining, superb entertainment, and gracious hostility. --Church Bulletin Blooper From kooch54 at gmail.com Fri Feb 16 15:17:37 2007 From: kooch54 at gmail.com (Kooch54) Date: 16 Feb 2007 12:17:37 -0800 Subject: Group Membership in Active Directory Query In-Reply-To: <1170942292.620399.102000@m58g2000cwm.googlegroups.com> References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> <1170859017.416570.247920@v33g2000cwv.googlegroups.com> <1170872824.710879.272830@v45g2000cwv.googlegroups.com> <1170895960.022698.299500@h3g2000cwc.googlegroups.com> <1170942292.620399.102000@m58g2000cwm.googlegroups.com> Message-ID: <1171657057.416791.108970@v33g2000cwv.googlegroups.com> On Feb 8, 8:44 am, "Kooch54" wrote: > On Feb 7, 7:52 pm, "alex23" wrote: > > > > > On Feb 8, 4:27 am, kooc... at gmail.com wrote: > > > > First and foremost thanks for the feedback. Although I don't > > > appreciate the slight dig at me. > > > dummy = ldap_obj.simple_bind...... > > > I _really_ don't think Uwe was intending any slight, 'dummy' generally > > means 'dummy variable' ie it's just there to catch the value but it's > > never used after that :) > > > If you're doing a lot of AD work, I highly recommend Tim Golden's > > active_directory module:http://timgolden.me.uk/python/ > > active_directory.html > > > His WMI module has also been a godsend on a number of occasions. > > > - alex23 > > Alex- > Thanks for your response and Uwe I apologize if I misunderstood > and misinterpreted your comments. I am sorry. > I have tried Tim's module called active_directory and it works really > well. But I can't figure out how to connect to a specific group is I > know the common name for it but not the DN and then return it's > members. Example.... I know the group name is domain1\sharedaccess. > How do I bind to that group and get the members. The domain isn't > necessarily the defaultnamingcontext. It could be another domain in > the forest. I need to be able to connect to any domain group and get > it's members. Thanks again. Bump From metaperl at gmail.com Tue Feb 6 09:58:44 2007 From: metaperl at gmail.com (metaperl) Date: 6 Feb 2007 06:58:44 -0800 Subject: "flushing"/demanding generator contents - implications for injection of control In-Reply-To: References: <1170704863.646629.156310@h3g2000cwc.googlegroups.com> Message-ID: <1170773924.417252.149140@s48g2000cws.googlegroups.com> On Feb 5, 3:08 pm, Jussi Salmela wrote: > metaperl kirjoitti: > > > For this program: > > > def reverse(data): > > for index in range(len(data)-1, -1, -1): > > yield data[index] > > > r = reverse("golf") > > > for char in r: > > print char > > > I'm wondering if the line: > > > r = reverse("golf") > > > "demands" the contents of the function reverse() all at once and if I > > must write > > > for char in reverse("golf"): > > print char > > > if I want the results streamed instead of generated complely. > > > ** CONTEXT ** > > > The simple example above is not what I am really doing. My real > > program parses very large > > data files using pyparsing. Pyparsing can generate incremental/yielded > > results with no problem: > > >http://pyparsing.wikispaces.com/message/view/home/248539#248852 > > > but because I believe in injection of control (pushing data around as > > opposed to having > > the target pull it), I get the parse and then inject it into the > > generator: > > > parse = parsing.parse(fp.read()) > > txt = textgen.generate(self.storage.output, patent_key, > > parse, f.basename(), debug=False) > > I don't know, I'm guessing: > > ... r = reverse("golf") > ... type(r) > very slick! thanks! > ... print r.next() > f > > So r is not the string 'flog', it is the generator producing it > > HTH, It does! > Jussi From horpner at yahoo.com Wed Feb 14 18:44:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 14 Feb 2007 23:44:53 GMT Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: On 2007-02-14, Aahz wrote: > In article <1171303251.796306.79520 at p10g2000cwp.googlegroups.com>, > Thomas Nelson wrote: >>I realize I'm approaching this backwards from the direction >>most people go, but does anyone know of a good c/c++ >>introduction for python programmers? > > This isn't an introduction, but you should probably also pick > up _Effective C++_ (and possibly _More Effective C++_, though > that seems less useful to me). I did enjoy _Effective C++_ very much, but in fact there's nothing in there that's not already stated in _The C++ Programming Language_. Granted, TCPL is so dense that it wasn't until *after* reading _Effective C++_ (Scott Meyers), that I noticed this. -- Neil Cerutti From boyandin at gmail.com Thu Feb 8 03:21:38 2007 From: boyandin at gmail.com (Sagari) Date: 8 Feb 2007 00:21:38 -0800 Subject: Referencing vars, methods and classes by name In-Reply-To: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> Message-ID: <1170922898.358949.194340@h3g2000cwc.googlegroups.com> Quite forgot to add the obvious example (in PHP): $a = 'b'; $obj =& new $a(); // instantiating class b() From toreriks at hotmail.com Fri Feb 9 06:06:24 2007 From: toreriks at hotmail.com (Tor Erik Soenvisen) Date: Fri, 9 Feb 2007 11:06:24 +0000 (UTC) Subject: python shelve on win vs unix Message-ID: Hi, Have a problem using shelve on windows and unix. While my windows box supports dbhash, my unix box supports gdbm, and neither supports what the other does. The problem arises when I try to use the shelve generated in unix on my windows box. Hoepfully there are alternatives to installing the berkeley db (needed by dbhash) on unix, which I'm looking at now. I'm no unix guru and would probably use "forever" to get it up and running. Any suggestions for a quick and dirty solution (such as alternatives to shelve for persistent storage) to this problem would be appreciated. regards, Tor Erik From hg at nospam.org Thu Feb 22 12:37:47 2007 From: hg at nospam.org (hg) Date: Thu, 22 Feb 2007 18:37:47 +0100 Subject: How to covert ASCII to integer in Python? References: <1172189757.487956.192130@l53g2000cwa.googlegroups.com> Message-ID: <8HqDh.318731$qy.207168@newsfe16.lga> Some people spend many buck bying guessing games ... be nice ! hg From gosinn at gmail.com Wed Feb 7 10:25:35 2007 From: gosinn at gmail.com (Gosi) Date: 7 Feb 2007 07:25:35 -0800 Subject: Calling J from Python In-Reply-To: <1170796103.766866.18320@a34g2000cwb.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> <1170796103.766866.18320@a34g2000cwb.googlegroups.com> Message-ID: <1170861935.779969.52980@v33g2000cwv.googlegroups.com> On Feb 6, 9:08 pm, bearophileH... at lycos.com wrote: > Gosi: > > > There are a number of graphics examples, utilities and demos you can > > use in J and combine it with Python. > > Some of those graphic examples are very nice, I have seen a big site > filled with complex fractals, chaotic attractors, etc. > Python Zen seems somewhat opposed to part of the J spirit, that's why > it's not easy to advertise J in this newsgroup. Python is open source, > and it values readability, it belives that it's better to write more > and be more readable/debuggable, than to be able to express many > things with few symbols. APL was an interesting language, powerful > too, and J looks more keyboard-friendly and it's probably better for > other things too. K seems even less readable than J to me. Probably J > has to be compared more to scipy than to Python itself, because they > share some purposes, the vector/matrix processing. If you need to do > lot of array processing the syntax of scipy (with the help of > MatPlotLib too, that's partially copied from MatLab) isn't (may be > not) high-level enough, the system isn't able to simplify things by > itself, etc. So in that situation a more functional language may be > fitter (maybe even F#, but probably there are better languages around > for that purpose, some modern ones coming from ML family). > > Bye, > bearophile Ken Iverson created APL and it ran first time on a computer 1966. Ken Iverson then corrected several things and made it so different that he could no longer use the name and the results was J around 1990. J can be very short and effective. I like to use J for many things and I think that combining Python and J is a hell of a good mixture. From pierre.imbaud at laposte.net Sat Feb 3 05:01:19 2007 From: pierre.imbaud at laposte.net (Imbaud Pierre) Date: Sat, 03 Feb 2007 11:01:19 +0100 Subject: pyYaml community Message-ID: <45c45d6f$0$5815$426a34cc@news.free.fr> I began using pyYaml. I found no place where pyYaml users exchange ideas, know-how, etc (as here for python). There is a wiki, a bug tracker, documentation, but such a place (mailing list, newsgroup, forum, or even IRC) is a must (IMHO) to smooth the learning curve. Does someone know better? My concern: yaml allows "complex data" as keys to dicts. I need tuples as keys, pyYaml turns my yaml sequences into lists, and then yells list cant be used as keys. No way to turn my yaml sequences into tuples? Oh, I found! RTFM, as usual! (the first question sticks) From pDOTpagel at gsf.de Fri Feb 23 06:43:24 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Fri, 23 Feb 2007 11:43:24 +0000 (UTC) Subject: CSV(???) References: Message-ID: David C. Ullrich wrote: > Is there a csvlib out there somewhere? How about csv in the standard library? > (Um: Believe it or not I'm _still_ using > python 1.5.7. I have no idea if csv was part of the standard library backin those days... But even if not: either upgrade to something less outdated or see if you can get todays csv to work with the oldtimer. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From mensanator at aol.com Tue Feb 13 21:19:36 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Feb 2007 18:19:36 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> <1171213686.383076.280390@j27g2000cwj.googlegroups.com> Message-ID: <1171419576.565394.253240@a34g2000cwb.googlegroups.com> On Feb 13, 2:24 am, Steve Holden wrote: > mensana... at aol.com wrote: > > On Feb 11, 4:24 am, Steve Holden wrote: > >> mensana... at aol.com wrote: > >>> On Feb 11, 1:35?am, Steve Holden wrote: > [...] > > >>> By the way, on the sci.math newsgroup I promote > >>> Python every chance I get. One fellow thanked me > >>> profusely for recommending Python & GMPY and asked > >>> for some help with a program he was having problems > >>> with. We worked it out fine but his problem made me > >>> suspect there may be more bugs in GMPY. What's my > >>> motivation for tracking them down? > >> The satisfaction of a job well done? What's my motivation for acting as > >> a director of the Python Software Foundation when I get accusations of > >> irresponsibility? > > > I apologize. But I hope you see how this appears from > > the outside, that the PSF doesn't give a rat's ass about > > Windows users with AOL addresses. Sure, that's wrong, > > but calling people who bring up these points whiny leeches > > doesn't do anything to dispell that notion. > > The AOL address is nothing to do with it. Did you read the reply from Steven D'Arpano? He seems to think it has something to do with it. > Accusations of whiny leeching > tend to be made at people whose attitudes aren't constructive That's why I brought up the gmpy incident, to show that I don't have such an attitude. I even said I would pay for a compiler if that's what it took, which is more than what some open source developers are willing to do (and I don't blame them). > and who > express their complaints in ways that seem to imply an expectation of > some kind of right to dictate to open source developers. I never meant to dictate what open source developers should do. But do they care about the implications of what they do? Remember, I got onto this thread replying to say that when an open source developer doesn't think past his own computer, then that's not the altruistic behaviour that others claim is the hallmark of open source. Sure, it rubs people the wrong way when I not so politely ask them to please look at the beam in their own eye before complaining about the mote in their neighbor's eye. > > >> Anyway, thanks for taking the time to help maintain gmpy. > > > Thanks, I try to help as much as I can. I'm a little > > sensitive about gmpy because without it, I would have > > to abandon Python and I don't want to abandon Python. > > >> This thread is starting to make me think that there's a case to be made > >> for somehow providing supported build facilities for third-party > >> extension modules. > > > And the untouchables would greatly appreciate it. > > We're all Python users. That's what I was hoping to hear. > There are no untouchables. I'll ignore Steven D'Arpano's prattle. > But in the open > source world you tend to have to take ownership of the problems that are > important to you. That's part of the trouble. I could never write gmpy from scratch, don't know enough. But I'm very good at understanding existing things. For 20 years I was a System Test Engineer and still consider myself a great debugger of both hardware and software. > > Since you say you couldn't get the attention of gmpy's developers you > might need to think about trying to join the team ... There's a team? > > >> This wouldn't be a simple project, but since there's a Windows buildbot > >> for Python there's no reason why the same couldn't be done for > >> extensions. I'll raise this with the PSF and see what the response is: > >> then your carping will at least have had some positive effect ;-) > > >> Stick with it, and let's try to make things better. > > > Ok. > > On a point of information, as it happens there's a Board meeting today > and I have tabled the topic for discussion. Unfortunately I can't > guarantee to attend the meeting (I am moving from the UK to the USA this > week) but I will try to do so, and will attempt to report back to c.l.py > within a week. Again, thanks for listening and trying to help. Even if nothing comes of it, at least we tried. I figure that sooner or later something has to be done and I'd rather see it done sooner. And no, I don't think I'm entitled to that. > > regards > Steve > > PS: Couldn't send this yesterday, or attend the meeting, because BT > Internet termined my DSL service early, mau God rot their profits and > drive them into bankruptcy. I'll report back once I found out how the > discussions went. > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007 From Bulkan at gmail.com Sun Feb 18 04:49:43 2007 From: Bulkan at gmail.com (placid) Date: 18 Feb 2007 01:49:43 -0800 Subject: cmd all commands method? In-Reply-To: <1171786661.599128.234300@k78g2000cwa.googlegroups.com> References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> <53per7F1t12jjU1@mid.individual.net> <1171786661.599128.234300@k78g2000cwa.googlegroups.com> Message-ID: <1171792183.564570.307940@m58g2000cwm.googlegroups.com> On Feb 18, 7:17 pm, "Michele Simionato" wrote: > On Feb 17, 11:44 pm, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > placid wrote: > > > if i want to treat every cmdloop prompt entry as a potential > > > command then i need to overwrite the default() method ? > > > Excuse me, what's a cmdloop prompt? What's the "default() method"? > > > > What i want to achieve is to be able to support global variable > > > creation for example; > > > > res = sum 1 2 > > > > this would create a variable res with the result of the method > > > do_sum() ? > > > > then would i be able to run; > > > > sum a 5 > > > > this would return 8 or an error saying that res is not defined > > > Are you sure you're talking about Python here? > > Yes, he is talking about the cmd module:http://docs.python.org/dev/lib/Cmd-objects.html. > However that module was never intended as a real interpreter, so > defining variables > as the OP wants would require some work. > > Michele Simionato How much work does it require ? From TheOneRedDragon at gmail.com Sat Feb 10 06:35:50 2007 From: TheOneRedDragon at gmail.com (TheOneRedDragon at gmail.com) Date: 10 Feb 2007 03:35:50 -0800 Subject: Wait for keypress Message-ID: <1171107349.967104.283080@j27g2000cwj.googlegroups.com> At the moment, I have a command-line application From http Sat Feb 17 12:52:08 2007 From: http (Paul Rubin) Date: 17 Feb 2007 09:52:08 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> <1171584254.805386.97300@a75g2000cwd.googlegroups.com> Message-ID: <7xejoozn7b.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > This may be where the "tuple is like a struct" analogy isn't so good, > and "tuple is like a list but immutable" is better. Right, that's what I'm getting at. From researchbase at gmail.com Sun Feb 11 01:49:54 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 11 Feb 2007 12:19:54 +0530 Subject: can't find a way to display and print pdf through python. In-Reply-To: <200702110647.l1B6l22s027328@nsa.veriwave.com> References: <200702110647.l1B6l22s027328@nsa.veriwave.com> Message-ID: On 11/02/07, Vishal Bhargava wrote: > Use Report Lab... I mentioned in my first email that I am already using reportlab. but I can only generate pdf out of that. I want to display it on screen and I also will be giving a print button which should do the printing job. by the way I use wxpython for gui. Krishnakant. From steve at holdenweb.com Mon Feb 19 10:39:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Feb 2007 10:39:41 -0500 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171898177.784761.283130@s48g2000cws.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <1171898177.784761.283130@s48g2000cws.googlegroups.com> Message-ID: Muntasir Azam Khan wrote: > On Feb 17, 3:22 am, ifti_cr... at yahoo.com wrote: >> I am VB6 programmer and wants to start new programming language but i >> am unable to deciced. >> >> i have read about Python, Ruby and Visual C++. but i want to go >> through with GUI based programming language like VB.net >> >> so will you please guide me which GUI based language has worth with >> complete OOPS Characteristics >> >> will wait for the answer >> >> hope to have a right direction from you Programmer >> >> Regards >> Iftikhar >> itzon... at yahoo.com > > There is no other GUI based programming language like VB. That's > because there is no such thing as a GUI based programming language. If > you want to learn a real general purpose programming language try > learning python. If you are only interested in making GUI's for > windows applications, better stick with VB or any of the other .NET > languages. > It's also worth remembering that you can use COM to drive a VB interface from Python, and of course there's now IronPython that allows you to use .NET-based interfaces directly. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From viscanti at gmail.com Tue Feb 6 05:16:42 2007 From: viscanti at gmail.com (viscanti at gmail.com) Date: 6 Feb 2007 02:16:42 -0800 Subject: XMLRPC Server Message-ID: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> Hi, I'm trying to create an XMLRPC server using apache + python (cgi). It's not too difficult to configure everything, but I would like to tune it in order to receive up to 2000 calls per minute without any problems. Do Pthon CGIs use threading? I need to make it very efficient, but I haven't found much information about Python CGI optimization. The called function will update a table in a mysql db. I will use triggers to export data from the table updated by the xmlrpc server to other tables used by the backend application. any hint? lv From rachele.defelice at gmail.com Fri Feb 2 10:17:13 2007 From: rachele.defelice at gmail.com (ardief) Date: 2 Feb 2007 07:17:13 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: <1170429433.258613.320600@a75g2000cwd.googlegroups.com> On Feb 2, 1:55 pm, "ardief" wrote: > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] .... thanks to everyone for the help, and the speed of it! It's really useful and I will spend some time working on understanding the code you posted. I'd be so lost without this group... r From rupendrakapali at yahoo.com Thu Feb 22 21:20:22 2007 From: rupendrakapali at yahoo.com (rupen) Date: 22 Feb 2007 18:20:22 -0800 Subject: LOOKING FOR REAL WORK AT HOME JOB?+MORE Message-ID: <1172197222.456633.44140@m58g2000cwm.googlegroups.com> Get paid For Completed Work. Would you like to earn money from home for completing various clerical based projects and assignments from home? You are not required to sell, or recruit but are simply paid to type ads and other media! No More relying on commissions Call: 00977-1- 2390177 / 9841206820 Check it out http://www.jobsnepal.info/idevaffiliate/idevaffiliate.php?id=1515 From grante at visi.com Wed Feb 7 22:40:46 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Feb 2007 03:40:46 -0000 Subject: help on packet format for tcp/ip programming References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> Message-ID: <12sl6tuhkla8ob2@corp.supernews.com> On 2007-02-08, rattan at cps.cmich.edu wrote: > struct module pack and unpack will only work for fixed size buffer : > pack('>1024sIL', buffer, count. offset) but the buffer size can vary > from one packet to the next :-( Oh for Pete's sake... struct.pack('>%dsIL' % len(buffer), buffer, count, offset) -- Grant Edwards grante Yow! I want the presidency at so bad I can already taste visi.com the hors d'oeuvres. From loveline17 at gmail.com Tue Feb 27 23:04:36 2007 From: loveline17 at gmail.com (loveline17 at gmail.com) Date: 27 Feb 2007 20:04:36 -0800 Subject: Installing java2python (Newbie) Message-ID: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> Hi guys, I'm having a hard time installing java2python ( http://code.google.com/p/java2python/ ) on my Windows XP 32-bit machine. I double click setup.py but nothing happens. Is there any specific Python sub-folder where I should put it and install using command line? Even when I use command-line, I get the error "install is not defined" etc. etc. java2python needs Antlr (other than Python 2.X obviously) which I already installed by double-clicking the .msi file. Thanks for any help!! From rjtucke at gmail.com Thu Feb 22 14:35:25 2007 From: rjtucke at gmail.com (rjtucke) Date: 22 Feb 2007 11:35:25 -0800 Subject: Quantum term project code- for interest and for help Message-ID: <1172172925.515686.244710@v33g2000cwv.googlegroups.com> Hello all, I have written a numerical simulation of a Bose Einstein Condensate in Python for a term project in my Quantum III class at Arizona State. You may find it at https://wiki.asu.edu/phy416/index.php/A_Simple_Bose-Einstein_Condensate_Simulation I post this for two reasons- first, as a matter of interest to any physics majors / professors out there, and second, because it is so _slow_ that the FORTRAN version runs ~180 times faster. I have used the profiler, and can't seem to speed it up at all. Any thoughts? I am now trying to port it to C, with mixed results. Finally, if you have any thoughts for how to tighten it up OR to make it more _readable_ (it is supposed to be an educational tool, after all), I would greatly appreciate it. Thanks, rjtucke From nagle at animats.com Mon Feb 26 01:34:39 2007 From: nagle at animats.com (John Nagle) Date: Mon, 26 Feb 2007 06:34:39 GMT Subject: Weakref problem: no way to get original object from proxy object? In-Reply-To: References: Message-ID: <3cvEh.1970$M65.599@newssvr21.news.prodigy.net> Gabriel Genellina wrote: > En Sun, 25 Feb 2007 19:07:38 -0300, John Nagle > escribi?: > >> Is there some way to get a strong ref to the original object back >> from a weakref proxy object? I can't find any Python function to do >> this. >> ".ref()" doesn't work on proxy objects. > > > Add a method to the original class that just returns self. Yes, that works. Thanks. John Nagle From steve at REMOVE.THIS.cybersource.com.au Tue Feb 27 10:16:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Feb 2007 02:16:55 +1100 Subject: os.system and quoted strings References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> Message-ID: On Tue, 27 Feb 2007 06:24:41 -0800, svata wrote: > Hello, > > as I'm new to python I've stumbled accros os.system and its not very > well documented usage. Documentation seems pretty good to me. system(...) system(command) -> exit_status Execute the command (a string) in a subshell. What more did you want to see? > I use Win XP Pro and Python 2.5. > > Here is the code snippet: > > -------------------------------------------------------------------------------------------------- > > import time > import os > > dir = "C:\\Documents and Settings\\somepath\\" I believe that Windows will accept forward slashes as directory separators, so you can write that as: dir = "C:/Documents and Settings/somepath/" > fileName = time.strftime("%d%m%Y") > os.system('gvim dir+fileName+".txt"') This will execute the command gvim dir+fileName+".txt" exactly as you typed it. I assume you don't have a file called dir+fileName+".txt" > The problem is that concatenated variable dir+fileName doesn't get > expanded as expected. Why would you expect them to be expanded? Does the documentation of os.system say that the command string will be expanded before it is passed to the subshell? > Is there anything I omitted? dir = "C:/Documents and Settings/somepath/" fileName = time.strftime("%d%m%Y") fileName = dir + fileName + ".txt" os.system('gvim %s' % fileName) That builds the command string correctly before passing it to a subshell. -- Steven From exarkun at divmod.com Tue Feb 6 16:00:50 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 6 Feb 2007 16:00:50 -0500 Subject: Python editor In-Reply-To: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> Message-ID: <20070206210050.25807.1039429928.divmod.quotient.12178@ohm> On 6 Feb 2007 12:51:13 -0800, BBands wrote: >No, no, no, this is not an invitation to the editor wars. > >I have been using Jos? Cl?udio Faria's superb Tinn-R, http://www.sciviews.org/Tinn-R/, >with the R language, http://www.r-project.org/. This editor allows you >to send code to the R shell for execution. You can easily send a line, >the selection, the balance after the cursor or the whole script. > >I have recently decided to move this project to Python instead of R. >However, I miss the interaction with the shell a la Tinn-R. Do any of >the Python editors support this feature? I would be especially >interested in using IPython as the shell. Python mode for emacs defines these functions which may be interesting to you: python-send-buffer Command: Send the current buffer to the inferior Python process. python-send-command Function: Like `python-send-string' but resets `compilation-minor-mode'. python-send-defun Command: Send the current defun (class or method) to the inferior Python process. python-send-receive Function: Send STRING to inferior Python (if any) and return result. python-send-region Command: Send the region to the inferior Python process. python-send-region-and-go Command: Send the region to the inferior Python process. python-send-string Command: Evaluate STRING in inferior Python process. Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Thu Feb 8 14:08:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 20:08:10 +0100 Subject: Functions, parameters In-Reply-To: References: Message-ID: <45cb6def$0$1014$426a74cc@news.free.fr> Boris Ozegovic a ?crit : > Hi, I'am still learning Python and while reading Django tutorial couldn't > understand this part: > > class Poll(models.Model): > question = models.CharField(maxlength=200) > pub_date = models.DateTimeField('date published') > > > # Django provides a rich database lookup API that's entirely driven by > # keyword arguments. > >>>>Poll.objects.filter(question__startswith='What') > > > This 'question__startswith' is the problem. What is the common idiom for > this type od arguments, so I can Google it? It's a named argument - in Python we usually name them keyword args. http://docs.python.org/tut/node6.html#SECTION006720000000000000000 > I understand what this filter > is suppose to do, but don't know how it is done (this separation of Poll > atribute and startwith function). > Why don't you just read the source code ? Django is free software, you know !-) What about something like: def filter(self, **kw): for argname, value in kw.items(): fieldname, op = argname.split('__', 1) assert fieldname in self.fields # build the query here # etc... From gert.cuykens at gmail.com Wed Feb 28 20:45:40 2007 From: gert.cuykens at gmail.com (gert) Date: 28 Feb 2007 17:45:40 -0800 Subject: urlDecode() In-Reply-To: <1172706706.152350.56390@z35g2000cwz.googlegroups.com> References: <1172706706.152350.56390@z35g2000cwz.googlegroups.com> Message-ID: <1172713540.467763.98810@t69g2000cwt.googlegroups.com> import re def htc(m): return chr(int(m.group(1),16)) def urldecode(url): rex=re.compile('%([0-9a-hA-H][0-9a-hA-H])',re.M) return rex.sub(htc,url) if __name__ == '__main__': print urldecode('adasasdasd%20asdasdasdas') Ok thats it enough googeling around i make one my self :) From orsenthil at gmail.com Tue Feb 27 01:50:34 2007 From: orsenthil at gmail.com (Phoe6) Date: 26 Feb 2007 22:50:34 -0800 Subject: How can I disable a device in windows using python Message-ID: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> Hi all, I am trying to disable the NIC card (and other cards) enabled in my machine to test diagnostics on that card. I am trying to disable it programmatic using python. I checked python wmi and i could not find ways to disable/enable, (listing is however, possible). Where should I look for to enable/disable devices in python. Thanks, Senthil From jm.suresh at gmail.com Wed Feb 14 02:23:46 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 13 Feb 2007 23:23:46 -0800 Subject: Recursive calls and stack In-Reply-To: References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: <1171437825.977798.249420@q2g2000cwa.googlegroups.com> On Feb 14, 11:45 am, "Gabriel Genellina" wrote: > En Wed, 14 Feb 2007 03:09:37 -0300, jm.sur... at no.spam.gmail.com > escribi?: > > > Hi, > > I have a program which literately finds the object that overlapping a > > point. The horizontal and vertical search are called recursively from > > inside each other. > > Is this way of implementation fill the stack space with the local > > variables inside each call. If this is not good, is there a better way > > to implement? Or python itself will understand that the calls happen > > in the last line, so local variables need not be pushed into the > > stack? > > I'm afraid not, the calls will be stacked until some object is found. > Python does not do "tail recursion optimization" (at least, I'm not aware > of that). But even if it could do that, in this case you have recursive > calls between two functions, and that's a bit harder. > > Going back to your original problem, maybe you can use some known > algorithms from computational geometry; start with http://www.faqs.org/faqs/graphics/algorithms-faq/ > > -- > Gabriel Genellina Thanks Gabriel for the response. I am OK with calls being stacked, but I wondering will the local variables be stacked given that return statement is followed by the function call? def test(): x = 22 y = 33 z = x+y return anotherFunction(z) In this function will all the local variables (x,y,z) be pushed into the stack before calling anotherFunction(z) or Python will find out that the locals are no longer needed as anotherFunction(z) is just returned? - Suresh From nogradi at gmail.com Tue Feb 27 05:59:10 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 27 Feb 2007 11:59:10 +0100 Subject: gmpy moving to code.google.com In-Reply-To: References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> Message-ID: <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> Hi Alex, I did another test, this time with python 2.4 on suse and things are worse than in the previous case (which was python 2.5 on fedora 3), ouput of 'python gmp_test.py' follows: Unit tests for gmpy 1.02 release candidate on Python 2.4 (#1, Mar 22 2005, 21:42:42) [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] Testing gmpy 1.02 (GMP 4.1.3), default caching (20, 20, -2..11) gmpy_test_cvr 270 tests, 0 failures gmpy_test_rnd 26 tests, 0 failures gmpy_test_mpf 155 tests, 0 failures gmpy_test_mpq 264 tests, 0 failures gmpy_test_mpz 376 tests, 0 failures ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_dec.py", line ?, in gmpy_test_dec.__test__.elemop Failed example: print f+d Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1, in ? print f+d File "/usr/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_dec.py", line ?, in gmpy_test_dec.__test__.elemop Failed example: print d+f Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1, in ? print d+f File "/usr/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_dec.py", line ?, in gmpy_test_dec.__test__.elemop Failed example: print q+d Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1, in ? print q+d File "/usr/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_dec.py", line ?, in gmpy_test_dec.__test__.elemop Failed example: print d+q Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1, in ? print d+q File "/usr/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_dec.py", line ?, in gmpy_test_dec.__test__.elemop Failed example: print z+d Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1, in ? print z+d File "/usr/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. ********************************************************************** File "/home/nogradi/tmp/gmpy/test/gmpy_test_dec.py", line ?, in gmpy_test_dec.__test__.elemop Failed example: print d+z Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1, in ? print d+z File "/usr/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. ********************************************************************** 1 items had failures: 6 of 15 in gmpy_test_dec.__test__.elemop ***Test Failed*** 6 failures. gmpy_test_dec 16 tests, 6 failures 7 items had no tests: gmpy_test_cvr._test gmpy_test_dec._test gmpy_test_mpf._test gmpy_test_mpq._test gmpy_test_mpz._memsize gmpy_test_mpz._test gmpy_test_rnd._test 29 items passed all tests: 6 tests in gmpy_test_cvr 12 tests in gmpy_test_cvr.__test__.misc_stuff 252 tests in gmpy_test_cvr.__test__.user_errors 1 tests in gmpy_test_dec 1 tests in gmpy_test_mpf 32 tests in gmpy_test_mpf.__test__.binio 33 tests in gmpy_test_mpf.__test__.cmpr 49 tests in gmpy_test_mpf.__test__.elemop 34 tests in gmpy_test_mpf.__test__.format 6 tests in gmpy_test_mpf.__test__.newdiv 2 tests in gmpy_test_mpq 26 tests in gmpy_test_mpq.__test__.binio 62 tests in gmpy_test_mpq.__test__.cmpr 66 tests in gmpy_test_mpq.__test__.elemop 54 tests in gmpy_test_mpq.__test__.format 12 tests in gmpy_test_mpq.__test__.newdiv 18 tests in gmpy_test_mpq.__test__.power 24 tests in gmpy_test_mpq.__test__.qdiv 4 tests in gmpy_test_mpz 34 tests in gmpy_test_mpz.__test__.binio 62 tests in gmpy_test_mpz.__test__.bitops 48 tests in gmpy_test_mpz.__test__.cmpr 42 tests in gmpy_test_mpz.__test__.elemop 36 tests in gmpy_test_mpz.__test__.format 12 tests in gmpy_test_mpz.__test__.newdiv 134 tests in gmpy_test_mpz.__test__.number 4 tests in gmpy_test_mpz.factorize 1 tests in gmpy_test_rnd 25 tests in gmpy_test_rnd.__test__.rand ********************************************************************** 1 items had failures: 6 of 15 in gmpy_test_dec.__test__.elemop 1107 tests in 37 items. 1101 passed and 6 failed. ***Test Failed*** 6 failures. HTH, Daniel From deets at nospam.web.de Tue Feb 27 05:56:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Feb 2007 11:56:55 +0100 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> <1172573562.215310.76760@8g2000cwh.googlegroups.com> Message-ID: <54ih3nF2143jeU2@mid.uni-berlin.de> > > Yes that I can deduce, but why I'm asking is why it's different on > Windows and Linux. Should it not be platform independent? It should be. I've got no idea why it seems to work on windows but I can say one thing for sure: that would be an artifact that you shouldn't rely on. In Qt, you _always_ need a QApplication for anything. So just do as it requires you to do: first, construct a QApplication. Then things will work. Diez From tech-hr at smartcharter.com Sun Feb 25 23:32:20 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Sun, 25 Feb 2007 20:32:20 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area Message-ID: http://www.smartcharter.com/jobs.html Smart Charter Inc. is a dynamic new startup company aiming to revolutionize the purchase and sale of private aviation services. If you are ready for a challenging ground-floor opportunity with significant upside potential you've come to the right place. We are not your typical dotcom. We have a razor-sharp focus on an existing multi-billion-dollar market. We are well funded, and have the connections and the technical expertise we need to revolutionize an industry. We are looking for people who are highly motivated and passionate about their work, and able to produce high quality code within a fast paced development environment. We are hiring for the following positions: ? Senior software engineer -- Ideal candidate would have significant development experience, possibly an advanced degree in computer science or related field, experience developing planning & scheduling or operations software using linear programming and heuristic search methods. Proficiency in multiple languages including (but not limited to) C++, Python and Common Lisp would also be desirable. ? Windows software engineer -- This person will be responsible for integrating elements of our products into multiple existing Windows applications. An ideal candidate would have experience in development for the PC platform, in multiple tool suites, including Visual Studio.net Useful skills include the ability to work within existing interfaces, protocols, and code structures and to work with extensively with database applications. ? Web developer, senior web developer, system administrator -- Our website is currently a LAMP appication with P=Python. We are looking for bright motivated people who know or are willing to learn Python and/or Linux, Apache and MySQL system administration skills. (And if you want to convince us that we should switch over to Postgres, we're willing to listen.) We are more interested in smarts, passion, and a willingness to learn new things than specific credentials. If you are interested in joining us drop us a line at: tech-hr at smartcharter.com From gagsl-py at yahoo.com.ar Thu Feb 8 22:02:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Feb 2007 00:02:13 -0300 Subject: Dictionary Question References: <2adc542f0702081832k2b917a86pede0f419d5ff7be4@mail.gmail.com> Message-ID: En Thu, 08 Feb 2007 23:32:50 -0300, Sick Monkey escribi?: > db = {'blah at gmail.com':'none', 'blah at yahoo.com':'none', > 'blah at aol.com':'none', > 'blah at gmail.com':'none',} > > And I want to pull out all of the "gmail.com" addresses.. How would I do > this? > > NOTE: I already have a regular expression to search for this, but I feel > that looping over a dictionary is not very efficient. for key in db: if domain_regexp.search(key): print "horray" Iterating over the dictionary keys should be rather efficient. timeit and see if it worths to make it more complex. -- Gabriel Genellina From jm.suresh at gmail.com Sun Feb 11 08:51:36 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 11 Feb 2007 05:51:36 -0800 Subject: gvim: doc string editing Message-ID: <1171201896.897644.60000@p10g2000cwp.googlegroups.com> Hi, I am using gvim, and am looking for a way to tell gvim to automatically wrap long lines into multiple lines ( by automatically inserting the newline character) when I edit doc strings. I am sure somebody must have done this. - Suresh From jdillworth at gmail.com Tue Feb 27 23:34:35 2007 From: jdillworth at gmail.com (Jeremy Dillworth) Date: 27 Feb 2007 20:34:35 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> Message-ID: <1172637274.994742.173850@p10g2000cwp.googlegroups.com> I haven't used that particular package, but the norm for setup.py is this command line: python setup.py install Hope this helps, Jeremy From theller at ctypes.org Sat Feb 24 11:42:36 2007 From: theller at ctypes.org (Thomas Heller) Date: Sat, 24 Feb 2007 17:42:36 +0100 Subject: Recreating a char array from a pointer In-Reply-To: <45e05fb2$0$486$cc7c7865@news.luth.se> References: <45e05fb2$0$486$cc7c7865@news.luth.se> Message-ID: buffinator schrieb: > I have an application that has to send a string as a pointer to memory, > and then another one that has to retriece it and fetch the string. > Converting the string to an array and sending the pointer was easy > > import array > a=array.array("c","mytextgoeshere") > my_pointer = a.buffer_info()[0] > > > But then I tried to get the data back... and I just can't find out how. > I ended up writing a C module for this that works fine in linux, but > this application is meant for windows and I just can't get C-modules to > compiler there correctly since I suck at windows. > > The relevant code from the module is > > static PyObject * > pointrtostr_casttostr(PyObject *self, PyObject *args) > { > char *mystr; > long int p; > > if (!PyArg_ParseTuple(args, "l", &p)) > return NULL; > > mystr = (char*)p; > return Py_BuildValue("s", mystr); > } > > My question is... can I do the above code in python without involving C > since it is quite a big hassle to have to go through the module building > in windows? :/ You can use the ctypes package for this. It is in the standard library in Python 2.5, for older versions it is a separate download. Thomas From gagsl-py at yahoo.com.ar Fri Feb 2 10:51:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 2 Feb 2007 12:51:53 -0300 Subject: stlib name clash when using python as ASP language References: <1170323389.184681.250640@v45g2000cwv.googlegroups.com> Message-ID: "Joost" escribi? en el mensaje news:1170323389.184681.250640 at v45g2000cwv.googlegroups.com... > When using ASP the iis/inetsrv path is placed as the first item in > sys.path. Consequently importing httplib2 will cause the following > error: > > ImportError: dynamic module does not define init function (initgzip) > > The following per page hack *fixes* the problem most of the time: > import sys > sys.path[0] = "c:/python24/lib" > > Strangely, even with this code loaded in every page the import error > sporadically occurs. What would be the preferred way to solve this > name clash? You *assume* that [0] is the IIS path, but perhaps some other imported module changed sys.path too, and now it's not the first one anymore. If you know exactly the path, try sys.path.remove(iis_path). -- Gabriel Genellina From franz.steinhaeusler at gmx.at Thu Feb 1 15:05:55 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Thu, 01 Feb 2007 21:05:55 +0100 Subject: Ubunu - Linux - Unicode - encoding References: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> <1170347047.711706.48020@a34g2000cwb.googlegroups.com> Message-ID: On 1 Feb 2007 08:24:07 -0800, "Paul Boddie" wrote: >On 1 Feb, 16:02, Franz Steinhaeusler >wrote: >> >> The case: >> I have a file on a WindowsXP partition which has as contents german >> umlauts and the filename itself has umlauts like i????k.txt >> >> If I want to append this file to a list, I get somehow latin-1, cannot >> decode 'utf-8'. > >You mean that you expect the filename in UTF-8, but it arrives as >ISO-8859-1 (Latin1)? How do you get the filename? Via Python standard >library functions or through a GUI toolkit? What does >sys.getfilesystemencoding report? Hello Paul, I set the sysencoding already to 'latin-1', but obviously the value is ignored and it takes 'utf-8' (?) I get it with thelist = os.listdir(directory) and the directory is a string, not unicode. > >[...] > >> Why is this setdefaultencoding otherwise not working on linux? > >My impression was that you absolutely should not change the default >encoding. Aha. >Instead, you should react to encoding information provided >by your sources of data. For example, sys.stdin.encoding tells you >about the data from standard input. > >> (Also Filemanagers like Nautilus or Krusader cannot display the files >> correctly). > >This sounds like a locale issue... Hm, a setting in linux. > >> Is there a system wide linux language setting (encoding), which I have >> to install and adjust? > >I keep running into this problem when installing various >distributions. Generally, the locale needs to agree with the encoding >of the filenames in your filesystem, so that if you've written files >with UTF-8 filenames, you'll only see them with their proper names if >the locale you're using is based on UTF-8 - things like en_GB.utf8 and >de_AT.utf8 would be appropriate. Such locales are often optional >packages, as I found out very recently, and you may wish to look at >the language-pack-XX and language-pack-XX-base packages for Ubuntu >(substituting XX for your chosen language). Once they are installed, >typing "locale -a" will let you see available locales, and I believe >that changing /etc/environment and setting the LANG variable there to >one of the available locales may offer some kind of a solution. Ah thank you very much for that enlightment! > >Another thing I also discovered very recently, after doing a >debootstrap installation of Ubuntu, was that various terminals >wouldn't reproduce non-ASCII characters without an appropriate (UTF-8) >locale being set up, even though other desktop applications were happy >to accept and display the characters. That sound familar to me! ;) > I thought this was a keyboard >issue, compounded by the exotic nested X server plus User Mode Linux >solution I was experimenting with, but I think locales were the main >problem. > >Paul So that is not exactly simple. :) Thank you very much for this precise answer! -- Franz Steinhaeusler From fccoelho at gmail.com Thu Feb 22 08:22:12 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 05:22:12 -0800 Subject: plugin development best practices In-Reply-To: <545ifrF1v049oU1@mid.uni-berlin.de> References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> <545ifrF1v049oU1@mid.uni-berlin.de> Message-ID: <1172150532.157803.299330@m58g2000cwm.googlegroups.com> On Feb 22, 11:00 am, "Diez B. Roggisch" wrote: > Flavio wrote: > > Hi, > > > Nowadays the addition of functionality to programs by means of > > plugins is very frequent. > > > I want to know the opinions of experienced Python developers about the > > best practices when it comes to developing a plugin system for a > > Python package. > > > Should plugins be modules in a separate package? > > Should there be a registry of available plugins? how would such a > > registry be implemented? etc. > > There have been a gazillion discussions about this on this newsgroup/mailing > list. Searching the archives will get you to them. > > The dynamic nature of python makes a whole range of options available. > Depending on what you want to do (how are the plugins made available and so > on), one or the other might be preferable. > > One relatively current development is the usage of setuptools "entry-points" > feature, which is precisely made for discovering installed plugins: > > http://peak.telecommunity.com/DevCenter/setuptools#dynamic-discovery-... > > Diez Thanks Diez, I will search the archives. I am aware of the setuptools feature It is quite nice. But the documentation is not very clear on how to define "entry point groups" on the importing end, i.e. how to prepare a an application to accept plugins it doesn't even now exist. Flavio From unidevel at gmail.com Fri Feb 23 07:19:29 2007 From: unidevel at gmail.com (unidevel at gmail.com) Date: 23 Feb 2007 04:19:29 -0800 Subject: python float-point problem Message-ID: <1172233169.420404.144250@j27g2000cwj.googlegroups.com> I just compiled python 2.4.2 using openembedded for my zaurus C750. I test some comparison for float-pointing number, for example: 3.1<3.0 True 3.2<3.0 True 3.3<3.0 False 8.4<4.0 True I use the cross compiler that compiled python to make a simple C program, got correct results. Anyone have some idea about that? From shanekwon at gmail.com Tue Feb 13 21:20:41 2007 From: shanekwon at gmail.com (agent-s) Date: 13 Feb 2007 18:20:41 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: <1171419641.085043.59550@k78g2000cwa.googlegroups.com> Thanks for the help guys but I'm a newbie at this and from what I understand from the code, it looks like you guys are using a two dimensional array. I am not using a two dimensional array. Basically, it looks like this: [ [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '] ] above: a list of lists NOT a two-dimensional array From v.davis2 at cox.net Wed Feb 28 19:24:12 2007 From: v.davis2 at cox.net (v.davis2) Date: Wed, 28 Feb 2007 17:24:12 -0700 Subject: Audio -- Looking for Help with Using Snack on Windows Message-ID: Hi all, I am looking for some non-trivial examples of use of the Snack toolbox [on Windows]. The documentation seems a bit lacking. One typical example is how to use the FFT method or the Configure method or the mixer or ..... I have searched and examined many examples, but so far they just seem to be replays of the trivial examples given with the package. Thanks so much! If you have more ideas to share than a simple post here, please feel free to email me at v.davis2 at cox.net Thanks! Vic From adonis at REMOVETHISearthlink.net Wed Feb 28 16:13:06 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Wed, 28 Feb 2007 21:13:06 GMT Subject: New to Tkinter GUI building In-Reply-To: <1172695675.279652.98920@a75g2000cwd.googlegroups.com> References: <1172695675.279652.98920@a75g2000cwd.googlegroups.com> Message-ID: Adam wrote: > I think my main questions are: > 1. How can I get the Window to be sized the way I want it? > 2. How can I get the Scrollbars to fill the side of the text box > instead of being small? (like .pack(fill= tk.Y) > > > I have only posted the code relevant to the GUI. > > TIA > Adam > To size the window use Tk's geometry method self.top.geometry("%dx%d%+d%+d" % (800, 600, 0, 0)) # (width, height, x, y) For the scrollbar to fill vertically, use the sticky grid option. self.scrlr1.grid(row=0, column=1, sticky=tk.N + tk.S) Hope this helps. Adonis From bobmon at gmail.com Sat Feb 24 19:08:19 2007 From: bobmon at gmail.com (bobmon) Date: 24 Feb 2007 16:08:19 -0800 Subject: newbie needs help building Python 2.5 for Fedora Core 6 In-Reply-To: <*firstname*nlsnews-02C6F9.18133624022007@news.verizon.net> References: <1172355934.549788.59820@a75g2000cwd.googlegroups.com> <*firstname*nlsnews-02C6F9.18133624022007@news.verizon.net> Message-ID: <1172362098.987415.102010@8g2000cwh.googlegroups.com> WOW. I'm gobsmacked... On Feb 24, 6:13 pm, Tony Nelson <*firstname*nlsnews at georgea*lastname*.com> wrote: > > Try it from the python command line. This is what happens when I try it Okay, that was interesting... Apparently there's a subtlety of /etc/hosts that affects this! Originally it had this line: 127.0.0.1 localhost localhost.localdomain foobar and I get this result for my machine ("foobar.foodomain.com"): >>> >>> import socket >>> socket.gethostname() 'foobar.foodomain.com' >>> socket.gethostbyname(_) Traceback (most recent call last): File "", line 1, in socket.gaierror: (-2, 'Name or service not known') >>> >>> >>> socket.gethostbyname('localhost') '127.0.0.1' >>> socket.gethostbyname('localhost.localdomain') '127.0.0.1' >>> Whe I change /etc/hosts to this: 127.0.0.1 foobar foobar.foodomain.net localhost.localdomain localhost Python is happy and I get; >>> >>> import socket >>> socket.gethostname() 'foobar.foodomain.net' >>> socket.gethostbyname(_) '127.0.0.1' >>> So, problem "fixed" although I have no real understanding of what was wrong or what's right now. Only that "gethostbyname()" seems to be really sensitive to the format of the /etc/hosts file. Thank you, Tony Nelson. -Bob Montante, -bob,mon. From tokauf at web.de Thu Feb 22 15:57:09 2007 From: tokauf at web.de (TK) Date: Thu, 22 Feb 2007 21:57:09 +0100 Subject: Newbie question: Install Tkinter with Python2.5 Message-ID: <45de03c6$0$8891$9b622d9e@news.freenet.de> Hi there, how can I install Tkinter with Python2.5? I can install Python2.5 (tarball) in the usual way but there is no Tkinter? What's wrong? Traceback (most recent call last): File "mbox.py", line 12, in from Tkinter import * File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter o-o Thomas From mail at microcorp.co.za Mon Feb 26 00:54:12 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 26 Feb 2007 07:54:12 +0200 Subject: Help on object scope? References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> Message-ID: <014b01c7596d$14927b80$03000080@hendrik> "hg" wrote: > bmaron2 at hotmail.com wrote: > > > Hello everybody, > > > > I have a (hopefully) simple question about scoping in python. I have a > > program written as a package, with two files of interest. The two > > files are /p.py and /lib/q.py Make a third file for all the system wide globals, say param.py: global r r = 42 > > > > My file p.py looks like this: > > > > --- > > > > from lib import q > > > > def main(): from param import * > > global r > > r = q.object1() > > s = q.object2() > > > > if __name__ == "__main__": > > main() > > > > --- > > > > My file q.py in the subdirectory lib looks like this: from param import * > > > > class object1: > > t = 3 > > > > class object2: > > print r.t > > > > --- > > > > Python gives me an error, saying it can't recognize global name r. > > However I define r as global in the top-level main definition! Can > > anyone suggest how I can get around this, if I want to define and bind > > global names inside of main() which are valid in all sub-modules? > > > > Thanks very much for your help! > > Might be wrong, but globals can only be global to the module they're > declared in. Correct. > > I suggest you find another way such as passing your object as a parameter or make the third file and import it everywhere you need them... - Hendrik From dknight at wsi.com Tue Feb 27 14:23:20 2007 From: dknight at wsi.com (Knight, Doug) Date: Tue, 27 Feb 2007 14:23:20 -0500 Subject: book for a starter In-Reply-To: <1172603326.853903.315620@z35g2000cwz.googlegroups.com> References: <54j9qfF20cqgnU1@mid.individual.net> <1172603326.853903.315620@z35g2000cwz.googlegroups.com> Message-ID: <1172604200.18790.14.camel@arc-dknightlx.wsicorp.com> Excellent choice. I used the 2nd edition for better than a year as a reference as I "came up to speed" on the language. Didn't know there was a 3rd edition out. Doug On Tue, 2007-02-27 at 11:08 -0800, Sriram wrote: > Hi, > > If you have experience programming, just read the online tutorial at > http://docs.python.org/tut/tut.html > > I find Python Essential Reference (3rd Edition) (Developer's Library) > (Paperback) invaluable though. BTW I have the 2nd edition. > Amazon link : > http://www.amazon.com/gp/pdp/profile/A9N9B1L0O4BYJ/ref=cm_blog_dp_pdp/002-7062034-2980840 > > > On Feb 27, 10:58 am, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: > > Wensui Liu wrote: > > > I just start learning python and have a question regarding books > > > for a newbie like me. > > > > http://wiki.python.org/moin/IntroductoryBooks > > > > > If you are only allowed to buy 1 python book, which one will you > > > pick? ^_^. > > > > I'd pick a reference. YMMV. > > > > Regards, > > > > Bj?rn (having been allowed to buy more than one Python book) > > > > -- > > BOFH excuse #314: > > > > You need to upgrade your VESA local bus to a MasterCard local bus. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From subscriber123 at gmail.com Mon Feb 12 20:36:56 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Mon, 12 Feb 2007 20:36:56 -0500 Subject: Gosper arithmetic in Python In-Reply-To: References: Message-ID: <4c0048df0702121736j75096631geecfe73eb462531a@mail.gmail.com> Speaking of useful home-made modules, I wrote this primitive module which does limited math with fractions. Anyone is welcome to expand on it or use it for any purpose. If anyone would like to submit it as a PEP to be added to the Python library of reference, that would be great. If anyone wishes to do that, I ask that you at least add me as a coauthor. Collin Stocks On 2/12/07, Marcin Ciura wrote: > > Hello, > > I hacked together a module implementing exact real > arithmetic via lazily evaluated continued fractions. > You can download it from > http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py > an use as an almost drop-in replacement for the math module > if you don't care too much about performance. > I'd be happy to hear any feedback and suggestions. > > Cheers, > Marcin > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- from math import sqrt class Fract(object): def __init__(self,*args): if len(args)==2: self.num,self.den=map(int,args) if len(args)==1: try:self.num,self.den=args[0].num,args[0].den except:self.num,self.den=int(args[0]),int(1) def __abs__(self): return Fract(abs(self.num),abs(self.den)) def __add__(self,other): other=Fract(other) x=self.change_den(self,other.den) y=self.change_den(other,self.den) return Fract(x.num+y.num,x.den) def __sub__(self,other): other=Fract(other) x=self.change_den(self,other.den) y=self.change_den(other,self.den) return Fract(x.num-y.num,x.den) def __div__(self,other): other=Fract(other) return Fract(self*self.invert(other)) def __mul__(self,other): other=Fract(other) return Fract(self.num*other.num,self.den*other.den) def __gt__(self,other): return float(self)>float(other) def __lt__(self,other): return float(self)=float(other) def __le__(self,other): return float(self)<=float(other) def __eq__(self,other): return float(self)==float(other) def __pow__(self,exp): x=self for i in range(1,exp): x=x*self return x def __float__(self): return float(self.num)/float(self.den) def __int__(self): return self.num/self.den def __str__(self): #print>>s,"string:",self.num,self.den self.simplify() return "%s/%s"%(self.num,self.den) def __repr__(self): #print>>s,"string:",self.num,self.den self.simplify() return "Fract(%s,%s)"%(self.num,self.den) def simplify(self): self.num,self.den=reduce(self.num,self.den) """ debug=[] debug.append((self.num,self.den)) for i in [self.num,self.den,2,3,5,7]: while self.num%i==0 and self.den%i==0 and self.num!=1 and self.den!=1: self.num/=i self.den/=i for i in xrange(11,int(sqrt(self.den))+3,2): while self.num%i==0 and self.den%i==0: self.num/=i self.den/=i if self.num==self.den!=1: print debug raise "the end" """ def invert(self,fraction): fraction=Fract(fraction) return Fract(fraction.den,fraction.num) def change_den(self,fraction,mult): return Fract(fraction.num*mult,fraction.den*mult) def scale(*args): mul=float(args[0]) args=list(args) length=len(args) dens=[] for arg in args: dens.append(arg.den) #print>>s,args for i in range(length): for j in range(length): if not i==j: args[i].num*=dens[j] args[i].den*=dens[j] nums=[] for arg in args:nums.append(arg.num) args=map(Fract,reduce(*nums)) #print>>s,args mul=float(args[0])/mul args.append(mul) #print>>s,args[0].den==args[1].den==args[2].den return args """ for j in range(len(args)): args2=list(args) for i in range(len(args)): #print>>s,i,j #print>>s,args,args2 args[i]*=args2[j].den dens=[] for arg in args:dens.append(arg.den) dens=reduce(*dens) for i in range(len(dens)):args[i].den=dens[i] #print>>s,args,args2 ##args[i].simplify() return args """ def reduce(*args): args=list(args) for i in [min(args),2,3,5,7]: divisible=True for j in range(len(args)):divisible=(divisible and (args[j]%i==0)) #print>>s,divisible,args,i if args[0]!=int(args[0]): raise Warning while divisible and min(args)!=1: for loc in range(len(args)):args[loc]/=i for j in range(len(args)):divisible=(divisible and (args[j]%i==0)) for i in xrange(11,int(sqrt(min(args)))+3,2): divisible=True for j in range(len(args)):divisible=(divisible and (args[j]%i==0)) while divisible and min(args)!=1: for loc in range(len(args)):args[loc]/=i for j in range(len(args)):divisible=(divisible and (args[j]%i==0)) return args import sys s=sys.__stdout__ From daftspaniel at gmail.com Fri Feb 9 07:54:32 2007 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 9 Feb 2007 04:54:32 -0800 Subject: Is Python for me? In-Reply-To: References: Message-ID: <1171025672.235503.128610@v33g2000cwv.googlegroups.com> On Feb 9, 5:08 am, "jiddu" wrote: > I'm planning to create a poker calculator, I learned some basic in > highschool years ago and I was told for beginners Python is a good > language to start. Be sure to check out the Python411 podcast http://awaretek.com/python/index.html Take care, Davy http://www.latedecember.co.uk/sites/personal/davy/?clp From bearophileHUGS at lycos.com Thu Feb 8 13:02:13 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Feb 2007 10:02:13 -0800 Subject: Does the world need another v0.1 python compiler? In-Reply-To: <1170954814.417840.64810@l53g2000cwa.googlegroups.com> References: <1170918215.074099.262930@p10g2000cwp.googlegroups.com> <1170954814.417840.64810@l53g2000cwa.googlegroups.com> Message-ID: <1170957733.673152.119430@j27g2000cwj.googlegroups.com> sturlamolden: > IMHO, with the presence of static types in Py3K, we should have a > static compiler that can be invoked dynamically, just like Common > Lisp. > Something like > > def foo(...): > bar = static_compile(foo, optimize=2) > bar(...) > > JIT compilers are hyped, static compilers perform much better. This > way the programmer can decide what needs to be compiled. This is the > reason why CMUCL can compete with most C compilers. Lot of Python code uses Psyco, so maybe it may be better to extend Psyco to that 'static compilation' functionality too: def foo(...): psyco.static_bind(foo) At the moment I think this approach can't improve much the speed of Python programs compared to what Psyco is already able to do. PyPy's RPython and ShedSkin are also to be considered, recently ShedSkin is going to support some of the usual Python forms of lazy processing too. Bye, bearophile From http Sun Feb 18 01:16:59 2007 From: http (Paul Rubin) Date: 17 Feb 2007 22:16:59 -0800 Subject: Need an identity operator because lambda is too slow References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> Message-ID: <7xlkiwhtwk.fsf@ruckus.brouhaha.com> "Deron Meranda" writes: > do_transform = some_rare_condition > for item in some_sequence: > if do_transform: > item2 = transform_function(item) > else: > item2 = item > ..... # more stuff This might be a little more direct: from itertools import imap if some_rare_condition: mapped_sequence = imap(transform_function, some_sequence) else: mapped_sequence = some_sequence for item in mapped_sequence: # more stuff I agree that an identity function would be useful. I think I suggested it a long time ago and didn't get much interest. From skip at pobox.com Tue Feb 6 13:32:48 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 6 Feb 2007 12:32:48 -0600 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: Message-ID: <17864.51664.838043.38090@montanaro.dyndns.org> John> MySQLdb isn't fully supported for Python 2.5 yet, and there's no John> tested Windows executable available, although there's an untested John> version from a World of Warcraft guild available. As Andy Dustman has pointed out a number of times, he doesn't do Windows. Someone in the MySQLdb community who does use Windows is going to have to fill that void. Skip From skip at pobox.com Sat Feb 3 09:04:49 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 3 Feb 2007 08:04:49 -0600 Subject: Python 2.5 Quick Reference In-Reply-To: <20070203131049.2990B1E4009@bag.python.org> References: <45C479EA.20908@jessikat.plus.net> <20070203131049.2990B1E4009@bag.python.org> Message-ID: <17860.38529.172919.293226@montanaro.dyndns.org> Dick> Respondent> I really like these for a good overview Dick> So it looks accurate? He's been doing it awhile: http://rgruet.free.fr/ I think he's got the drill down pretty well by now... ;-) Skip From wattersmt at gmail.com Tue Feb 6 08:26:45 2007 From: wattersmt at gmail.com (wattersmt at gmail.com) Date: 6 Feb 2007 05:26:45 -0800 Subject: Running long script in the background Message-ID: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> Hello, I am trying to write a python cgi that calls a script over ssh, the problem is the script takes a very long time to execute so Apache makes the CGI time out and I never see any output. The script is set to print a progress report to stdout every 3 seconds but I never see any output until the child process is killed. Here's what I have in my python script: command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % (host, domuname) output = os.popen(command) for line in output: print line.strip() Here's a copy of the bash script. http://watters.ws/script.txt I also tried using os.spawnv to run ssh in the background and nothing happens. Does anybody know a way to make output show in real time? From robert.kern at gmail.com Thu Feb 8 11:02:48 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 08 Feb 2007 10:02:48 -0600 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: W. Watson wrote: > I did a search in the python24 folder for sys.exec* (in c:\python24), but > came up with nothing. [nothing in a search of c:--sys.exec*] I have two > python folders, c:\python24 and c:\python25. The contents of both folders > look fairly similar and each have a python.exe. I do not use a PIL or > Numeric in 2.5. I'm sorry. sys is a module. I meant for you to execute the following Python code: import sys print sys.executable -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From usenet1 at ingfamily.net Thu Feb 15 19:49:56 2007 From: usenet1 at ingfamily.net (usenet1 at ingfamily.net) Date: 15 Feb 2007 16:49:56 -0800 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded In-Reply-To: <1171571229.141330.250700@m58g2000cwm.googlegroups.com> References: <1171305876.030471.59470@s48g2000cws.googlegroups.com> <1171564971.279097.151370@p10g2000cwp.googlegroups.com> <1171571229.141330.250700@m58g2000cwm.googlegroups.com> Message-ID: <1171586996.509170.162020@a34g2000cwb.googlegroups.com> After installing activestate python 2.4 and ctypes-1.0.1.win32- py2.4.exe, everything just worked. So, I decided to stay with 2.4 since I don't have time to figure out the problem. Steve From JohnRoth1 at jhrothjr.com Thu Feb 1 12:39:19 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 1 Feb 2007 09:39:19 -0800 Subject: SWIG overhead In-Reply-To: <1170325295.575450.84340@s48g2000cws.googlegroups.com> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> Message-ID: <1170351559.493523.45020@a75g2000cwd.googlegroups.com> On Feb 1, 3:21 am, "Bart Ogryczak" wrote: > Hi, > I?m looking for some benchmarks comparing SWIG generated modules with > modules made directly with C/Python API. Just how much overhead does > SWIG give? Doing profile of my code I see, that it spends quiet some > time in functions like _swig_setattr_nondinamic, _swig_setattr, > _swig_getattr. This isn't exactly what you're looking for, but I tried SWIG a while ago, back when I still had a C compiler, and then decided to use c- types. The reason: I've got an aversion to anything that generates huge steaming piles of incomprehensible code. Especially when I found a couple of bugs in a SWIG-generated module I'd gotten from someone else. This wasn't SWIG's fault, it was the author's for not understanding the API he was wrapping properly, but I had to dig into the SWIG code before I could figure out what was going on. Bottom line: the c-types module was a lot smaller, in Python, and completely comprehensible. And while I didn't measure the performance, I doubt if it was slower. John Roth From B.Ogryczak at gmail.com Thu Feb 22 11:22:45 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 22 Feb 2007 08:22:45 -0800 Subject: How to test whether a host is reachable? In-Reply-To: References: Message-ID: <1172161365.526113.177260@s48g2000cws.googlegroups.com> On Feb 22, 3:22 pm, Fabian Steiner wrote: > Now I am wondering if there isn't any better method which would be more > general. In fact, I think of something like a python version of ping > which only tries to send ICMP packets. Server or a firewall in between most probably will filter out any ICMP packets, so you'll get no pings at all from a machine which IS on- line. The only way is try the services that you know, that should be open on that machine. Do not try too many at a time, becouse that could be interpeted as portscan and you'll get blacklisted. From __peter__ at web.de Sat Feb 10 02:47:36 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Feb 2007 08:47:36 +0100 Subject: Retry:Question about optparse/OptionParser callback. References: Message-ID: Steven W. Orr wrote: > I decided I could be more articulate. I hope this helps. In case James did not guess right: try to provide more details about /what/ you want to achieve rather than /how/ you want to get there. And please don't open a third thread for it. Peter From etatoby at gmail.com Sun Feb 25 16:12:21 2007 From: etatoby at gmail.com (Toby) Date: 25 Feb 2007 21:12:21 GMT Subject: How to build Hierarchies of dict's? (Prototypes in Python?) References: <45e06bab$0$20809$5fc30a8@news.tiscali.it> <45e17ec0$0$20813$5fc30a8@news.tiscali.it> Message-ID: <45e1fbb4$0$20823$5fc30a8@news.tiscali.it> Charles D Hixson wrote: > I want to access the values via instances of the class, so your D().a > approach isn't suitable. More like: "t = D(); t[a]" Well, D() is an instance of D, so D().a is the same as t = D(); t.a In fact the various "a" attributes I'm accessing are class attributes of the various classes, just as you asked. If you'd rather use t[a], then things are simpler, because you won't need to override __getattribute__, with all the ugliness that comes with it: __getitem__ will suffice. > Your approach uses techniques that I'm going to need to study > carefully before I can hope to understand them. Don't worry, here's a heavily commented version, just because it's sunday and I have some free time ;-) # inheriting from object so that we can use __getattribute__ # see http://www.python.org/download/releases/2.2.3/descrintro/ class AttrSearch(object): '''Base class that customizes attribute access in all of its derived classes, choosing between all the candidates in a custom way.''' @classmethod def getclassattrset(cls, name): '''Class method (= polymorphic static method) that collects a set of the attributes with a given name from itself and from all its base classes (determined at runtime.) The only argument is the name of the attribute to look up; the return value is a list of (class_name, attribute_value) listing all the candidates found.''' # note: the first parameter 'cls' is the class of the runtime object # on which this class method is called, much like 'self' is the # object instance in instance methods # # notice: this method is defined on class AttrSearch, but if I call # it on B (subclass of AttrSearch), then 'cls' is class B! s = set() # a set is an unordered list without duplicates try: # __dict__ is the internal dictionary which holds all of a class # or of an instance's attributes # creating a tuple with the name of the runtime class 'cls' # and the value of cls's attribute named name, and adding the # tuple to the set (unless an equal tuple is already there) s.add((cls.__name__, cls.__dict__[name])) except KeyError: # ...unless the class cls has no such attribute pass # for every base class, from which the runtime class inherits: for base in cls.__bases__: try: # call this same method on them and add their results to the set s.update(base.getclassattrset(name)) except AttributeError: # except for the base classes which don't implement this method # (for example the class object) pass return s # returning the collected set def getattrset(self, name): '''Instance method that collects a set of the attributes with a given name from itself, from its class and from all the base classes. The only argument is the name of the attribute to look up; the return value is a list of (class_name, attribute_value) listing all the candidates found. In case the attribute is also found in the object itself, element 0 of the tuple is set to null.''' # saving references to a couple of attributes we need to access # directly, bypassing all this machinery; to achieve it, we # explicitly call object's implementation of __getattribute__ self_dict = object.__getattribute__(self, '__dict__') self_class = object.__getattribute__(self, '__class__') s = set() try: # adding to the set the attribute named name in this very intance, # if it exists, with None in place of the class name s.add((None, self_dict[name])) except KeyError: # unless the instance doesn't have an attribute named name pass # addig to the set all the class attributes named name, from this # object's class and all its base classes s.update(self_class.getclassattrset(name)) return s def __getattribute__(self, name): '''Customized version of attribute fetching, that uses getattrset (and thus getclassattrset) to get a list of all the attributes named name before choosing which one to return.''' # saving references to the attributes we need to access directly self_class = object.__getattribute__(self, '__class__') # calling AttrSearch's getattrset to do the dirty work found = AttrSearch.getattrset(self, name) # here is where you should examine 'found' and choose what to # return; I only print what is available and return None print 'Looking for "%s" in a %s instance, found %d candidates:' \ % (name, self_class.__name__, len(found)) print ' class value' print ' ===== =====' print '\n'.join([ " %-6s '%s'" % x for x in found ]) print '(now choose wisely what to return)' return None # example use of AttrSearch in a class hierarchy: class A(AttrSearch): a = 'attribute "a" of class A' class B(A): a = 'attribute "a" of class B' class C(A): a = 'attribute "a" of class C' class D(B, C): a = 'attribute "a" of class D' t = D() t.a = 'attribute "a" of instance t' # --- end --- Now if you ask for t.a, for example in a print statement, you get None, but not before the following lines are printed to stdout: Looking for "a" in a D instance, found 5 candidates: class value ===== ===== D 'attribute "a" of class D' B 'attribute "a" of class B' A 'attribute "a" of class A' None 'attribute "a" of instance t' C 'attribute "a" of class C' (now choose wisely what to return) HTH Toby PS: I couldn't make out what you meant with your code... I fear it's because of the hideous formatting :-) From srikanth.allu at gmail.com Sun Feb 11 20:47:30 2007 From: srikanth.allu at gmail.com (mech point) Date: 11 Feb 2007 17:47:30 -0800 Subject: Read/write 2D data from/to file..? Message-ID: <1171244850.077289.130330@s48g2000cws.googlegroups.com> I was able to read the data from file into a two dimensional array (lists) rows=[map(float,line.split())for line in file("data")] but How to write them back into the file. Thank you, srikanth From thorsten at thorstenkampe.de Sat Feb 10 09:35:37 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 10 Feb 2007 14:35:37 -0000 Subject: How to find all the same words in a text? References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: * Johny (10 Feb 2007 05:29:23 -0800) > I need to find all the same words in a text . > What would be the best idea to do that? > I used string.find but it does not work properly for the words. > Let suppose I want to find a number 324 in the text > > '45 324 45324' > > there is only one occurrence of 324 word but string.find() finds 2 > occurrences ( in 45324 too) > > Must I use regex? There are two approaches: one is the "solve once and forget" approach where you code around this particular problem. Mario showed you one solution for this. The other approach would be to realise that your problem is a specific case of two general problems: partitioning a sequence by a separator and partioning a sequence into equivalence classes. The bonus for this approach is that you will have a /lot/ of problems that can be solved with either one of these utils or a combination of them. 1>>> a = '45 324 45324' 2>>> quotient_set(part(a, [' ', ' '], 'sep'), ident) 2: {'324': ['324'], '45': ['45'], '45324': ['45324']} The latter approach is much more flexible. Just imagine your problem changes to a string that's separated by newlines (instead of spaces) and you want to find words that start with the same character (instead of being the same as criterion). Thorsten From http Wed Feb 7 23:17:06 2007 From: http (Paul Rubin) Date: 07 Feb 2007 20:17:06 -0800 Subject: 'IF' Syntax For Alternative Conditions References: Message-ID: <7x3b5h7071.fsf@ruckus.brouhaha.com> rshepard at nospam.appl-ecosys.com writes: > if cond1: > if cond2: > do_something. You can write: if cond1 and cond2: do_something > if cond1 OR if cond2: > do_something. if cond1 or cond2: do_something > I've tried using the C syntax for OR (||) but python complained. I'm sure > there's a way to do this rather than using if cond1: elif cond2: both with > the same code to execute. Python uses the "and" and "or" keywords for && and ||. From donn at u.washington.edu Fri Feb 16 14:15:49 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 16 Feb 2007 11:15:49 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> Message-ID: In article <7xfy97uhv0.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Donn Cave writes: > > If t is a valid argument tuple for function f, then can t[1:] > > also be a valid argument tuple for function f? > > > > For ordinary functions without special argument handling, no. > > We know that without having to know anything about t, and not > > much about f. This is characteristic of tuple applications. > > I'm not sure what you're saying. The current situation is if I say > > def f(*args): > print args > > f (1,2,3,4,5,6,7) > > f receives a 7-element tuple, but if I say > > f (8, 9, 10) > > f receives a 3-element tuple. OK, and of course - f has some implementation which assigns meaning to each parameter, according to its position. - it does this by assigning names to those positions (this isn't essential to my point, but reinforces the struct analogy) For any basic, no-tricks implementation of f, the second application is going to have problems: - fourth and following positions have no actual parameters - if you meant to portray (8, 9, 10) as t[4:], where t is (_, _, _, _, 8, 9, 10), following my proposition above, then it should be clear that inasmuch as t[4] for example has some meaning in terms of f, one cannot preserve this meaning in a smaller slice of t. Please think about it, because I do not intend to try to explain this again. So the parameters of f form a sort of type -- an ordered sequence of values, where each item has a different meaning according to its absolute position in the sequence, and where a name is assigned (by at least f and optionally by its caller) to each position. This type can be represented by many possible values, but we can observe that just as a matter of principle, for any value of this type, a smaller slice is not also of this type. Of course the word "type" above is about something that is not formally implemented in Python, so you can obtusely quibble about whether it's a type or not, but the constraints are real. > I'm asking whether f should receive a list instead. I think that is > more in keeping with the notion of a tuple being like a structure > datatype. How can there be a structure datatype with an unpredictable > number of members? Unpredictable? How do you manage to write functions in this case? Are all your formal parameter lists like (*a), with logic to deal with the variable lengths? But even that wouldn't by itself make your point. Any experienced C programmer is likely to have "subtyped" a struct, adding one or more values to the end of the parent struct, so the value can be passed to functions that expect the parent type. Variable length isn't strictly foreign to struct types. Donn Cave, donn at u.washington.edu From exarkun at divmod.com Mon Feb 5 11:15:57 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 Feb 2007 11:15:57 -0500 Subject: when will python 2.5 take in mainstream? In-Reply-To: Message-ID: <20070205161557.25807.2114739552.divmod.quotient.10899@ohm> On Mon, 05 Feb 2007 17:07:15 +0100, Laurent Pointal wrote: >Jean-Paul Calderone a ?crit : >> On Mon, 05 Feb 2007 10:19:26 +0100, Laurent Pointal >> wrote: >>> tleeuwenburg at gmail.com a ?crit : >>>> When they have to ... >>>> >>>> One of the big things about Python is that its penetration slows it >>>> down. There's more legacy code and interdependant systems around now >>>> that Python is more successful and more mature. >>>> >>>> Here's a thought -- perhaps it would be worth having some good ways to >>>> interact with Python from Python. Suppose you have some 2.4 code >>>> someplace, interacting with your mysqldb or whatever, and you don't >>>> want to rewrite it. So long as you have some kind of object broker, >>>> you could (plausibly) leave your 2.4 apps running with the old >>>> interpreter, but wrap them for Python 2.5 and use that in your new >>>> development. >>> >>> KISS please. >>> >> >> Requiring change is simpler than not requiring change? >> Okay, perhaps >> you could make a case, but it's far from obvious this is always true. >> > >IMHO trying to have a binary compatibility with older compiled modules >by maintaining an ad-hoc layer to switch between 2.4/2.5 engines make >Python code more complex. And more complex code have generally more >bugs. This is the reason for my KISS hope about Python. > >Its simple to require changes, not so sure that doing these >modifications keep things simple. Maybe an internal Python hacker can >give us his advice on such a modification (ie. staying compatible with >legacy modules compiled for previous versions). > It's very easy to maintain compatibility in the C API. I'm much more interested in compatibility at the Python layer, which is changed incompatibly much, much more frequently than is the C layer. Anyway, you didn't address my point. Maintaining compatibility in Python itself might be more complex than not maintaining complexity. But _not_ maintaining compatibility just pushes the complexity into every program and library written with Python. Which one of these things do you think results in more developer time being spent? (Hint: it's the 2nd one.) Don't mistake this for advocacy that Python never break any compatibility. Whether or not I think that is the case is unrelated to whether or not it is useful to understand and admit all of the costs associated with breaking compatibility. Jean-Paul From michele.simionato at gmail.com Wed Feb 7 10:48:25 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 Feb 2007 07:48:25 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: References: <45C9A137.8090009@v.loewis.de> Message-ID: <1170863305.476942.318420@s48g2000cws.googlegroups.com> > Martin v. L?wis schrieb: > > > > > I'm happy to announce partial 1.0; a module to implement > > partial classes in Python. It is available from > > >http://cheeseshop.python.org/pypi/partial/1.0 > > > A partial class is a fragment of a class definition; > > partial classes allow to spread the definition of > > a class over several modules. One location serves > > as the original definition of the class. This looks the same as Ruby classes, right? I don't like class definitions to be scattered in different files, for the same reason I don't like excessive inheritance, it is too easy to get lost when debugging code written by somebody else. But probably I am just overreacting due to my exposure to Zope ... Michele Simionato From gdamjan at gmail.com Sat Feb 17 15:31:07 2007 From: gdamjan at gmail.com (Damjan) Date: Sat, 17 Feb 2007 21:31:07 +0100 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <87fy965plq.fsf@benfinney.id.au> <1171738855.785792@bubbleator.drizzle.com> Message-ID: <45d7668c$0$90264$14726298@news.sunsite.dk> > | > If a programmer decides on behalf of the user that "localhost" should > | > be treated specially, that programmer is making an error. > | > | Inter-process TCP/IP communication between two processes on the same > | host invariably uses the loopback interface (network 127.0.0.0). > | According to standards, all addresses in that network space refer to the > | local host, though 127.0.0.1 is conventionally used. > | > | The transmit driver for the loopback interface receives a datagram from > | the local network layer and immediately announces its reception back to > | the local network layer. > > Are you saying, in that first paragraph, that if for example I telnet to > my local host's external IP address, to a service that bound explicitly to > the external interface -- I'll actually be going through the loopback > interface anyway, invariably regardless of host network implementation? On linux at least, this is true, yes. -- damjan From sjmachin at lexicon.net Mon Feb 12 02:20:11 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 23:20:11 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: <1171264811.509582.224870@p10g2000cwp.googlegroups.com> On Feb 12, 4:24 pm, Samuel Karl Peterson wrote: > C-like way to do it, (warning, untested in python): > > for i in range(8): > for j in range(8): > for offset_i in range(-1,2): > for offset_j in range(-1, 2): > row = i + offset_i > col = j + offset_j > if (row < 0 or row > 7) or (col < 0 or col > 8) \ > or ((row,col) == (i,j)): > continue > # else do something with board[row][col] > > I realize this is gross and un-Pythonic and does the same thing It's also just a little bit inefficient. Never mind the algorithm, we'll talk about that later. Let's just improve the code a little: side_range = range(8) delta_range = range(-1, 2) for i in side_range: for offset_i in delta_range: row = i + offset_i if not (0 <= row <= 7): continue for j in side_range: for offset_j in delta_range: if not offset_i and not offset_j: continue col = j + offset_j if not(0 <= col <= 7): continue # *now* it's safe to do something # with (row, col) Such hoisting of code out of inner loops is done for you by a C compiler -- Python assumes you know what you are doing :-) Now for the algorithm: all of that testing to see if you are about to sail off the end of the world is a bit ugly and slow. You can use bit- bashing, as Paul suggested, even though it's on Steven D'Aprano's list of 6 deadly sins :-) Another approach that has been used is to have a 9 x 9 storage area; the squares off the edge contain a value that is neither "empty" nor any value that represents a piece. So with careful coding, they automatically fail tests like "can I capture the piece on this square" [no, it's not a piece] and "can I move here" [no, it's not empty]. If the game is chess, you need 10 x 10 to cater for those pesky knights. Cheers, John From mail at timgolden.me.uk Tue Feb 27 02:34:09 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 27 Feb 2007 07:34:09 +0000 Subject: How can I disable a device in windows using python In-Reply-To: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> References: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> Message-ID: <45E3DEF1.8030503@timgolden.me.uk> Phoe6 wrote: > Hi all, > I am trying to disable the NIC card (and other cards) enabled in my > machine to test diagnostics on that card. > I am trying to disable it programmatic using python. I checked python > wmi and i could not find ways to disable/enable, (listing is however, > possible). Since you mention WMI I'm going to assume you're on Windows (although if you hadn't we'd have had no idea!). Running the terms: wmi disable network card past Google came up with this page: http://channel9.msdn.com/ShowPost.aspx?PostID=158340 where the first answer to the question "Is there any way to programatically disable an NIC" points us to this page: http://www.mcpmag.com/columns/article.asp?EditorialsID=619 which uses the Shell application object to automate the control panel (and, by the way, I'd no idea you could do this). You should be able to recreate this fairly easily from Python using the pywin32 extensions, and in particular the win32com.client tools. To get you started: import win32com.client shell = win32com.client.Dispatch ("Shell.Application") control_panel = shell.Namespace (3) for item in control_panel.Items (): if item.Name == "Network and Dial-up Connections": network_connections = item break else: raise Exception ("networking not found") # you now have the networking item TJG From nogradi at gmail.com Sun Feb 25 15:45:43 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 25 Feb 2007 21:45:43 +0100 Subject: Help on Dict In-Reply-To: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> References: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> Message-ID: <5f56302b0702251245h239bdb0wec40bb28f36b6af8@mail.gmail.com> > Can any body tell how Dict is implemented in python... plz tell what > datastructure that uses................ Please see http://svn.python.org/view/python/trunk/Objects/dictnotes.txt?rev=53782&view=markup for general notes and http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=53911&view=markup for the actual implementation. HTH, Daniel From __peter__ at web.de Mon Feb 19 05:25:28 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 11:25:28 +0100 Subject: timeout in urllib.open() References: Message-ID: Stefan Palme wrote: > is there a way to modify the time a call of > > urllib.open(...) > > waits for an answer from the other side? Have a tool > which automatically checks a list of websites for > certain content. The tool "hangs" when one of the > contacted websites behaves badly and "never" answers... I believe this can only be set globally: import socket socket.setdefaulttimeout(seconds) Peter From bignose+hates-spam at benfinney.id.au Thu Feb 15 14:26:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Feb 2007 06:26:51 +1100 Subject: f---ing typechecking References: Message-ID: <87hctn6x38.fsf@benfinney.id.au> James Stroud writes: > I increasingly come to the decision to avoid tuples altogether > because, eventually, you end up turning them into lists anyway I don't. I end up extracting them to separate variables. >>> foo = (12, None, "spam") >>> # ... >>> # much code, perhaps passing foo around as parameter >>> # ... >>> (bar, baz, wibble) = foo >>> # code using bar, baz, and/or wibble If they are eventually extracted to lists, then it generally makes no sense for them ever to begin as a tuple. -- \ "I have an answering machine in my car. It says, 'I'm home now. | `\ But leave a message and I'll call when I'm out.'" -- Steven | _o__) Wright | Ben Finney From blancmunier1 at yahoo.FR Thu Feb 1 05:15:50 2007 From: blancmunier1 at yahoo.FR (blancmunier1 at yahoo.FR) Date: 1 Feb 2007 02:15:50 -0800 Subject: retrbinary ! how does it work ? In-Reply-To: References: <1170321454.210348.91370@a75g2000cwd.googlegroups.com> Message-ID: <1170324950.045282.192480@h3g2000cwc.googlegroups.com> Thanks a lot Diez and Gabriel. It works perfectly ! Have a nice day Yvan From TheOneRedDragon at gmail.com Sat Feb 10 06:37:36 2007 From: TheOneRedDragon at gmail.com (TheOneRedDragon at gmail.com) Date: 10 Feb 2007 03:37:36 -0800 Subject: Wait for keypress Message-ID: <1171107456.651569.101680@q2g2000cwa.googlegroups.com> At the moment, I have a command-line application which prints out quite a lot of text to the screen. However, when Windows users run it, the prompt disappears before they can read any of it. Is there any simple way to make a script wait for a keypress before completing? Thanks for any help. From liuwensui at gmail.com Tue Feb 27 10:09:57 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Tue, 27 Feb 2007 10:09:57 -0500 Subject: book for a starter Message-ID: <1115a2b00702270709i4363557etbbc6bb424af71561@mail.gmail.com> Good morning, all, I just start learning python and have a question regarding books for a newbie like me. If you are only allowed to buy 1 python book, which one will you pick? ^_^. Thank you so much! From gagsl-py at yahoo.com.ar Thu Feb 15 20:18:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 22:18:58 -0300 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 22:04:34 -0300, Edward K Ream escribi?: > In other words, the consequence of pep 3105 will be that *nobody* who > wants > their app to be portable will be able to use print until *everybody* has > converted to Python 3.x. I doubt that is what Guido had in mind, but I > may > be mistaken :-) print is nice, and has a few advantages (like its own opcode!), and I use it a lot on the interactive interpreter, but I almost never use it in production code. -- Gabriel Genellina From aleaxit at gmail.com Wed Feb 28 14:36:35 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 28 Feb 2007 11:36:35 -0800 Subject: gmpy moving to code.google.com In-Reply-To: References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> Message-ID: <1172691395.635962.90050@j27g2000cwj.googlegroups.com> On Feb 27, 9:10 am, "Daniel Nogradi" wrote: > > > Hi Alex, > > > > I did another test, this time with python 2.4 on suse and things are > > > worse than in the previous case (which was python 2.5 on fedora 3), > > > ouput of 'python gmp_test.py' follows: > > > Interesting! gmpy interacts with decimal.Decimal by "monkey- > > patching" that class on the fly; clearly the monkey-patching isn't > > working with 2.4 on SuSE, so all the addition attempts are failing > > (all 6 of them). > > > So the issue is finding out why this strategy is failing there, while > > succeeding on other Linux distros, Mac, and Windows. > > > To that end, I have added a feature in the latest svn trunk (revision > > 11) to set gmpy's own options.debug flag from an environment variable > > named GMPY_DEBUG at startup (if that environment variable is set). > > > If you could please svn up and rebuild, then running with GMPY_DEBUG > > set in the environment should give something like: > > > brain:~/gmpy alex$ GMPY_DEBUG=1 python -c 'import gmpy' 2>&1 | tail -5 > > mp_allocate( 4->8 ) > > mp_allocate( 4->8 ) ->0x60b8b0 > > gmpy_module at 0x63390 > > gmpy_module imported decimal OK > > gmpy_module tweaked decimal OK > > > This is the expected behavior when module decimal is present, while, > > when it's absent, you should see something like: > > > brain:~/gmpy alex$ GMPY_DEBUG=1 python2.3 -c 'import gmpy' 2>&1 | > > tail -5 > > Initing new not in zcache > > mp_allocate( 4->8 ) > > mp_allocate( 4->8 ) ->0x3017d0 > > gmpy_module at 0x6de70 > > gmpy_module could not import decimal > > > In each case, what matters is the last line or two after "gmpy_module > > at" -- the rest of the copious debugging output is irrelevant here. > > > Module decimal is expected to be present from 2.4 forward (though it > > could also be explicitly installed on 2.3). However, from the test > > failures you report, it looks like SuSE's 2.4 does not have decimal > > available for importing when gmpy is starting up -- so I'd like to > > confirm that first. > > > If it's confirmed, it will be interesting to discover how this > > happens (but that requires a SuSE installation, which I don't have) > > and secondarily what is gmpy to do about it -- maybe offer a warning > > on startup when module decimal is unexpectedly not importable but > > then skip the relevant unittests in that case? (Note that the tests > > ARE already skipped if module decimal is not importable _at test > > time_ -- what's really weird is that apparently on SuSE decimal CAN > > be imported by the tests but CANNOT be imported earlier while gmpy is > > loading, which is truly puzzling). > > > I'd appreciate reports about this behavior on as many Python/Linux > > installations as possible -- yours, of course (to check my guess that > > the problem is that decimal can't be imported while gmpy is loading), > > but also others' (to see how widespread the problem is, etc, etc). > > > Thanks again for reporting this, and thanks in advance to anybody > > who'll lend a hand in tracking down this little strangeness!!! > > Okay, here is a summary. The notation is: > > platform version python version debug unittest > > where debug will be either 'pass' or 'fail' if that particular > platform and python version passes or fails the GMPY_DEBUG=1 > importing/tweaking test. Unittest will also be 'pass' or 'fail' if the > full unittesting passes or fails respectively. > > Fedora 3 python 2.5 pass pass > Fedora 3 python 2.4 pass fail > Fedora 3 python 2.3.4 fail pass > Suse 9.3 python 2.4 pass fail > Suse 10 python 2.4.1 pass pass > Suse 10.2(64bit) python 2.5 pass fail > > The output from each test is zipped and you can grab it from here:http://lorentz.leidenuniv.nl/~nogradi/gmpy_test.zip Thanks for all the testing! So, Ziga's next post explains that the 2.4 problems are 2.4.0 bugs fixed since 2.4.1 -- I don't think I can do anything about in gmpy, nor (I think) even if I could should I go to great complications to support old, known-buggy, easily upgradable (I hope) releases of Python. The 2.5 issues have nothing to do with decimal -- they _do_ have to do with 64-bit builds: For the hash(z) issue, I think I know what to do -- instead of claiming I know what the hash value should be (which clearly I don't when it can be either a 32-bit or 64-bit build:-), I'll just claim that the hash value of z is the same as the the hash value of long(z). I have svn committed that change (svn repository for gmpy is now at revision 14) -- could you please svn up and run the tests again (ideally after updating the Python 2.4 installations to 2.4.1 or better, but that's minor, what I'd really need to see would be the results on the 64-bit build... thanks! I _am_ a bit surprised at the other failure, the one of: ix(_g.mpz(sys.maxint)) == sys.maxint where ix is operator.index -- particularly considering that the other tests around that one succeed (e.g., the identical one using sys.maxint + 1). Maybe that's an actual bug of 1.02 on a 64-bit build of Python. Could you please tell me, on that 64-bit build, what happens with: >>> import gmpy, sys, operator >>> sys.maxint ??? >>> gmpy.mpz(sys.maxint) ??? >>> operator.index(gmpy.mpz(sys.maxint)) ??? >>> sys.maxint+1 ??? >>> gmpy.mpz(sys.maxint+1) ??? >>> operator.index(gmpy.mpz(sys.maxint)+1) ??? i.e., what are the values correspondiing to the ??? occurrences when you actually do that...? Thanks again Alex From steveo at syslang.net Thu Feb 1 13:15:19 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 1 Feb 2007 13:15:19 -0500 (EST) Subject: Question about a single underscore. In-Reply-To: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> References: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> Message-ID: On Thursday, Feb 1st 2007 at 09:25 -0800, quoth Bart Ogryczak: =>On Feb 1, 5:52 pm, "Steven W. Orr" wrote: =>> I saw this and tried to use it: =>> =>> ------------------><8------------------- const.py------------- =>[...] =>> sys.modules[__name__]=_const() => =>__name__ == 'const', so you?re actually doing =>const = _const() So how can I say this in const.py? class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__[name]=value def __init__(self): sys.modules[self]=_const() import sys to cause a different instantiation a la foo = _const() The goal would be to create different instances of consts. I did try the previous suggestion irrational_consts = _const() but I got >>> import const >>> iii=_const() Traceback (most recent call last): File "", line 1, in ? NameError: name '_const' is not defined *>>> iii=const() Traceback (most recent call last): File "", line 1, in ? AttributeError: _const instance has no __call__ method ------------ For ref: class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__[name]=value import sys sys.modules[__name__]=_const() -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From http Wed Feb 28 16:46:41 2007 From: http (Paul Rubin) Date: 28 Feb 2007 13:46:41 -0800 Subject: Yet another unique() function... References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <1172647505.784091.193710@q2g2000cwa.googlegroups.com> <7x7iu2niif.fsf@ruckus.brouhaha.com> <1172697024.754286.325450@m58g2000cwm.googlegroups.com> <1172698992.142640.55250@z35g2000cwz.googlegroups.com> Message-ID: <7xtzx6oszi.fsf@ruckus.brouhaha.com> "MonkeeSage" writes: > In your case optimized version, in the second try clause using > itertools, it should be like this, shouldn't it? > > return t(g.next()[1] for k,g in groupby(s, lambda (i,v): v)) I didn't think so but I can't conveniently test it for now. Maybe tonight. From bdesth.quelquechose at free.quelquepart.fr Fri Feb 16 17:12:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 16 Feb 2007 23:12:52 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <45d624f7$0$10573$426a74cc@news.free.fr> ifti_crazy at yahoo.com a ?crit : > I am VB6 programmer and wants to start new programming language but i > am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language "GUI based programming languages" ? What's that ? > like VB.net > > so will you please guide me which GUI based language has worth with > complete OOPS Characteristics "complete OOPS Characteristics" ? What's that ? Visual C++ is not a language, it's a (proprietary, non portable) implementation of a language named C++. Ruby and Python are both hi-level, object-oriented languages, and both have bindings to the main GUI toolkits. These GUI toolkits usually have language-independant GUI designers. For the programming part, you're free to choose whatever editor you like. Both Python and Ruby are worth learning. Since both have open-source implementations, you can easily try them for yourself and choose the one you like best. Now I don't know what's the situation for Ruby, but - since you seem to be mostly on the MS side -, Python has a pretty good integration with Windows (COM programming and scripting, Win32 API bindings etc), and is usually a better choice than VB for this j=kind of tasks. Note also that there's IronPython (Python for .NET). HTH From ptmcg at austin.rr.com Sun Feb 11 17:34:28 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 Feb 2007 14:34:28 -0800 Subject: Parsing HTML In-Reply-To: <1171148616.780656.13230@m58g2000cwm.googlegroups.com> References: <1171148616.780656.13230@m58g2000cwm.googlegroups.com> Message-ID: <1171233267.997784.321000@a75g2000cwd.googlegroups.com> On Feb 10, 5:03 pm, "mtuller" wrote: > Alright. I have tried everything I can find, but am not getting > anywhere. I have a web page that has data like this: > > > > LETTER > > 33,699 > > 1.0 > > > > What is show is only a small section. > > I want to extract the 33,699 (which is dynamic) and set the value to a > variable so that I can insert it into a database. I have tried parsing > the html with pyparsing, and the examples will get it to print all > instances with span, of which there are a hundred or so when I use: > > for srvrtokens in printCount.searchString(printerListHTML): > print srvrtokens > > If I set the last line to srvtokens[3] I get the values, but I don't > know grab a single line and then set that as a variable. > So what you are saying is that you need to make your pattern more specific. So I suggest adding these items to your matching pattern: - only match span if inside a with attribute 'headers="col2_1"' - only match if the span body is an integer (with optional comma separater for thousands) This grammar adds these more specific tests for matching the input HTML (note also the use of results names to make it easy to extract the integer number, and a parse action added to integer to convert the '33,699' string to the integer 33699). -- Paul htmlSource = """ LETTER 33,699 1.0 """ from pyparsing import makeHTMLTags, Word, nums, ParseException tdStart, tdEnd = makeHTMLTags('td') spanStart, spanEnd = makeHTMLTags('span') def onlyAcceptWithTagAttr(attrname,attrval): def action(tagAttrs): if not(attrname in tagAttrs and tagAttrs[attrname]==attrval): raise ParseException("",0,"") return action tdStart.setParseAction(onlyAcceptWithTagAttr("headers","col2_1")) spanStart.setParseAction(onlyAcceptWithTagAttr("class","hpPageText")) integer = Word(nums,nums+',') integer.setParseAction(lambda t:int("".join(c for c in t[0] if c != ','))) patt = tdStart + spanStart + integer.setResultsName("intValue") + spanEnd + tdEnd for matches in patt.searchString(htmlSource): print matches.intValue prints: 33699 From arkanes at gmail.com Tue Feb 6 12:44:00 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Feb 2007 11:44:00 -0600 Subject: when will python 2.5 take in mainstream? In-Reply-To: <1170780389.535028.60400@j27g2000cwj.googlegroups.com> References: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> <1170780389.535028.60400@j27g2000cwj.googlegroups.com> Message-ID: <4866bea60702060944l20f7813ek83c0a83b36a62cac@mail.gmail.com> On 6 Feb 2007 08:46:29 -0800, Ben Sizer wrote: > On Feb 6, 3:35 pm, a... at pythoncraft.com (Aahz) wrote: > > Ben Sizer wrote: > > > > >It would be great if someone could invest some time in trying to fix > > >this problem. I don't think I know of any other languages that require > > >recompilation of libraries for every minor version increase. > > > > How do you define "minor version increase"? If you look at the > > progression from 2.0 through 2.5, it's pretty clear that each version > > doesn't particularly fit "minor version increase" even though each one > > only increments by 0.1. > > I can't say I agree with that. In terms of naming, it's a minor > release because the 'major' release number has stayed at 2. In terms > of time, it's a minor release because it's only happening about once > every 18 months or so - a short period in computer language terms. In > terms of semantics, I'd argue they are minor releases because > generally the changes are just minor additions rather than large > revisions; I don't see much in the way of significant language > alterations for 2.5 apart from arguably 'unified try/except/finally', > nor in 2.4. I don't count addition of new types or modules as 'major'. > The language itself is fairly stable; it's just the way that it links > to extensions which is pretty fragile. > > -- > Ben Sizer > You're claiming that it's a minor increase because you didn't see anything that "justifies" a major release. Well, the ABI changed, so there you go. It doesn't really matter what you call it - the Python releases are numbered according to their own rules, and if you disagree you can call 2.5 a major release all you want. Or you can call it a minor release and accept that the ABI changes between minor releases. But making up your own release rules and arguing from those is pretty much a non-starter. From bruno.desthuilliers at gmail.com Thu Feb 15 08:00:07 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 15 Feb 2007 05:00:07 -0800 Subject: Method overloading? In-Reply-To: References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> Message-ID: <1171544407.170495.31680@a34g2000cwb.googlegroups.com> On 15 f?v, 09:32, "Troy Melhase" wrote: > On 14 Feb 2007 20:54:31 -0800, placid wrote: > > > class Test: > > def __init__(self): > > pass > > > def puts(self, str): > > print str > > > def puts(self, str,str2): > > print str,str2 > > you might look into the overloading module and its decorator. source > is in the sandbox: > > http://svn.python.org/view/sandbox/trunk/overload/overloading.py > Or have a look at Philip Eby's dispatch package, which is kind of overloading on steroids... From openopt at ukr.net Thu Feb 22 13:04:01 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 22 Feb 2007 10:04:01 -0800 Subject: JIT (just-in-tme accelerator) for Python - exists or no? Message-ID: <1172167441.845600.154270@s48g2000cws.googlegroups.com> Or is any progress going on now? The JIT in MATLAB or Java seems to be very effective. From deets at nospam.web.de Sun Feb 25 10:34:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 Feb 2007 16:34:53 +0100 Subject: convert strings to utf-8 In-Reply-To: References: Message-ID: <54doljF20aq9hU1@mid.uni-berlin.de> Niclas schrieb: > Hi > > I'm having trouble to work with the special charcters in swedish (? ? ? > ? ? ?). The script is parsing and extracting information from a webpage. > This works fine and I get all the data correctly. The information is > then added to a rss file (using xml.dom.minidom.Document() to create the > file), this is where it goes wrong. Letters like ? ? ? get messed up and > the rss file does not validate. How can I convert the data to UTF-8 > without loosing the special letters? Show us code, and example text (albeit I know it is difficult to get that right using news/mail) The basic idea is this: scrapped_byte_string = scrap_the_website() output = scrappend_byte_string.decode('website-encoding').encode('utf-8') Diez From paul at eventuallyanyway.com Mon Feb 12 20:34:00 2007 From: paul at eventuallyanyway.com (Paul Hummer) Date: Tue, 13 Feb 2007 01:34:00 +0000 Subject: Newbie Question In-Reply-To: <342d7$45d0c389$d443bb3a$9252@news.speedlinq.nl> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> <53bqoaF1rlgkqU1@mid.individual.net> <342d7$45d0c389$d443bb3a$9252@news.speedlinq.nl> Message-ID: <45D11588.40104@eventuallyanyway.com> Stef Mientki wrote: > Oh I forgot that, ... > ... in Delphi you don't have to choose ;-) Dang it! I hate it when they give me choices like that! Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Feb 26 23:41:53 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 27 Feb 2007 15:41:53 +1100 Subject: how to call os.path.join() on a list ... References: <1172549038.422389.296920@q2g2000cwa.googlegroups.com> Message-ID: <87zm70yzxq.fsf@benfinney.id.au> "funkyj" writes: > I want to call os.path.join() on a list instead of a variable list of > arguments. I.e. > > [...] > >>> import os > >>> import string > >>> p = os.environ['PWD'] > >>> p > '/tmp/a/b/c/d' > >>> os.path.join(string.split(p, os.sep)) > ['', 'tmp', 'a', 'b', 'c', 'd'] > >>> > > the value returned by os.path.join() is obviously not the desired > result ... Nor is the value returned by the string 'split' function quite what you describe. >>> p.split(os.sep) ['', 'tmp', 'a', 'b', 'c', 'd'] >>> os.path.split(p) ('/tmp/a/b/c', 'd') > [...] > What is the python idiom for callling a function like os.path.join() > that takes a variable number of arguments when you currently have > the arguements in a list variable? >>> import os >>> p = ["/tmp", "a", "b", "c", "d"] >>> os.path.join(*p) '/tmp/a/b/c/d' "funkyj" writes: > I can just do: > > os.sep.join(string.split(p, os.sep)) > > it isn't "funcall" but it gets me where I want to go. It also isn't 'os.path.join'. >>> p = ["/tmp", "a", "b/", "c/", "d"] >>> os.sep.join(p) '/tmp/a/b//c//d' >>> os.path.join(*p) '/tmp/a/b/c/d' -- \ "Never use a long word when there's a commensurate diminutive | `\ available." -- Stan Kelly-Bootle | _o__) | Ben Finney From gonzlobo at gmail.com Sun Feb 4 22:56:08 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Sun, 4 Feb 2007 20:56:08 -0700 Subject: Decimating Excel files In-Reply-To: References: Message-ID: Excellent suggestion. I'm going with xlrd! Thanks > I've had good luck with xlrd. It does not require using COM, Excel, or even Windows! > http://www.lexicon.net/sjmachin/xlrd.htm > Robert Kern From gagsl-py at yahoo.com.ar Sun Feb 18 03:17:38 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Feb 2007 05:17:38 -0300 Subject: Getting a class name References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> Message-ID: En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf escribi?: > I suppose that you wont get class name into its code (or before > definition end) but not into a method definition. > > > import sys > > def getCodeName(deap=0): > return sys._getframe(deap+1).f_code.co_name > > > class MyClass (object): > name = getCodeName() + '!' What's the advantage over MyClass.__name__? -- Gabriel Genellina From ptmcg at austin.rr.com Thu Feb 15 19:04:14 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Feb 2007 16:04:14 -0800 Subject: f---ing typechecking In-Reply-To: <7xfy97uhv0.fsf@ruckus.brouhaha.com> References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> Message-ID: <1171584254.805386.97300@a75g2000cwd.googlegroups.com> On Feb 15, 5:21 pm, Paul Rubin wrote: > How can there be a structure datatype with an unpredictable > number of members? > > It might have come across as a different question-sorry for any > confusion. This may be where the "tuple is like a struct" analogy isn't so good, and "tuple is like a list but immutable" is better. In both of your examples, the caller of f() sent a fixed list of arguments: (1,2,3,4,5,6,7) in the first case and (8,9,10) in the second. Internally I bet the compiler wants to clean up that same list of those same args when f() is finished. Just as a thought experiment, do this for yourself. Implement f as: def f(*args): args = list(args) print args Now what is it you want to do with args that you can't do with it as a tuple? Do you want some form of communication back to the caller to occur, for example? Maybe some kind of pass-by-ref instead of pass-by- value? -- Paul From sjmachin at lexicon.net Sat Feb 3 18:37:11 2007 From: sjmachin at lexicon.net (John Machin) Date: 3 Feb 2007 15:37:11 -0800 Subject: .pth configuration method not working In-Reply-To: <1170543783.843044.22670@k78g2000cwa.googlegroups.com> References: <1170543783.843044.22670@k78g2000cwa.googlegroups.com> Message-ID: <1170545831.812235.181740@a34g2000cwb.googlegroups.com> On Feb 4, 10:03 am, "Mark" wrote: > Sys.path doesn't recognize any directories that I add using the .pth > method. I'm running Windows XP if that helps diagnose the problem. > > Here is what I've done: > > The original output of sys.path: > ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', > 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat- > win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\ > \site-packages'] > > I've added a file "MyPaths.pth" to "C:\Python25\". MyPaths.pth > contains one line that reads: C:\Python25\MyModules. For some reason > sys.path won't ever recognize that C:\Python25\MyModules exists. This > is very frustrating because I know that this method is supposed to > work. ANY help would be appreciated. > If you were to do a Google search for "pth" in this newsgroup, the first 2 or 3 results would tell you what to do, *and* point you to which section of the Python documentation covers .pth files. BTW, are YourModules specific to Python 2.5? If not, what do you plan to do when Python 2.6 is released? HTH, John From ososa at estudiantes.uci.cu Sun Feb 18 21:07:21 2007 From: ososa at estudiantes.uci.cu (Oliver Sosa Cano) Date: Sun, 18 Feb 2007 21:07:21 -0500 Subject: I need a crack for pyext1.2.5 plugin Message-ID: Hi pythoneros. I'm a cuban guy interested in python and I need the crack of an Eclipse plugin: pyext 1.2.5 Thanks very much cheers Oliver Sosa From gagsl-py at yahoo.com.ar Sat Feb 17 19:46:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 21:46:53 -0300 Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> <53b70$45d799c3$d443bb3a$30116@news.speedlinq.nl> Message-ID: En Sat, 17 Feb 2007 21:12:07 -0300, Stef Mientki escribi?: >> I would love to see: >> - a comparison between wx and gtk (QT doesn't have a very inviting >> license ;-) > I just found this: > http://www.wxwidgets.org/wiki/index.php/WxWidgets_Compared_To_Other_Toolkits But keep in mind that that comparison may be biased... A more impartial source would be better. -- Gabriel Genellina From _karlo_ at _mosor.net_ Sun Feb 18 22:17:54 2007 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Mon, 19 Feb 2007 03:17:54 +0000 (UTC) Subject: What is more efficient? Message-ID: Let's say I have a class with few string properties and few integers, and a lot of methods defined for that class. Now if I have hundreds of thousands (or even more) of instances of that class - is it more efficient to remove those methods and make them separate functions, or it doesn't matter? Thanks... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From joshua at eeinternet.com Wed Feb 28 21:46:21 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 28 Feb 2007 17:46:21 -0900 Subject: convert many excel files to pdf in batch References: <1172696032.167875.154800@s48g2000cws.googlegroups.com> Message-ID: <45e631f1$0$16373$88260bb3@free.teranews.com> Wensui Liu wrote: > Adam, > If you could come up with a way without using Adobe writer, it should > also work for me. > thanks. > > On 28 Feb 2007 12:53:52 -0800, Adam wrote: >> 1. Get PDFCreator >> 2. Install >> 3. Set as default printer >> 4. Have all excel files in same folder >> 5. Select all excel files >> 6. Right click >> 7. Select Print >> 8. Save Each PDF to a location >> 9. ??? >> 10. Profit!!!! >> >> Never done it with Adobe Writer. I'm a cheapskate. He didn't use Adobe Writer! In fact he said he didn't. PDFCreator is a free utility. Download it here: http://www.pdfforge.org/products/pdfcreator/ j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From simon at brunningonline.net Wed Feb 14 13:46:34 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 14 Feb 2007 18:46:34 +0000 Subject: list of range of floats In-Reply-To: References: Message-ID: <8c7f10c60702141046l2b6e5916u1e594bc2b53c7847@mail.gmail.com> On 2/14/07, Steve wrote: > After re-reading my original post I was pretty vague. I'm trying to creat > a list of ranges of floats, 0.0 10.0, 11 20, etc then checking to see if > an float, example 12.5 falls in the list and if so get the list index of > where it is in the index. Does this make sense? Ah, you want to know if a certain number is between to other numbers. That's not what range() is for - range() is for generating lists of integers. You can use it to do a between test for integers, I suppose, but even for integers it's a pretty poor way of going about it - you'll be creating a potentially large lists of integers, only to throw it away again. Consider something like: def between(lower, upper, target): return lower < target < upper Works for integers and floats interchangably. Or better still, do the lower < target < upper thing inline. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From sjmachin at lexicon.net Sat Feb 24 20:34:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 24 Feb 2007 17:34:39 -0800 Subject: ANN: xlrd 0.6.1a4 is now available Message-ID: <1172367279.769525.86460@p10g2000cwp.googlegroups.com> An alpha release (a4) of version 0.6.1 of xlrd is now available from http://www.lexicon.net/sjmachin/xlrd.htm and from the Cheeseshop (http://cheeseshop.python.org/pypi/xlrd). What is xlrd? It's a small (download approx 0.1 Mb) pure-Python library for extracting information from Microsoft Excel (tm) files, anywhere Python 2.1 or later will run -- no need for Excel itself, nor COM, nor even Windows. Further info: follow the links on the home page. This release incorporates the functionality of 0.6.0 which was not released independently for various reasons including the need to push ahead with the 0.6.1 functionality. New in 0.6.0: facility to access named cell ranges and named constants (Excel UI: Insert/Name/Define). New in 0.6.1: extracts formatting information for cells (font, "number format", background, border, alignment and protection) and rows/ columns (height/width etc). To save memory and time for those who don't need it, this information is extracted only if formatting_info=1 is supplied to the open_workbook() function. The cell records BLANK and MULBLANKS which contain no data, only formatting information, will continue to be ignored in the default (no formatting info) case. There have been several changes made to handle anomalous files (written by 3rd party software) which Excel will open without complaint, but failed with xlrd, usually because an assertion fails or xlrd deliberately raises an exception. Refer to HISTORY.html for details. These have been changed to accept the anomaly either silently or with a NOTE message or a WARNING message, as appropriate. Many thanks are due to Simplistix Ltd (http://www.simplistix.co.uk). for funding the new functionality in 0.6.1. BTW, Feedback: general discussion on the python-excel newsgroup (sign up at http://groups.google.com.au/group/python-excel?lnk=li&hl=en) or mailto: sjmachin at lexicon.net preferably with [xlrd] in the message subject. Cheers, John From nick at craig-wood.com Wed Feb 21 12:30:10 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 21 Feb 2007 11:30:10 -0600 Subject: f---ing typechecking References: Message-ID: Delaney, Timothy (Tim) wrote: > Nick Craig-Wood wrote: > > > x += a > > > > does not equal > > > > x = x + a > > > > which it really should for all types of x and a > > Actually, this will *never* be the case for classes that do in-place > augmented assignment. > > a = [1] > b = [2] > > c = a + b > print a, b, c > > a += b > print a, b, c Not sure what that is trying to show, it appears to back my point up... To rephrase your example >>> x = [1] >>> a = [2] >>> x += a >>> x [1, 2] >>> x = [1] >>> a = [2] >>> x = x + a >>> x [1, 2] >>> Which appears to support my point, x (and a for that matter) are the same for both methods wheter you do x = x + a or x += a. The mechanism is different certainly, but the result should be the same otherwise you are breaking the basic rules of arithmetic the programmer expects (the rule of least suprise). > You'll note that I didn't rebind 'a' in the non-augmented assignment. If > you do, augmented and non-augmented assignment may look the same, but > they can be very different. Perhaps if you post a worked example from the python interpreter I'll get what you mean! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From eddie at holyrood.ed.ac.uk Tue Feb 20 13:19:01 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 20 Feb 2007 18:19:01 +0000 (UTC) Subject: CherryPy/Turbogears on server not controlled by me References: <540bokF1shej5U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" writes: >Brian Blais wrote: >> Hello, >> >> I was wondering if there is a way to run CherryPy/Turbogears on a server >> that I don't >> have root access to. If I just choose a random port, I think the security >> guys on >> the server would get annoyed at me. >Why should they? Opening anything networking will open a port. And if you >have shell access, you can point PYTHONPATH to a directory of your choice >and let easy_install install the packages required there. >I don't see a problem. And _if_ they get mad at you, well - there isn't >anything you can do about that I presume apart from telling them to shut >up - because without a port, there is no webapp... And since your application is not running as root the worst that can happen if you introduce a security hazard in your app is that only your files are endangered. I run several TG apps in user space and the only small problem I've had is the logistics of telling people if you have to move it somewhere else since a DNS alias doesn't help much with explicit port numbers in the URL. Eddie From scott.daniels at acm.org Sat Feb 24 00:38:24 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 23 Feb 2007 21:38:24 -0800 Subject: Finding non ascii characters in a set of files In-Reply-To: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> Message-ID: <12tvjopst9fjd17@corp.supernews.com> bg_ie at yahoo.com wrote: > I'm updating my program to Python 2.5, but I keep running into > encoding problems. I have no ecodings defined at the start of any of > my scripts. What I'd like to do is scan a directory and list all the > files in it that contain a non ascii character. How would I go about > doing this? def non_ascii(files): for file_name in files: f = open(file_name, 'rb') if '~' < max(f.read(), ' '): yield file_name f.close() if __name__ == '__main__': import os.path import glob import sys for dirname in sys.path[1:] or ['.']: for name in non_ascii(glob.glob(os.path.join(dirname, '*.py')) + glob.glob(os.path.join(dirname, '*.pyw'))): print name --Scott David Daniels scott.daniels at acm.org From Shawn at Milochik.com Sat Feb 10 23:02:39 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Sat, 10 Feb 2007 23:02:39 -0500 Subject: Regular Expressions In-Reply-To: <1171162731.488726.160400@a75g2000cwd.googlegroups.com> References: <1171162731.488726.160400@a75g2000cwd.googlegroups.com> Message-ID: <2dc0c81b0702102002s15f6798fr5f49a1f93a4af847@mail.gmail.com> On 10 Feb 2007 18:58:51 -0800, gregarican wrote: > On Feb 10, 6:26 pm, "Geoff Hill" wrote: > > What's the way to go about learning Python's regular expressions? I feel > > like such an idiot - being so strong in a programming language but knowing > > nothing about RE. > > I highly recommend reading the book "Mastering Regular Expressions," > which I believe is published by O'Reilly. It's a great reference and > helps peel the onion in terms of working through RE. They are a > language unto themselves. A fun brain exercise. > > -- > http://mail.python.org/mailman/listinfo/python-list > Absolutely: Get "Mastering Regular Expressions" by Jeffrey Friedl. Not only is it easy to read, but you'll get a lot of mileage out of regexes in general. Grep, Perl one-liners, Python, and other tools use regexes, and you'll find that they are really clever little creatures once you befriend a few of them. Shawn From horpner at yahoo.com Fri Feb 2 09:41:13 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 15:41:13 +0100 Subject: newbie/ merging lists of lists with items in common References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: On 2007-02-02, ardief wrote: > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with > the only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] > > I have the feeling it's trivial, and I've scoured the group > archives - sets might be a possibility, but I'm not sure how to > operate on a list of lists with sets. This is a job for... duhn-duhn-DAAAAH! Captain CHAOS! Er... I mean itertools.groupby. I took the liberty of not assuming the alist was sorted already. This could be a one-liner if you wanted to be evil. def bundle_alist(seq): """ Bundle together some alist tails. >>> seq = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] >>> bundle_alist(seq) [['a', ['13', '3']], ['b', ['6']], ['c', ['12', '15', '4']], ['d', ['2']], ['e', ['11', '5', '16', '7']]] """ from itertools import groupby def key_func(t): return t[0] groups = groupby(sorted(seq, key=key_func), key_func) seq = [] for item in groups: seq.append([item[0], [a[1] for a in item[1]]]) return seq -- Neil Cerutti Music gets more chromatic and heavy towards the end of the century. One of the popular questions of the day was, "Why?" --Music Lit Essay From steve at REMOVE.THIS.cybersource.com.au Mon Feb 19 17:09:26 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 20 Feb 2007 09:09:26 +1100 Subject: How do I create an array of functions? References: <1171872999.751809.256880@p10g2000cwp.googlegroups.com> <1171891023.613866.312260@s48g2000cws.googlegroups.com> Message-ID: On Mon, 19 Feb 2007 05:17:03 -0800, Rob Wolfe wrote: >> > # test.py >> > >> > def fun1(): return "fun1" >> > def fun2(): return "fun2" >> > def fun3(): return "fun3" >> > >> > # list of functions >> > dsp = [f for fname, f in sorted(globals().items()) if callable(f)] >> >> Hmmm... when I try that, I get dozens of other functions, not just fun1, >> fun2 and fun3. And not just functions either; I also get classes. > > Oh, really? Where are these _other_ functions and classes > in *MY* example? I ran your example, word for word. Copied it and pasted it into my Python session. >> Does Python have a function that will read my mind and only return the >> objects I'm thinking of? > > Your sarcasm is unnecessary. > Using of `globals` function was easier to write this example. That's all. Actually, it wasn't easier to write at all. Your version: dsp = [f for fname, f in sorted(globals().items()) if callable(f)] Sensible version: dsp = [fun1, fun2, fun3] Not only is your version brittle, but it is also about three times as much typing. -- Steven. From skip at pobox.com Sun Feb 11 13:07:13 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 11 Feb 2007 12:07:13 -0600 Subject: Regular Expressions In-Reply-To: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> Message-ID: <17871.23377.580391.403818@montanaro.dyndns.org> jwz> Some people, when confronted with a problem, think 'I know, I'll jwz> use regular expressions.' Now they have two problems. dbl> So as a newbie, I have to ask.... So I guess I don't really dbl> understand why they are a "bad idea" to use. Regular expressions are fine in their place, however, you can get carried away. For example: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html Skip From deets at nospam.web.de Thu Feb 22 10:08:29 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 16:08:29 +0100 Subject: How to test whether a host is reachable? References: Message-ID: <545pvdF1vfjifU1@mid.uni-berlin.de> > Just because you could ping with ICMP packets doesn't mean you could > do anything with the machine. I assume that you are connecting to > do something on the machine. Just wrap what you are trying to do > in try: block. It will either succeed or fail. Handle the exeption. And the other way round: just because you can't ping a machine doesn't mean you can't do anything with it - a Firewall might just have snipped away all the ICMP-packets. Diez From deets at nospam.web.de Thu Feb 1 04:33:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Feb 2007 10:33:59 +0100 Subject: retrbinary ! how does it work ? References: <1170321454.210348.91370@a75g2000cwd.googlegroups.com> Message-ID: <52dqg7F1o6mvqU1@mid.uni-berlin.de> blancmunier1 at yahoo.FR wrote: > Hello dear community ! > > I'm a bit ashamed to ask such an easy question, but I didn't find my > answer on previous posts. > I'd like to copy files with FTP protocol in a subdirectory. > So far, my code look like that : > > import ftplib > session = ftplib.FTP('222.33.44.55','usr','pwd') > session.cwd('/') > files = session.nlst() > for file in files: > session.retrbinary('RETR '+file, open(file, 'wb').write) > > It does work but the files are copied in the same directory as the > python file. And I would like to copy the file in this relative > directory : ../archives > For example, if the python file is in this directory : C:\SCOR\Bat\, > the FTP files gotta be in C:\SCOR\archives\ . > > Can anyone help me. The problem is your callback-function that you create like this: open(file, 'wb').write If all you pass here is file, where else than in the current working directory do you expect files to appear? Either provide a full destination path like this open(os.path.join('../', file), 'wb').write or change the current working directory beforehand, using os.cwd. Diez From yinglcs at gmail.com Mon Feb 19 12:04:19 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 19 Feb 2007 09:04:19 -0800 Subject: Declare a variable global Message-ID: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> Hi, I have the following code: colorIndex = 0; def test(): print colorIndex; This won't work. But it works if i do this: colorIndex = 0; def test(): global colorIndex; print colorIndex; My question is why do I have to explicit declaring 'global' for 'colorIndex'? Can't python automatically looks in the global scope when i access 'colorIndex' in my function 'test()'? Thank you. From deets at nospam.web.de Mon Feb 12 06:20:02 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Feb 2007 12:20:02 +0100 Subject: Progress when parsing a large file with SAX References: <1171277000.671586.191250@q2g2000cwa.googlegroups.com> Message-ID: <53b0r2F1rqg29U1@mid.uni-berlin.de> marc.omorain at gmail.com wrote: > Hi there, > > I have a 28mb XML file which I parse with SAX. I have some processing > to do in the startElement / endElement callbacks, which slows the > parsing down to about 60 seconds on my machine. > > My application is unresponsive for this time, so I would like to show > a progress bar. I could show a spinner to show that the application is > responsive, but I would prefer to show a percentage. Is there any way > to query the parser to see how many bytes of the input file have been > processed so far? I'd create a file-like object that does this for you. It should wrap the original file, and count the number of bytes delivered. Something along these lines (untested!!!): class PercentageFile(object): def __init__(self, filename): self.size = os.stat(filename)[6] self.delivered = 0 self.f = file(filename) def read(self, size=None): if size is None: self.delivered = self.size return self.f.read() data = self.f.read(size) self.delivered += len(data) return data @property def percentage(self): return float(self.delivered) / self.size * 100.0 Diez From thegeoffmeister at gmail.com Sat Feb 10 18:24:03 2007 From: thegeoffmeister at gmail.com (Geoff Hill) Date: Sat, 10 Feb 2007 23:24:03 GMT Subject: Best Free and Open Source Python IDE References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: If you can take some time and master Vim, you'll be set for typing out any programming language for the rest of your life. I hear Emacs is good too, and the GNU project is great, so you could try that as well. It's supposed to be more geared towards programming From jura.grozni at gmail.com Fri Feb 9 06:26:20 2007 From: jura.grozni at gmail.com (azrael) Date: 9 Feb 2007 03:26:20 -0800 Subject: unique elements from list of lists In-Reply-To: <1171019636.020023.274770@s48g2000cws.googlegroups.com> References: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> <1171019636.020023.274770@s48g2000cws.googlegroups.com> Message-ID: <1171020380.695289.245020@v33g2000cwv.googlegroups.com> tra using the firs sublist (list[1]) as cell.then take zhe second sublist and take a value from it at once and if the value from list[2] doesnt exist in list[1] then insert it into list[1] at the correct place. Something like the insertionsort. From sjmachin at lexicon.net Tue Feb 6 18:54:04 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Feb 2007 15:54:04 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170775779.707583.131420@k78g2000cwa.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> <1170775779.707583.131420@k78g2000cwa.googlegroups.com> Message-ID: <1170806044.201254.289080@l53g2000cwa.googlegroups.com> On Feb 7, 2:29 am, garri... at gmail.com wrote: > On Feb 1, 8:25 pm, "Krypto" wrote: > > > The correct answer as told to me by a person is > > (N>>3) + ((N-7*(N>>3))>>3) > > The above term always gives division by 7 > > Does anybody else notice that this breaks the spirit of the problem > (regardless of it's accuracy)? 'N-7' uses the subtraction operator, > and is thus an invalid solution for the original question. > > Build a recursive function, which uses two arbitrary numbers, say 1 > and 100. Recursive? Bzzzt! > Check each, times 7, and make sure that your target number, > N, is between them. Increase or decrease your arbitrary numbers as > appropriate. Now pick a random number between those two numbers, and > check it. Figure out which two the answer is between, and then check a > random number in that subset Might it not be better to halve the interval at each iteration instead of calling a random number function? mid = (lo + hi) >> 1 looks permitted and cheap to me. Also you don't run the risk of it taking a very high number of iterations to get a result. >. Continue this, and you will drill down > to the correct answer, by using only *, +, >, and <. > > I'll bet money that since this was a programming interview, that it > wasn't a check of your knowledge of obscure formulas, but rather a > check of your lateral thinking and knowledge of programming. > > ~G Did you notice the important word *efficiently* in line 1 of the spec? Even after ripping out recursion and random numbers, your proposed solution is still way off the pace. Cheers, John From john at smith.com Mon Feb 26 08:38:55 2007 From: john at smith.com (john smith) Date: Mon, 26 Feb 2007 13:38:55 GMT Subject: comp post Message-ID: comp post From ah at hatzis.de Thu Feb 8 10:59:44 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Thu, 08 Feb 2007 16:59:44 +0100 Subject: distutils: different names in src and dist/build In-Reply-To: <45CB22EE.7090301@hatzis.de> References: <45CB22EE.7090301@hatzis.de> Message-ID: <45CB48F0.1020800@hatzis.de> Anastasios Hatzis wrote: > Hi, > > is it possible to have different names between the original package name > and that which will be installed? > > Example: > > setup.py > src/ > sdk/ > __init__.py > startme.py > > This usually creates a distribution file like sdk-0.6.2.tar.gz, which > may create > > site-packages/ > sdk/ > > But I would like to have a MySDK-0.6.2.tar.gz and in > > site-packages/ > MySDK/ > > Of course with-out changing the original src package name "sdk" to > "MySDK" (which likely would be the easiest way, hum). > > Any suggestion or link how I can achieve this? > Sorry, now I understood that package_dir option can also be used to have a installed package layout *totally different* from original source layout. Regards, Anastasios From ironfroggy at gmail.com Sat Feb 10 10:14:58 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 10 Feb 2007 10:14:58 -0500 Subject: Hacking in python In-Reply-To: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> References: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> Message-ID: <76fd5acf0702100714m5393dd69t74fcab540db30e65@mail.gmail.com> http://en.wikipedia.org/wiki/Hacker_%28disambiguation%29 Educate yourself on what hacking actually is. We're all hackers, because it just means we get the most out of code, enjoy pushing our technology to the limit, and generally love programming. The term has been abused by the media and you don't do much more than show your own naiveness by asking such a question. You also do a great job of insulting everyone on this list. On 2/10/07, enes naci wrote: > > i would like to know about hacking in python too whether its illegal > or not is not the point and anyway it doesn't mean i'm gong to use it. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From skip at pobox.com Fri Feb 2 16:08:19 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 2 Feb 2007 15:08:19 -0600 Subject: Python does not play well with others In-Reply-To: <7xr6t89wkw.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> Message-ID: <17859.43075.422376.941355@montanaro.dyndns.org> Paul> What does "batteries included" mean to you? To me, it means you Paul> don't have to install add-ons. Who decides which batteries are important to include? Skip From paddy3118 at netscape.net Sun Feb 4 00:27:34 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 21:27:34 -0800 Subject: Decimating Excel files In-Reply-To: References: Message-ID: <1170566854.692261.148920@j27g2000cwj.googlegroups.com> On Feb 3, 7:43 pm, gonzlobo wrote: > No, I don't want to destroy them (funny how the word 'decimate' has > changed definition over the years) :). > > We have a data acquisition program that saves its output to Excel's > .xls format. Unfortunately, the programmer was too stupid to write > files the average user can read. > > I'd like some advice on how to go about: > 1. Reading a large Excel file and chop it into many Excel files (with > only 65535 lines per file) > or > 2. Decimate an Excel file & write... say every other line (user > selectable)... to a new file. > > I'm pretty experienced at reading and writing simple text files, but > this is my first foray into using COM. I would imagine either choice 1 > or 2 is pretty simple once I can get the file open. > > Thanks in advance. I got a fair amount of hits for xls-to-csv in Google.. - Paddy. . From skip at pobox.com Fri Feb 9 12:53:17 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 9 Feb 2007 11:53:17 -0600 Subject: pygame and python 2.5 In-Reply-To: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> Message-ID: <17868.46349.59089.178486@montanaro.dyndns.org> Ben> Python extensions written in C require recompilation for each new Ben> version of Python, due to Python limitations. Can you propose a means to eliminate this limitation? Skip From buffinator at mymail.com Sat Feb 24 11:10:55 2007 From: buffinator at mymail.com (buffinator) Date: Sat, 24 Feb 2007 17:10:55 +0100 Subject: Recreating a char array from a pointer Message-ID: <45e05fb2$0$486$cc7c7865@news.luth.se> I have an application that has to send a string as a pointer to memory, and then another one that has to retriece it and fetch the string. Converting the string to an array and sending the pointer was easy import array a=array.array("c","mytextgoeshere") my_pointer = a.buffer_info()[0] But then I tried to get the data back... and I just can't find out how. I ended up writing a C module for this that works fine in linux, but this application is meant for windows and I just can't get C-modules to compiler there correctly since I suck at windows. The relevant code from the module is static PyObject * pointrtostr_casttostr(PyObject *self, PyObject *args) { char *mystr; long int p; if (!PyArg_ParseTuple(args, "l", &p)) return NULL; mystr = (char*)p; return Py_BuildValue("s", mystr); } My question is... can I do the above code in python without involving C since it is quite a big hassle to have to go through the module building in windows? :/ /buffis From mail at microcorp.co.za Sat Feb 10 00:12:53 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 10 Feb 2007 07:12:53 +0200 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com><1170731096.976076.173270@h3g2000cwc.googlegroups.com><1170749117.582426.151770@p10g2000cwp.googlegroups.com><1170796103.766866.18320@a34g2000cwb.googlegroups.com><1170861935.779969.52980@v33g2000cwv.googlegroups.com><1170874782.600836.210670@a34g2000cwb.googlegroups.com><2ZKdnYNMboxxS1fYRVnzvA@telenor.com> Message-ID: <002901c74cd2$1f296c40$03000080@hendrik> "Dennis Lee Bieber" wrote: > On Thu, 8 Feb 2007 10:55:17 +0200, "Hendrik van Rooyen" > declaimed the following in comp.lang.python: > > > I am under the impression that Loki had a daughter called Hel ... > > > One of his few "normal" offspring... After all, Loki also was > Sleipnir's* /mother/! And probably related to Fenrir (aka, the Fenris > Wolf) as well. > > > * Odin's eight-legged horse We should both be more careful - using the past tense like that is disrespectful, and there are no guarantees that the Norse gods are dead. Vindictive lot, they were.. ....uuhhh are, I mean. - Hendrik From nogradi at gmail.com Thu Feb 22 15:14:15 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 22 Feb 2007 21:14:15 +0100 Subject: JIT (just-in-tme accelerator) for Python - exists or no? In-Reply-To: <1172167441.845600.154270@s48g2000cws.googlegroups.com> References: <1172167441.845600.154270@s48g2000cws.googlegroups.com> Message-ID: <5f56302b0702221214s79da852v810ecaf186af7f7a@mail.gmail.com> > Or is any progress going on now? > > The JIT in MATLAB or Java seems to be very effective. This document describes the JIT situation in pypy: http://codespeak.net/pypy/dist/pypy/doc/jit.txt From gnewsg at gmail.com Wed Feb 14 08:05:16 2007 From: gnewsg at gmail.com (billie) Date: 14 Feb 2007 05:05:16 -0800 Subject: WindowsNT user authentication In-Reply-To: <1171357845.968797.229580@m58g2000cwm.googlegroups.com> References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> <1171294708.261232.18290@p10g2000cwp.googlegroups.com> <1171357845.968797.229580@m58g2000cwm.googlegroups.com> Message-ID: <1171458314.065280.164360@v33g2000cwv.googlegroups.com> Another question, I'm sorry. Do you got any idea about how to get permissions of a file/directory given the username? For example: I would like to know if C:\my_file.ext is readable/ writable by user 'x' or not. From laurent.pointal at limsi.fr Fri Feb 23 04:05:07 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 23 Feb 2007 10:05:07 +0100 Subject: Europe Tests Established Chemicals on Millions of Animals In-Reply-To: <1172188038.680999.181740@a75g2000cwd.googlegroups.com> References: <1172188038.680999.181740@a75g2000cwd.googlegroups.com> Message-ID: You help nothing by posting subjects unrelated to the *programming language* Python into a usenet group about this language. From robson.cozendey.rj at gmail.com Mon Feb 5 12:55:47 2007 From: robson.cozendey.rj at gmail.com (robson.cozendey.rj at gmail.com) Date: 5 Feb 2007 09:55:47 -0800 Subject: Unicode formatting for Strings Message-ID: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> Hi, I?m trying desperately to tell the interpreter to put an '?' in my string, so here is the code snippet: # -*- coding: utf-8 -*- filename = u"Ataris Aqu?ticos #2.txt" f = open(filename, 'w') Then I save it with Windows Notepad, in the UTF-8 format. So: 1) I put the "magic comment" at the start of the file 2) I write u"" to specify my unicode string 3) I save it in the UTF-8 format And even so, I get an error! File "Ataris Aqu?ticos #2.py", line 1 SyntaxError: Non-ASCII character '\xff' in file Ataris Aqu?ticos #2.py on line 1 , but no encoding declared; see http://www.python.org/peps/ pep-0263.html for det ails I don?t know how to tell Python that it should use UTF-8, it keeps saying "no encoding declared" ! Robson From ziga.seilnacht at gmail.com Tue Feb 27 18:23:25 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 27 Feb 2007 15:23:25 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172616850.962166.27480@k78g2000cwa.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> <1172615426.752353.25610@8g2000cwh.googlegroups.com> <1172616850.962166.27480@k78g2000cwa.googlegroups.com> Message-ID: <1172618605.121435.247300@t69g2000cwt.googlegroups.com> Andrew Felch wrote: > I pasted the code into mine and replaced the old. It seems not to > work for either unpickled objects or new objects. I add methods to a > class that inherits from AutoReloader and reload the module, but the > new methods are not callable on the old objects. Man! It seems we're > so close, it will be huge if this ends up working. This stuff is so > over my head, I wish I could help in some additional way. > > -Andrew Did you copy and paste the entire module? I fiddled almost all parts of the original code. I did some base testing and it worked for me. Could you post the traceback? Note that Google Groups messed up indentation; in MetaAutoReloader.__init__, the line starting with cls.__instance_refs__ should be at the same level as previous line. Did you restart Python? InstanceTracker, MetaInstanceTracker and MetaAutoReloader are not auto reloaded :). Ziga From gnewsg at gmail.com Tue Feb 13 04:10:46 2007 From: gnewsg at gmail.com (billie) Date: 13 Feb 2007 01:10:46 -0800 Subject: WindowsNT user authentication In-Reply-To: References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> <1171294708.261232.18290@p10g2000cwp.googlegroups.com> Message-ID: <1171357845.968797.229580@m58g2000cwm.googlegroups.com> On 12 Feb, 16:53, Tim Golden wrote: > billie wrote: > > Do you got any idea about how getting user's home directory? > > The answer to that is unfortunately slightly complicated, > because Windows has no such thing as a "user's home directory" > or, if you prefer, it has several such things. > > If you want, you can let Python make the decision, by > calling os.path.expanduser on "~" which, in my case, > correctly gives h:\ which is my domain home directory. > > Obviously this is not necessarily the same as my Documents > and Settings directory, which can also be considered a home > directory. That you can get by querying the shell: > > > from win32com.shell import shell, shellcon > > idlist = shell.SHGetSpecialFolderLocation (0, shellcon.CSIDL_PERSONAL) > documents_and_settings = shell.SHGetPathFromIDList (idlist) > print documents_and_settings > > > > In my case they are the same but that will depend on your > setup. I know in the past at least one of these has > defaulted to c:\ > > Alternatives (which in my case amount to the same thing) > include using the HOMEDRIVE / HOMEPATH / HOMESHARE > environment vars: > > > import os > drive = os.environ.get ("HOMEDRIVE", "") > path = os.environ.get ("HOMEPATH", "") > > share = os.environ.get ("HOMESHARE", "") > > print drive+path > print share > > > I haven't bothered to look, but I think this latter > is how the expanduser function works things out. > > YMMV > TJG Thanks. From moin at blackhole.labs.rootshell.ws Sun Feb 25 19:49:56 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Sun, 25 Feb 2007 18:49:56 -0600 Subject: newbie question Message-ID: <001f01c75940$0aed2080$9c10590a@cisco.com> >>> asd={} >>> asd={1:2,3:4,4:5} >>> print asd {1: 2, 3: 4, 4: 5} >>> asd.has_key(3) True >>> asd.update() >>> print asd {1: 2, 3: 4, 4: 5} >>> what does asd.update() signifies. What is the use of it. Any comments would help to understand it. Thanks Mohideen From deets at nospam.web.de Sat Feb 17 03:35:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 17 Feb 2007 09:35:07 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> Message-ID: <53nt2aF1sn581U1@mid.uni-berlin.de> > The final goal of programming language is (in most cases) > meant to create functional things, > that can assist people to perform their tasks. > The UI of that resulting thing should be optimal adapted to the final > audience (and task). > My audience is most comfortable with a intuitive GUI. > In most of my applications, > I need about 50% of the time for the GUI and 50% for the other > functional code. > These estimates are for Delphi (is about identical as VB, which I used > previous). > For what I've seen until now from Python, > - designing the GUI will cost me about 2 .. 3 times as much in Python You mean delphi here I presume? > - Python is not capable of doing everything I need > (almost all interactive actions are very primitive and crashes a lot) I'm not sure what you are talking about here, and I have the deep impression you yourself don't as well. Matter of factly, there is no "the python GUI". There are quite a few choices. The built-in tkinter, which - while limited in some senses - is developed by Frederik Lundh, and while I personally haven't done too much with it, his reputation as one of the most high profiled python developers doesn't go along pretty well with your assertions above. So -whatever you used as GUI-toolkit, you either used it wrong, or it really wasn't good. But then there are at least three major other toolkits available, wx, gtk and Qt. The first two I've only dabbled a bit with and can't comment on. But I've done extensive, cross-platform development with Qt. And can assert that it is unmatched in productivity and feature richness, especially when combined with python. And certainly beat VB, and most probably even delphi (albeit I haven't done too much in that to really put all my weight behind these words). And so I'm under the strong impression that your - undoubtedly correct from a personal point of view, and I don't think your meaning evil here - observations are wrong and are based on a lack of experience in python and it's available gui-options. Diez From gagsl-py at yahoo.com.ar Mon Feb 5 19:43:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 21:43:13 -0300 Subject: Python module question References: Message-ID: En Mon, 05 Feb 2007 16:43:54 -0300, Rodolfo S. Carvalho escribi?: > My question is: can I code a method __getattr__() to change the behavior > of > the 'import' command? You can play with __import__, imp and ihooks, but could you explain better what you need? Perhaps you don't ever need to change how import works. -- Gabriel Genellina From Afro.Systems at gmail.com Tue Feb 27 07:12:13 2007 From: Afro.Systems at gmail.com (Tzury) Date: 27 Feb 2007 04:12:13 -0800 Subject: Python, Embedded linux and web development Message-ID: <1172578332.957236.247800@8g2000cwh.googlegroups.com> Regarding the platform described below, can anyone suggest from his experience what would be the best library choice to develop the following application. a) application that deals with data transformed via TCP sockets. b) reading and writing to and from sqlite3 (include Unicode manipulations). c) small web application that will be used as front end to configure the system (flat files and sqlite3 db are the back-end). Our platform is base on the Intel PXA270 processor (XSCALE family, which is ARM compatible) running at 312MHz. From lbates at websafe.com Wed Feb 21 19:12:51 2007 From: lbates at websafe.com (Larry Bates) Date: Wed, 21 Feb 2007 18:12:51 -0600 Subject: Convert to binary and convert back to strings In-Reply-To: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: Harlin Seritt wrote: > Hi... > > I would like to take a string like 'supercalifragilisticexpialidocius' > and write it to a file in binary forms -- this way a user cannot read > the string in case they were try to open in something like ascii text > editor. I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is there any > way to do this in Python? > > Thanks! > > Harlin > I promise you that everything written to a file is done in binary. Computers don't know how to work with anything BUT binary. I think what you want to do is to encrypt/obstifucate the string. For that you will need to encrypt the string, write it out, read it back in, and decrypt it. If you want it to be REALLY strong use pyCrypto and something like AES-256. http://www.amk.ca/python/code/crypto If you just want to make it somewhat hard for someone to decypher you can do something like below (sorry I can't remember where I found this to attribute to someone): import random import zlib import time def tinycode(key, text, reverse=False): rand = random.Random(key).randrange if not reverse: text = zlib.compress(text) text = ''.join([chr(ord(elem)^rand(256)) for elem in text]) if reverse: text = zlib.decompress(text) return text def strToHex(aString): hexlist = ["%02X" % ord(x) for x in aString] return ''.join(hexlist) def HexTostr(hString): res = "" for i in range(len(hString)/2): realIdx = i*2 res = res + chr(int(hString[realIdx:realIdx+2],16)) return res if __name__ == "__main__": keyStr = "This is a key" #testStr = "which witch had which witches wrist watch abc def ghi" testStr=time.strftime("%Y%m%d", time.localtime()) print "String:", testStr etestStr = tinycode(keyStr, testStr) print "Encrypted string:", etestStr hex=strToHex(etestStr) print "Hex : ", hex print "Len(hex):", len(hex) nonhex=HexTostr(hex) #testStr = tinycode(keyStr, etestStr, reverse=True) testStr = tinycode(keyStr, nonhex, reverse=True) print "Decrypted string:", testStr WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM. It is just a nuisance for someone that really wants to decrypt the string. But it might work for your application. -Larry From gagsl-py at yahoo.com.ar Tue Feb 6 23:14:34 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Feb 2007 01:14:34 -0300 Subject: Dictionary/Hash question References: <2adc542f0702061531g7504de83ob01b56933794a37e@mail.gmail.com> <2adc542f0702061718h5a943312id61c3ac77c074a95@mail.gmail.com> <2adc542f0702061928p27c8585eta82c20e0cbf7c30@mail.gmail.com> Message-ID: En Wed, 07 Feb 2007 00:28:31 -0300, Sick Monkey escribi?: > qualm after qualm. Before you read this, my OS is Linux, up2date, and > minimal RAM (512). And Python 2.3 or earlier, I presume, else you would have the builtin set type. > The files that my script needs to read in and interpret can contain > anywhere > from 5 million lines to 65 million lines > > I have attached 2 versions of code for you to analyze. > ================= > I am having issues with performance. > > Instance 1: dict_compare.py {which is attached} > Is awesome, in that I have read a file and stored it into a hash table, > but > if you run it, the program decides to stall after writing all of the > date. > file has actually finished processing within 1 minute, but the script > continues to run for additional minutes (10 additional minutes actually). > This version reads both files FULLY into memory; maybe the delay time you see, is the deallocation of those two huge lists. > Instance 2: dictNew.py > Runs great but it is a little slower than Instance 1 (dict_compare.py). > BUT > WHEN IT FINISHES, IT STOPS THE APPLICATION.... no additional > minutes..... > This version processes both files one line at a time, so the memory requirements are a lot lower. I think it's a bit slower because the Set class is implemented in Python; set (Python 2.4) is a builtin type now. You could combine both versions: use the dict approach from version 1, and process one line at a time as in version 2. You can get the mails in both dictionaries like this: for key in dict1: if key in dict2: print key -- Gabriel Genellina From __peter__ at web.de Mon Feb 26 10:32:38 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Feb 2007 16:32:38 +0100 Subject: Interactive os.environ vs. os.environ in script References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> Message-ID: boris.smirnov at gmail.com wrote: > Hi there, > > I have a problem with setting environment variable in my script that > uses qt library. For this library I have to define a path to tell the > script whre to find it. > > I have a script called "shrink_bs_070226" that looks like this: > ********************************** > import sys, re, glob, shutil > import os > > os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > > from qt import * > *********************** > > When I run this script I get this error: > > >> python shrink_bs_070226.py > Traceback (most recent call last): > File "shrink_bs_070226.py", line 25, in ? > from qt import * > File "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ > qt.py", line 46, in ? > import libsip > ImportError: libadamsqt.so: cannot open shared object file: No such > file or directory > > What is important here that when I set this variable interactive in > python session, there is no problem with import. > >> python > Python 2.2.3 (#1, Aug 8 2003, 08:44:02) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-13)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os > >>>> import shrink_bs_070226 > Traceback (most recent call last): > File "", line 1, in ? > File "shrink_bs_070226.py", line 25, in ? > from qt import * > ImportError: No module named qt > >>>> os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > >>>> import shrink_bs_070226 >>>> > > Could anybody explain me the logic here? Am I missing something? Until Python 2.4 a failed import could leave some debris which would make you think a second import did succeed. Try >>> import os >>> os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' >>> import shrink_bs_070226 # I expect that to fail in a fresh interpreter to verify that what you see is an artifact of your test method. Peter From joerg.rech at gmail.com Thu Feb 8 14:27:49 2007 From: joerg.rech at gmail.com (Joerg Rech) Date: 8 Feb 2007 11:27:49 -0800 Subject: Survey about Architecture and Design Patterns Message-ID: <1170962869.027239.39750@j27g2000cwj.googlegroups.com> Dear software practitioners, consultants, and researchers, we are currently conducting an international survey about architecture and design patterns. Our goal is to discover how familiar people are with these patterns (and anti-patterns) as well as to elicit the information need, the usage behavior, and the experience of software organizations regarding architecture patterns and design patterns. Therefore, we would like to invite you and members of your organizations to participate in the survey at http:// softwarepatterns.eu. Answering the survey should take about 20-30 minutes. The survey will close on 1 March 2007. All data will be treated confidentially. Please pass information about this survey on to your colleagues and managers as well as other contacts who might be interested in this topic and have experience with architecture and design patterns. Many thanks in advance, Joerg Rech --- Joerg Rech Speaker of the GI-Workgroup Architecture and Design Patterns (AKAEM) Web: http://www.architekturmuster.de (in German) XING: http://www.xing.com/profile/Joerg_Rech/ From rkmr.em at gmail.com Wed Feb 21 18:20:45 2007 From: rkmr.em at gmail.com (mark) Date: Wed, 21 Feb 2007 15:20:45 -0800 Subject: getting a thread out of sleep In-Reply-To: <1172098070.913952.20730@h3g2000cwc.googlegroups.com> References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> <1172098070.913952.20730@h3g2000cwc.googlegroups.com> Message-ID: On 21 Feb 2007 14:47:50 -0800, placid wrote: > On Feb 22, 3:23 am, mark wrote: > > On 20 Feb 2007 21:26:18 -0800, placid wrote: > > > > > > > > > On Feb 21, 4:21 pm, "placid" wrote: > > > > On Feb 21, 4:12 pm, mark wrote: > > > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > > > On Feb 21, 3:08 pm, mark wrote: > > > > > > > Right now I have a thread that sleeps for sometime and check if an > > > > > > > event has happened and go back to sleep. Now instead I want the thread > > > > > > > to sleep until the event has occured process the event and go back to sleep > > > > > > > > > class eventhndler(threading.Thread): > > > > > > > def __init__(self): > > > > > > > threading.Thread.__init__(self) > > > > > > > def run(self): > > > > > > > while True: > > > > > > > time.sleep(SLEEPTIME) > > > > > > > ''''do event stuff''' > > > > > > > > The way i would do this is by using an threading.Event ( > > > > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > > > > > > > > > class eventhandler(threading.Thread): > > > > > > def __init__(self): > > > > > > threading.Thread.__init__(self) > > > > > > self.event = threading.Event() > > > > > > def run: > > > > > > while True: > > > > > > # block until some event happens > > > > > > self.event.wait() > > > > > > """ do stuff here """ > > > > > > self.event.clear() > > > > > > > > > > > > > > the way to use this is to get the main/separate thread to set() the > > > > > > event object. > > > > > > > Can you give an example of how to get the main threead to set teh event object? > > > > > this is exactly what i wanted to do! > > > > > thanks a lot! > > > > > mark> > > > oops I've miss-typed the thread variable name the following should > > > work > > > > > > > > if __name__ == "__main__": > > > evtHandlerThread = eventhandler() > > > evtHandlerThread.start() > > > > > # do something here # > > > evtHandlerThread.event.set() > > > > > # do more stuff here # > > > evtHandlerThread.event.set() > > > > > > > > > Can I have the same thread process two or more events? Can you tell > > how to do this? The code you gave is waiting on one event right. How > > can I do it for more events? > > thanks a lot! > > mark > > I don't think a thread can block on more than one event at a time. But > you can make it block on more then one event one at a time. > > > > class eventhandler(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > self.events = [threading.Event(), threading.Event()] > self.currentEvent = None > def run: > while True: > for event in self.events: > self.currentEvent = event > # block until some event happens > self.currentEvent.wait() > """ do stuff here """ > self.currentEvent.clear() > > if __name__ == "__main__": > evtHandlerThread = eventhandler() > evtHandlerThread.start() > > # do something here # > evtHandlerThread.currentEvent.set() > > # do more stuff here # > evtHandlerThread.currentEvent.set() > > > > what the thread does is sequentially waits for two events to happen > and then execute the same code. You could change this code to perform > different functions for different event objects. Once the thread starts it is going to wait on the event that is the first element of the list right? This would mean : evtHandlerThread.currentEvent.set(): that I have only one event right? Can you explain how I can have different event objects. I dont see how I can do different functinos for same event. Thanks a lot! mark From michele.simionato at gmail.com Thu Feb 1 08:14:18 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 Feb 2007 05:14:18 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: References: <1170309756.501758.303800@a34g2000cwb.googlegroups.com> Message-ID: <1170335658.099847.178670@a34g2000cwb.googlegroups.com> On Feb 1, 1:43 pm, Jean-Paul Calderone wrote: > On 31 Jan 2007 22:02:36 -0800, Michele Simionato wrote: > >Another thing I miss is a facility to run an iterator in the Tkinter > >mainloop: since Tkinter is not thread-safe, > >writing a multiple-download progress bar in Tkinter using threads is > >definitely less obvious than running > >an iterator in the main loop, as I discovered the hard way. Writing a > >facility to run iterators in Twisted > >is a three-liner, but it is not already there, nor standard :-( > > Have you seen the recently introduced twisted.internet.task.coiterate()? > It sounds like it might be what you're after. Ops! There is a misprint here, I meant "writing a facility to run iterators in TKINTER", not in Twisted. Twisted has already everything, even too much. I would like to have a better support for asynchronous programming in the standard library, for people not needing the full power of Twisted. I also like to keep my dependencies at a minimum. Michele Simionato From jstroud at mbi.ucla.edu Thu Feb 15 07:07:19 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 15 Feb 2007 04:07:19 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Wed, 14 Feb 2007 22:21:43 -0800, James Stroud wrote: > >>> The user's expected behaviour for [1] + (1,) might be to return a list, or >>> it might be to return a tuple. Since there is no obviously correct >>> behaviour, the right thing to do is to refuse to guess. >> I guess we differ on what is obvious. This seems obvious to me: >> >> [1] + (1,) => [1, 1] >> (1,) + [1] => (1, 1) >> >> simply becuase the operand on the left should take precendence because >> its "__add__" is called and its "__add__" returns a list. > > But that's data dependent. When you call > > [1] + MyTuple(1) > > your MyTuple.__radd__ will be called first, not the list's __add__. OK. With this you are beginning to convince me. Yes, I would want my __radd__ called in this case (which is a form of mind-reading, but necessary and convenient)--so your point is how might python read one's mind given list and tuple. You got me there. But you must agree that I am not an easy turn. From eopadoan at altavix.com Thu Feb 8 12:42:37 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Thu, 8 Feb 2007 15:42:37 -0200 Subject: idea for testing tools In-Reply-To: <45CB5494.2070806@gmx.de> References: <87ejp1mzla.fsf@arcor.de> <45ca5f5a$0$26771$426a74cc@news.free.fr> <8764adm2jw.fsf@arcor.de> <45CB5494.2070806@gmx.de> Message-ID: > That's hardly desirable. If one is writing a test library that goes as > far as reparsing the assert statements, I can't see the point of > requiring the user to clutter his test suite with such spurious print > statements. After all, that's one of the main points of test suites in > the first place (that's why there is assertEqual). It will be only be printed when the test fails, along with the rest of the info. The tests will not be "cluttered" by this litle print. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From samckain at southslope.net Wed Feb 14 22:00:00 2007 From: samckain at southslope.net (Steve) Date: Wed, 14 Feb 2007 21:00:00 -0600 Subject: list of range of floats References: Message-ID: On Wed, 14 Feb 2007 18:46:34 +0000, Simon Brunning wrote: > On 2/14/07, Steve wrote: >> After re-reading my original post I was pretty vague. I'm trying to creat >> a list of ranges of floats, 0.0 10.0, 11 20, etc then checking to see if >> an float, example 12.5 falls in the list and if so get the list index of >> where it is in the index. Does this make sense? > > Ah, you want to know if a certain number is between to other numbers. > That's not what range() is for - range() is for generating lists of > integers. You can use it to do a between test for integers, I suppose, > but even for integers it's a pretty poor way of going about it - > you'll be creating a potentially large lists of integers, only to > throw it away again. > > Consider something like: > > def between(lower, upper, target): > return lower < target < upper > > Works for integers and floats interchangably. Or better still, do the > lower < target < upper thing inline. You hit it on the head Simon. Thanks for strightening out my thinking. Steve From mbutscher at gmx.de Mon Feb 12 08:37:15 2007 From: mbutscher at gmx.de (Michael Butscher) Date: Mon, 12 Feb 2007 14:37:15 +0100 Subject: Putting wxFrame on the second monitor Message-ID: <45d06dae$0$30310$9b4e6d93@newsspool1.arcor-online.net> Hi, My software is written with wxPython. At some point it pops up a child- frame of the main frame. The child-frame gets a fixed position in constructor (maybe this is the problem). Now I got reports from users with dual monitor systems that this child- frame is always shown on the primary monitor even if the main frame is on the second. Any hints what I can do here? TIA Michael From alainpoint at yahoo.fr Fri Feb 2 08:08:23 2007 From: alainpoint at yahoo.fr (alain) Date: 2 Feb 2007 05:08:23 -0800 Subject: Why does this not work? In-Reply-To: References: <1170420108.701432.77090@q2g2000cwa.googlegroups.com> Message-ID: <1170421703.561821.326840@k78g2000cwa.googlegroups.com> On Feb 2, 1:57 pm, Bart Van Loon wrote: > It was 2 Feb 2007 04:41:48 -0800, when alain wrote: > > > I tried the following: > > > myobj=object() > > myobj.newattr=5 > > > results in: > > > Traceback (most recent call last): > > File "", line 1, in ? > > AttributeError: 'object' object has no attribute 'newattr' > > > Any idea? > > I think it's because... object has no attribute 'newattr' > > what else is there left to say? > > try: > > myobj=object() > print dir(myobj) > > does that contain 'myattr'? > > -- > groetjes, > BBBart > > "To make a bad day worse, spend it wishing for the impossible." -Calvin What about this: class Object(object):pass myobj=Object() myobj.newattr=5 and it works !!! Python allows the dynamic creation of attributes for an instance of an object. Alain From edreamleo at charter.net Fri Feb 16 07:02:59 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 06:02:59 -0600 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: > There are a tool called "2to3" that translates things like "print foo" to > print(foo). The point of my original post was that if I want to maintain a common code base the tool must translate 'print foo' to 'print2(foo)'. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From gigs at hi.t-com.hr Tue Feb 6 08:02:19 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 06 Feb 2007 14:02:19 +0100 Subject: List Behavior when inserting new items In-Reply-To: <1170099535.989235.35800@a75g2000cwd.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <1170099535.989235.35800@a75g2000cwd.googlegroups.com> Message-ID: wittempj at hotmail.com wrote: > On Jan 29, 7:57 pm, "Drew" wrote: >> I'm looking to add an element to list of items, however I'd like to >> add it at a specific index greater than the current size: >> >> list = [1,2,3] >> list.insert(10,4) >> >> What I'd like to see is something like: >> >> [1,2,3,,,,,,4] >> >> However I see: >> >> [1,2,3,4] >> >> Is there any way to produce this kind of behavior easily? >> >> Thanks, >> Drew > > You could write your own class mimicing a list with your desired > behaviour, something like: > > py>class llist(object): > py> def __init__(self, arg = []): > py> self.__list = arg > py> def __setitem__(self, key, value): > py> length = len(self.__list) > py> if length < key: > py> for i in range(length, key +1): > py> self.__list.append(None) > py> self.__list[key] = value > py> def __str__(self): > py> return str(self.__list) > py> > py>x = llist() > py>x[10] = 1 > py>print x > [None, None, None, None, None, None, None, None, None, None, 1] > > for other methods to add to the llist class see http://docs.python.org/ > ref/sequence-types.html > or like this >>> class Llist(list): def __init__(self): list.__init__(self) def insertatindex(self, index, value): lenght = len(self) if lenght < index: for i in range(lenght, index): self.append(None) self.insert(index, value) From skip at pobox.com Wed Feb 7 13:20:55 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 7 Feb 2007 12:20:55 -0600 Subject: Why doesn't my heapify work? In-Reply-To: References: <52uiomF1olkevU1@mid.uni-berlin.de> Message-ID: <17866.6279.950548.197588@montanaro.dyndns.org> ruan> Can't range go from larger to smaller? Yes. Read the doc: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. To go from larger to smaller you need a negative step size. Also, note that the endpoint is never included. range(10) serves up 0 throu 9. Skip From grahamd at dscpl.com.au Mon Feb 5 18:08:27 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 5 Feb 2007 15:08:27 -0800 Subject: Python does not play well with others In-Reply-To: <7x3b5k8d4e.fsf@ruckus.brouhaha.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170711562.894756.120270@h3g2000cwc.googlegroups.com> <7x3b5k8d4e.fsf@ruckus.brouhaha.com> Message-ID: <1170716907.358882.24920@a34g2000cwb.googlegroups.com> On Feb 6, 9:15 am, Paul Rubin wrote: > "Graham Dumpleton" writes: > > Yes, these per VirtualHost interpreter instances will only be created > > on demand in the child process when a request arrives which > > necessitates it be created and so there is some first time setup for > > that specific interpreter instance at that point, but the main Python > > initialisation has already occurred so this is minor. > > Well ok, but what if each of those interpreters wants to load, say, > the cookie module? Do you have separate copies of the cookie module > in each interpreter? Does each one take the overhead of loading the > cookie module? Each interpreter instance will have its own copy of any Python based code modules. You can't avoid this as Python code is so modifiable that they have to be separate else you would be modifying the same instance as used by a different interpreter which could screw up the other applications view of the world. The whole point of having separate interpreters is to avoid applications trampling on each other. If you really are concerned about multiple loading, use the PythonInterpreter directive to specifically say that applications running under different VirtualHost containers should use the same interpreter. Note though, that although you can run multiple applications in one interpreter in many cases, it may not be able to be done in others. For example, it is not possible to run two instances of Django within the one interpreter instance. The first reason as to why this can't be done is that Django expects certain information about its configuration to come from os.environ. Since there is only one os.environ it can't have two different values for each application at the same time. Some may argue that in 'prefork' you could just change os.environ to be correct for the application for the current request and this effectively is what the mod_python adapter for Django does, but this will fail when 'worker' MPM or Windows is used. I suspect this is the where the idea that Django can't be run on 'worker' MPM came from. Although the documentation for Django suggests it is a mod_python problem, it is actually a Django problem. This use of os.environ by Django also means that Django isn't a well behaved WSGI application component. :-( > It would be neat if there was a way of including > frequently used modules in the shared text segment of the > interpreters, as created during the initial build process. GNU Emacs > used to do something like that with a contraption called "unexec" (it > could dump out parts of its data segment into a pure (shared) > executable that you could then run without the overhead of loading all > those modules) but the capability went away as computers got faster > and it became less common to have a lot of Emacs instances weighing > down timesharing systems. Maybe it's time for a revival of those > techniques. I don't see it as being applicable. Do note that provided there are precompiled byte code files for .py files then load time is at least reduced because Python doesn't have to recompile the code. This actually can be quite significant. Graham From pavlovevidence at gmail.com Wed Feb 21 05:25:44 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 21 Feb 2007 02:25:44 -0800 Subject: BDFL in wikipedia In-Reply-To: References: Message-ID: <1172053544.515756.28200@v45g2000cwv.googlegroups.com> On Feb 20, 9:27 pm, "Jorge Vargas" wrote: > Hi I just hit this page in wikipedia BDFL[1] > > and it redirected me to Guido's wikipedia[2] entry > now without causing any troubles (read flamewar) shouldn't > > a) that page have an explanation of what BDFL is > b) shouldn't it mention Linus, Larry Wall, others?[3] Since when is Larry Wall benevolent? He should be called the SDFL. :) Carl Banks From steve at holdenweb.com Fri Feb 16 09:53:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 09:53:58 -0500 Subject: Pickling of generators In-Reply-To: References: Message-ID: KIaus Muller wrote: > Generators are becoming more and more important and powerful in Python. > The inability of pickle to save/restore generators has become a major > (and growing) limitation to the full exploitation of generators. > > The requirement for pickling generators has already been raised in 2003. > > My project (SimPy - Simulation in Python) has had this requirement since > its inception in 2002. Generator pickling would make saving and > reloading simulation state trivial. The workarounds one has to use > without this capability are baroque and beyond the expertise of a > typical simulation user. > > Is there any hope of action in this area in the foreseeable future? > I doubt it, though who can know what's in the minds of other developers. You might want to look at Stackless Python, which allows you to pickle tasklets and resume them - even on a machine of a different architecture. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From BEpstein at BBWG.COM Fri Feb 2 16:45:04 2007 From: BEpstein at BBWG.COM (Brian Epstein) Date: Fri, 2 Feb 2007 16:45:04 -0500 Subject: what are you using python language for? Message-ID: Brian Y. Epstein, Esq. Belkin Burden Wenig & Goldman LLP 270 Madison Avenue New York, New York 10016 Bus: (212) 867-4466 (x363) Fax: (212) 867-0709 bepstein at bbwg.com ---------------------------------------------------------------------- This message contains information which may be confidential and privileged. Unless you are the addressee (or authorized to receive for the addressee), you may not use, copy, or disclose to anyone the message or any information contained in the message. If you have received the message in error, please advise the sender by reply e-mail or reply to info at bbwg.com , and delete the message. ---------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From m_tayseer82 at yahoo.com Wed Feb 21 10:09:47 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Wed, 21 Feb 2007 07:09:47 -0800 (PST) Subject: outlook bar like widget In-Reply-To: Message-ID: <782542.27928.qm@web31106.mail.mud.yahoo.com> This is a module that does what you want using Tkinter ---------------- from Tkinter import * class OutlookBar(Frame): def __init__(self, *args, **options): Frame.__init__(self, *args, **options) self.panes = {} def add_pane(self, name, pane): self.panes[name] = pane pane.pack(side=TOP, fill=X) def get_frame(self, name): return self.panes[name] class OutlookPane(Frame): def __init__(self, *args, **options): if options.get('text'): text = options['text'] del options['text'] Frame.__init__(self, *args, **options) self.btn = Button(self, text=text, command=self.toggle_collapse) self.btn.pack(side=TOP, fill=X) self.child_frame = Frame(self) self.child_frame.pack(side=TOP, fill=X) if options.get('collapsed'): self.collapsed = True del options['collapsed'] else: self.collapsed = False self.child_frame.pack(side=TOP, fill=X) def frame(self): return self.child_frame def toggle_collapse(self): if self.collapsed: self.child_frame.pack(side=TOP) # show else: self.child_frame.pack_forget() self.collapsed = not self.collapsed def add_widget(self, widget): widget.pack(side=TOP) if __name__ == '__main__': root = Tk() root.title('Outlook Bar Demo') bar = OutlookBar(root) bar.pack(expand=1, fill=BOTH) bar.add_pane('pane1', OutlookPane(bar, text='Hello')) pane1 = bar.get_frame('pane1') pane1.add_widget(Button(pane1.frame(), text='Button 1')) pane1.add_widget(Button(pane1.frame(), text='Button 2')) pane1.add_widget(Button(pane1.frame(), text='Button 3')) bar.add_pane('pane2', OutlookPane(bar, text='Zankalon')) pane2 = bar.get_frame('pane2') pane2.add_widget(Button(pane2.frame(), text='Button 1')) pane2.add_widget(Button(pane2.frame(), text='Button 2')) pane2.add_widget(Button(pane2.frame(), text='Button 3')) mainloop() ---------------- --------------------------------- The fish are biting. Get more visitors on your site using Yahoo! Search Marketing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From melih.onvural at gmail.com Thu Feb 1 01:15:48 2007 From: melih.onvural at gmail.com (Melih Onvural) Date: 31 Jan 2007 22:15:48 -0800 Subject: SyntaxError: 'return' outside function In-Reply-To: References: <1170278702.599741.212420@l53g2000cwa.googlegroups.com> Message-ID: <1170310547.974938.323810@a34g2000cwb.googlegroups.com> Thanks all, I did a massive make sure everything is indents and not spaces across all of my files and now things are running much more smoothly. I appreciate the responses. --melih On Jan 31, 4:49 pm, s... at pobox.com wrote: > Melih> Has anyone seen this error before and been able to solve it? I > Melih> can't seem to find anything that leads to a solution. > > Your code is incorrectly indented. Try: > > def legiturl(self, url): > # this breaks down the url into 6 components to make sure it's "legit" > t = urlparse.urlparse(url) > > if t[0] != 'http': > return "" > > # remove URL fragments, but not URL > if len(t[5]) > 0: > url = urlparse.urlunparse((t[0],t[1],t[2],"","","")) > t = urlparse.urlparse(url) > > # stupid parser sometimes leaves frag in path > x = find(t[2], '#') > if x >= 0: > return "" > > instead. Note also the lack of a return at the end of the function. > > Skip From grisha at apache.org Thu Feb 15 16:54:13 2007 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Thu, 15 Feb 2007 16:54:13 -0500 Subject: ANNOUNCE: Mod_python 3.3.1 Message-ID: <20070215165246.H48122@grisha.dyndns.org> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the 3.3.1 release of mod_python. Mod_python 3.3.1 is considered a stable release, suitable for production use. Mod_python is an Apache HTTP Server module that embeds the Python language interpreter within the server. With mod_python you can write web-based applications in Python that will run many times faster than traditional CGI and will have access to advanced features such as ability to maintain objects between requests, access to httpd internals, content filters and connection handlers. The 3.3.1 release has many new features, feature enhancements, fixed bugs and other improvements over the previous version. See Appendix A of mod_python documentation for more details. Mod_python 3.3.1 is released under the new Apache License version 2.0. Mod_python 3.3.1 is available for download from: http://httpd.apache.org/modules/python-download.cgi More infromation about mod_python is available at: http://httpd.apache.org/modules/ Many thanks to everyone who contributed to and helped test this release, without your help it would not be possible! Regards, The Apache Mod_python team. From kooch54 at gmail.com Wed Feb 7 09:36:57 2007 From: kooch54 at gmail.com (kooch54 at gmail.com) Date: 7 Feb 2007 06:36:57 -0800 Subject: Group Membership in Active Directory Query In-Reply-To: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> Message-ID: <1170859017.416570.247920@v33g2000cwv.googlegroups.com> On Feb 7, 9:22 am, kooc... at gmail.com wrote: > I am trying to write a script to simply query the group members in an > active directory group. I need to use LDAP to make sure I capture any > global > global group nestings that may occur. I already have a > function that uses WinNT provider to capture this info from NT4 or AD > domains and it works beautifully. It just doesn't capture global > > global nestings. I am having great difficulties in getting this to > work on AD though with ldap. I have a multiple domain tree > environment and need to be able to query groups in different domains. > I want to simply make an ldap connection, bind to it, search for the > group and get it's members. > I do the following for eDirectory and it works great but not in AD. > > import ldap > l=ldap.open(1.2.3.4,trace_level = 1) > l.simple_bind_s('cn=username,ou=company','password') > UserRes = UserRes + l.search_s( > o=company, > ldap.SCOPE_SUBTREE, "(|'cn=groupname') > > If I do the same thing as above but to an AD source it doesn't work. > I run the open and it seems successful, I run the bind using DN, UPN, > or domain name and password and it seems to bind, I run the query and > it says I must complete a successfull bind operation before doing a > query. > > Any help is appreciated. I found an example in the groups here and attempted it but it failed as well. Below is the code I used and the results. import ldap, ldapurl proto = 'ldap' server = 'domaincontroller.domain.company.com' port = 389 url = ldapurl.LDAPUrl(urlscheme=proto, hostport="%s:%s" % (server, str(port))).initializeUrl() ldap_obj = ldap.initialize(url) # !!!password will be on wire in plaintext!!! ldap_obj = ldap_obj.simple_bind_s('username at domain.company.com', 'password') base = 'DC=DOMAIN, DC=COMPANY, DC=COM' scope = ldap.SCOPE_SUBTREE query = '(objectclass=user)' res_attrs = ['*'] res = ldap_obj.search_ext_s(base, scope, query, res_attrs) print res RESULTS FROM PYTHON SHELL res=ldap_obj.search_ext_s(base, scope, query, rest_attrs) AttributeError: 'NoneType' object has no attribute 'search_Ext_s' From tom.theisen at gmail.com Thu Feb 15 10:54:45 2007 From: tom.theisen at gmail.com (tomtheisen@tomtheisen.com) Date: 15 Feb 2007 07:54:45 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <1171472657.567241.302690@h3g2000cwc.googlegroups.com> Message-ID: <1171554885.700403.102020@q2g2000cwa.googlegroups.com> On Feb 14, 11:46 am, "Gabriel Genellina" wrote: > En Wed, 14 Feb 2007 14:04:17 -0300, Andy Dingley > escribi?: > > > I still don't understand what a lambda is _for_ in Python. I know what > > they are, I know what the alternatives are, but I still haven't found > > an instance where it permits something novel to be done that couldn't > > be done otherwise (if maybe not so neatly). > > A lambda is a shorthand for a simple anonymous function. Any lambda can be > written as a function: > > lambda args: expression > > is the same as: > > def __anonymous(args): return expression > > (but the inverse is not true; lambda only allows a single expression in > the function body). > > Except for easy event binding in some GUIs, deferred argument evaluation, > and maybe some other case, the're not used much anyway. Prior common usage > with map and filter can be replaced by list comprehensions (a lot more > clear, and perhaps as fast - any benchmark?) > > -- > Gabriel Genellina They are still useful for reduce(), which has no listcomp equivalent that I know of. From n00b at n00b.n00b.n00b Fri Feb 2 15:39:00 2007 From: n00b at n00b.n00b.n00b (Mister Newbie) Date: Fri, 02 Feb 2007 15:39:00 -0500 Subject: Where Does One Begin? Message-ID: I have no programming experience. I want to learn Python so I can make simple, 2D games. Where should I start? Can you recommend a good book? Thank you. From gigs at hi.t-com.hr Thu Feb 15 18:10:21 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 16 Feb 2007 00:10:21 +0100 Subject: Tkinter __call__ Message-ID: from Tkinter import * from tkFileDialog import askopenfilename from tkColorChooser import askcolor from tkMessageBox import askquestion, showerror from tkSimpleDialog import askfloat demos = { 'Open': askopenfilename, 'Color': askcolor, 'Query': lambda: askquestion('Warning', 'You typed "..."\nConfirm?'), 'Error': lambda: showerror('Error!', "He's dead, Jim"), 'Input': lambda: askfloat('Entry', 'Enter credit card number') } class Demo(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack() Label(self, text="Basic demos").pack() for (key, value) in demos.items(): func = (lambda key=key: self.printit(key)) Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) def printit(self, name): print name, 'returns =>', demos[name]() I have tried but cant get it to work properly. I want to instead printit method to put __call__ and call it like that Can someone help me, please? From attn.steven.kuo at gmail.com Wed Feb 28 20:27:57 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 28 Feb 2007 17:27:57 -0800 Subject: text wrapping help In-Reply-To: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> References: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> Message-ID: <1172712476.946180.63140@t69g2000cwt.googlegroups.com> On Feb 28, 4:06 pm, "Ryan K" wrote: > I'm trying to text wrap a string but not using the textwrap module. I > have 24x9 "matrix" and the string needs to be text wrapped according > to those dimensions. Is there a known algorithm for this? Maybe some > kind of regular expression? I'm having difficulty programming the > algorithm. Try: import re sample_text = """Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet.""" # assume 24 is sufficiently wide: lines = map(lambda x: x.rstrip(), re.findall(r'.{1,24}(?:(?<=\S)\s|$)', sample_text.replace("\n", " "))) print "\n".join(lines) -- Hope this helps, Steven From harlinseritt at yahoo.com Wed Feb 21 19:46:19 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 21 Feb 2007 16:46:19 -0800 Subject: Convert to binary and convert back to strings In-Reply-To: References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <1172105179.708565.201600@v33g2000cwv.googlegroups.com> On Feb 21, 7:12 pm, Larry Bates wrote: > Harlin Seritt wrote: > > Hi... > > > I would like to take a string like 'supercalifragilisticexpialidocius' > > and write it to a file in binary forms -- this way a user cannot read > > the string in case they were try to open in something like ascii text > > editor. I'd also like to be able to read the binary formed data back > > into string format so that it shows the original value. Is there any > > way to do this in Python? > > > Thanks! > > > Harlin > > I promise you that everything written to a file is done in binary. > Computers don't know how to work with anything BUT binary. I think > what you want to do is to encrypt/obstifucate the string. For that > you will need to encrypt the string, write it out, read it back in, > and decrypt it. If you want it to be REALLY strong use pyCrypto > and something like AES-256. > > http://www.amk.ca/python/code/crypto > > If you just want to make it somewhat hard for someone to decypher > you can do something like below (sorry I can't remember where I > found this to attribute to someone): > import random > import zlib > import time > > def tinycode(key, text, reverse=False): > rand = random.Random(key).randrange > if not reverse: > text = zlib.compress(text) > text = ''.join([chr(ord(elem)^rand(256)) for elem in text]) > if reverse: > text = zlib.decompress(text) > return text > > def strToHex(aString): > hexlist = ["%02X" % ord(x) for x in aString] > return ''.join(hexlist) > > def HexTostr(hString): > res = "" > for i in range(len(hString)/2): > realIdx = i*2 > res = res + chr(int(hString[realIdx:realIdx+2],16)) > return res > > if __name__ == "__main__": > > keyStr = "This is a key" > #testStr = "which witch had which witches wrist watch abc def ghi" > > testStr=time.strftime("%Y%m%d", time.localtime()) > > print "String:", testStr > etestStr = tinycode(keyStr, testStr) > print "Encrypted string:", etestStr > hex=strToHex(etestStr) > print "Hex : ", hex > print "Len(hex):", len(hex) > nonhex=HexTostr(hex) > #testStr = tinycode(keyStr, etestStr, reverse=True) > testStr = tinycode(keyStr, nonhex, reverse=True) > print "Decrypted string:", testStr > > WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM. It is just a > nuisance for someone that really wants to decrypt the string. But > it might work for your application. > > -Larry Thanks Larry! I was looking for something more beautiful but what the hey, it works! Harlin From __peter__ at web.de Sat Feb 3 12:23:30 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 18:23:30 +0100 Subject: How can I access data from MS Access? References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> <45c4bee4$0$453$426a74cc@news.free.fr> <1170522973.012926.252510@k78g2000cwa.googlegroups.com> Message-ID: Finger.Octopus at gmail.com wrote: > On Feb 3, 10:27 pm, Bruno Desthuilliers >> "doesn't work" is the worst possible description of a problem. Did it >> print out some insults in a foreign language ? wipe out your HD ? Else ? > I havn't said "doesn't work", I rather doesn't seem to work. Bruno, admit that you were wrong. Finger.Octopus is able to give a description that is even worse than what you deemed possible :-) Peter From martin at v.loewis.de Fri Feb 23 15:20:43 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 23 Feb 2007 21:20:43 +0100 Subject: Finding non ascii characters in a set of files In-Reply-To: References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: <45DF4C9B.8030405@v.loewis.de> Tim Arnold schrieb: > That looks much cleaner. I didn't know the 'num' from the enumerate would > persist so the except block could report it. It's indeed guaranteed that the for loop index variables will keep the value they had when the loop stopped (either through regular termination, break, or an exception) (unlike list comprehensions, where the variable also stays, but only as a side effect of the implementation strategy). Regards, Martin From hg at nospam.org Thu Feb 22 05:55:37 2007 From: hg at nospam.org (hg) Date: Thu, 22 Feb 2007 11:55:37 +0100 Subject: How to covert ASCII to integer in Python? References: Message-ID: <6OkDh.177594$IL1.143903@newsfe13.lga> John wrote: > Is there any built in function that converts ASCII to integer or vice > versa in Python? > > Thanks! >>> int('10') 10 >>> str(10) '10' >>> From bearophileHUGS at lycos.com Fri Feb 23 01:34:59 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Feb 2007 22:34:59 -0800 Subject: What is the best queue implemetation in Python? In-Reply-To: References: Message-ID: <1172212499.165842.249360@t69g2000cwt.googlegroups.com> John: > I want to write a code for Breadth First Traveral for Graph, which needs a > queue to implement. For that purpose I have used the good deque that you can find in collections in the standard library. It's very good for queues, and it's a bit faster than regular lists for stacks too. Bye, bearophile From mail at microcorp.co.za Tue Feb 13 00:57:43 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 13 Feb 2007 07:57:43 +0200 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> <1171264811.509582.224870@p10g2000cwp.googlegroups.com> Message-ID: <021901c74f4e$8827c6a0$03000080@hendrik> "John Machin" wrote: > Now for the algorithm: all of that testing to see if you are about to > sail off the end of the world is a bit ugly and slow. You can use bit- > bashing, as Paul suggested, even though it's on Steven D'Aprano's list > of 6 deadly sins :-) Thou shallt not bit - bash What are the other five? - Hendrik From steve at holdenweb.com Thu Feb 15 06:32:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 11:32:47 +0000 Subject: hi all In-Reply-To: References: Message-ID: Sandeep Patil , Bangalore wrote: > I get an error while I try to call python through VB. > > The error is ? Error 429: Active X cant create object? > > > > Pls anybody help me to call python through VB. > The problem is on line 23 of your code. Sorry, that was a rather flip way of saying that without seeing some actual code it's very difficult to know what will help. Do you get a Python stack traceback? If so that would also help. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From paul at boddie.org.uk Tue Feb 20 10:33:48 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Feb 2007 07:33:48 -0800 Subject: Python-list Digest, Vol 41, Issue 286 In-Reply-To: References: Message-ID: <1171985628.541804.65740@h3g2000cwc.googlegroups.com> On 20 Feb, 11:59, KoDer wrote: > > Subject: Can I reverse eng a .pyc back to .py? [...] > https://svn.cs.pomona.edu/sys/src/konane/pyunparse.py > > Need add new AST nodes if You want to use it with python2.5. The above code seems to need to parse a source file, since it uses the compiler module's parse function. Something like decompyle would be more appropriate for reverse engineering purposes: http://packages.qa.debian.org/d/decompyle.html Paul From kairosenthal at tiscali.de Fri Feb 9 06:30:42 2007 From: kairosenthal at tiscali.de (Kai Rosenthal) Date: 9 Feb 2007 03:30:42 -0800 Subject: resolve environment variables in string - regular expression Message-ID: <1171020642.655125.164880@p10g2000cwp.googlegroups.com> Hello, how can I resolve envionment variables in a string. e.g. strVar = /myVar resolve in str1 = /mytest02/$MYVAR/mytest02 --> /mytest02//myVar/mytest02 (unix) str2 =$MYVAR/mytest03 --> /myVar/mytest03 (unix) str3 =%MYVAR%/mytest03 --> /myVar/mytest03 (windows) I would not set the variables in this time. I think I need a little regular expression code snippet, but I have not work with regular expression before. Thanks for your help, Kai. From http Mon Feb 19 18:53:52 2007 From: http (Paul Rubin) Date: 19 Feb 2007 15:53:52 -0800 Subject: Newbie help looping/reducing code References: Message-ID: <7x1wkl901b.fsf@ruckus.brouhaha.com> Lance Hoffmeyer writes: > T2B = even_odd_round(float(str(T2B))) > VS = even_odd_round(float(str(VS))) > SS = even_odd_round(float(str(SS))) > sh.Cells(21,lastcol+1).Value = float(str(T2B))/100 > sh.Cells(22,lastcol+1).Value = float(str(VS))/100 > sh.Cells(23,lastcol+1).Value = float(str(SS))/100 First of all, I don't understand float(str(VS)) and so forth; if VS is (say) an integer, you can say float(VS) directly. Second, even_odd_round is written in a way that it can accept either an int or a float. So assuming you need to keep those variables around, I'd write the first three lines of the above as: T2B = even_odd_round(T2B) VS = even_odd_round(VS) SS = even_odd_round(SS) or you could get fancier and say T2B, VS, SS = map(even_odd_round, (T2B, VS, SS)) Then you could write the next three lines as a loop: for i,v in ((21, T2B), (22, VS), (23,SS)): sh.Cells(i, lastcol+1) = float(v) / 100.0 From pablo at sigex.com Wed Feb 21 07:15:54 2007 From: pablo at sigex.com (pablo at sigex.com) Date: 21 Feb 2007 04:15:54 -0800 Subject: Performance project for the SigEx Foundry Message-ID: <1172060154.122555.190330@k78g2000cwa.googlegroups.com> have been testing performances of different scripting languages fordatabase access, text processing and client application data transfer. So far, I am getting better performance from PHP, but I don't have any hard data to back it up compared to others. This is a large project for the SigEx Foundry and it involves hundreds of servers. I am looking for articles/studies/benchmarks on the subject. Thank you, Pablo Server Side Developer Student for the SigEx Foundry funded by SigEx Ventures From gigs at hi.t-com.hr Fri Feb 2 11:10:11 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 02 Feb 2007 17:10:11 +0100 Subject: coping directories In-Reply-To: References: Message-ID: Jussi Salmela wrote: > Gigs_ kirjoitti: >> hi people >> >> I have problem with this example, not actually the problem, but >> [code] >> class FileVisitor(object): >> def __init__(self, data=None): >> self.context = data >> def run(self, startdir=os.curdir): >> os.path.walk(startdir, self.visitor, None) >> def visitor(self, data, dirname, filesindir): >> self.visitdir(dirname) >> for fname in filesindir: >> fpath = os.path.join(dirname, fname) >> if not os.path.isdir(fpath): >> self.visitfile(fpath) >> def visitdir(self, dirpath): # override or extend this >> method >> print dirpath, '...' >> def visitfile(self, filepath): # override or extend this >> method >> print self.fcount, '=>', filepath >> # >> class CVisitor(FileVisitor): >> def __init__(self, fromdir, todir): >> self.fromdirLen = len(fromdir) + 1 # here is my problem >> self.todir = todir >> FileVisitor.__init__(self, fromdir) >> def visitdir(self, dirpath): >> topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) >> os.mkdir(topath) >> def visitfile(self, filepath): >> topath = os.path.join(self.todir, filepath[self.fromdirLen:]) >> cpfile(filepath, topath) #copy contents from filepath to >> topath[/code] >> >> >> When I copy contents from C:\IronPython to C:\temp >> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this >> self.fromdirLen = len(fromdir) + 1 >> but when I change self.fromdirLen = len(fromdir) + 1 to >> self.fromdirLen = len(fromdir) i get contents copied to C:\ (actually >> to parent dir) >> >> Can anyone explain me that? >> >> Thanks!!! >> :o > > Why do you want to change a working program anyway? :) > > The result of your change is that os.path.join does the join > differently. Before the change the join is, for example: > os.path.join(r'c:\temp', r'AUTOEXEC.BAT') > with a result: > c:\temp\AUTOEXEC.BAT > > After your change the join is: > os.path.join(r'c:\temp', r'\AUTOEXEC.BAT') > with a result: > \AUTOEXEC.BAT > > This is described in the doc: > > join( path1[, path2[, ...]]) > > Join one or more path components intelligently. If any component is an > absolute path, all previous components (on Windows, including the > previous drive letter, if there was one) are thrown away, and joining > continues. > > HTH, > Jussi thats what i need to know Thanks From greg at cosc.canterbury.ac.nz Wed Feb 21 00:27:32 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 21 Feb 2007 18:27:32 +1300 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> <7x1wkkxnmn.fsf@ruckus.brouhaha.com> Message-ID: <5423mbF1uudv4U1@mid.individual.net> John Nagle wrote: > It's a bit > embarassing that the main implementation of Python is still a > pure interpreter. Even Javascript has a JIT compiler now. Pure interpreted Python has always seemed more responsive to me than any Java application I've tried to use. So I can't help feeling that this JIT business is over-hyped. -- Greg From google at orcon.net.nz Sun Feb 18 07:42:06 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 18 Feb 2007 04:42:06 -0800 Subject: How do I save the contents of a text buffer In-Reply-To: References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> <1171761050.149331.208910@v45g2000cwv.googlegroups.com> Message-ID: <1171802526.339977.153730@p10g2000cwp.googlegroups.com> Solved! # Output file outfile = open("newbannedsitelist", "w") outfile.write(textbuffer.get_text(textbuffer.get_start_iter(), textbuffer.get_end_iter(), include_hidden_chars=True)) outfile.close() I'm new to Python and GTK and may not be asking the right type of questions initially. I programmed with C many many years ago and my programming instincts are very rusty so still feeling my way again with this stuff. Apologies for the sarcastic reply earlier but i felt your initial reply to be sarcastic. I also did research this problem but seemed to be getting nowhere - thats why I asked for the groups help. Anyway, thanks to all that replied via emailed and in this group. On Feb 18, 7:34 pm, Steven D'Aprano wrote: > On Sat, 17 Feb 2007 17:10:50 -0800, google wrote: > > I just included file opening code just to show how i read the file > > into the text buffer - I have no issues with this as such. Problem is > > only with the writing of the text buffer back to a file. When I try to > > write the buffer to a file it gave the following, > > > > > Traceback (most recent call last): > > File "./configbox.py", line 78, in ? > > TextViewExample() > > File "./configbox.py", line 53, in __init__ > > outfile.write(textbuffer.get_text(0,1000, > > include_hidden_chars=True)) > > TypeError: start should be a GtkTextIter > > Ah, well there's your problem. start should be a GtkTextIter, just like > the exception says. > > Question for you: in the line of code in the traceback, which function > takes an argument called "start"? > > > How can I use outfile.write() to wite the contents of the text buffer > > correctly? > > Your problem isn't with outfile.write(). > > -- > Steven. From gagsl-py at yahoo.com.ar Fri Feb 16 05:44:38 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 07:44:38 -0300 Subject: KeyboardInterrupt not caught References: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 07:26:09 -0300, Steven D'Aprano escribi?: > I seem to have a vague recollection that the keyboard interrupt under > Windows isn't ^C but something else... ^Z maybe? Ctrl-C is the keyboard interrupt, Ctrl-Z means EOF. -- Gabriel Genellina From gdamjan at gmail.com Fri Feb 9 15:27:36 2007 From: gdamjan at gmail.com (Damjan) Date: Fri, 09 Feb 2007 21:27:36 +0100 Subject: ANN: Wing IDE 2.1.4 Released References: Message-ID: <45ccd9a4$0$49207$14726298@news.sunsite.dk> > This is a bug fix release that among other things fixes handling of > UTF-8 byte order marks, What are UTF-8 byte order marks ?!? There's only one order in the UTF-8 bytes! -- damjan From bob at work.org Tue Feb 13 18:07:10 2007 From: bob at work.org (Martien Friedeman) Date: 14 Feb 2007 12:07:10 +1300 Subject: Testers please References: <8cde9$45d179ba$83aef404$16072@news1.tudelft.nl> Message-ID: <45d2449e$1@clear.net.nz> Thanks Stef! I looked at that area of storing large structures. That would seriously make the whole thing much more complicated. Say you have object 'foo' and it has lots of attributes. If you're only accessing foo.length in the statement 'if foo.length > 12:' why should I store everything about foo? Its 'length' is the only attribute accessed, therefore I only store its 'length'. And therefore you can not click on 'foo', only on 'length'. No video shows such an example though. On the other hand if you had the statement 'if foo:' then 'foo' would be able to be clicked, and it would say '<__main__.Foo instance ... etc. The usual. No attributes though. The interface is web based; I was going to make it as universal as possible. The web server is required to do the Ajax thing and display pages. Makes it harder to install too, unfortunately. The size of the 'recording' is a major drawback, it was clearly not meant to record the processing of millions of records. I need to find a way to specify the area in the code that needs recording. Thanks for the suggestions. From paul at boddie.org.uk Fri Feb 16 09:16:52 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Feb 2007 06:16:52 -0800 Subject: Approaches of interprocess communication In-Reply-To: <53lranF1th0pcU1@mid.uni-berlin.de> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <45d5a499$0$5995$b9f67a60@news.newsdemon.com> <1171631180.776312.258100@v33g2000cwv.googlegroups.com> <53lp57F1t2g4mU2@mid.uni-berlin.de> <1171633519.379342.306750@j27g2000cwj.googlegroups.com> <53lranF1th0pcU1@mid.uni-berlin.de> Message-ID: <1171635412.076170.57210@p10g2000cwp.googlegroups.com> On 16 Feb, 14:53, "Diez B. Roggisch" wrote: > [XMPP, XML messaging] > Didn't know that. Yet I presume it is pretty awful to manually decompose and > compose the method invocations and parameter sets. It depends on how well you like working with XML, I suppose. > I've got no idea what document-orientied SOAP means either. Is that just > pushing XML-files over a protocol? As I understand it, yes, although you still have to put the payload inside the usual SOAP boilerplate. Paul From JStoneGT at aol.com Tue Feb 13 21:54:29 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Tue, 13 Feb 2007 21:54:29 EST Subject: Please help about an instance var Message-ID: >>> from UserDict import UserDict >>> d = {1:2,3:4,5:6} >>> d1 = UserDict(d) >>> d1 {1: 2, 3: 4, 5: 6} >>> d1.data {1: 2, 3: 4, 5: 6} Here why both d1 and d1.data have the same values?As shown below,they're different types. >>> type(d1) >>> type(d1.data) Please help.Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Tue Feb 20 01:19:38 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 20 Feb 2007 08:19:38 +0200 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> Message-ID: <000001c754bc$817baf60$03000080@hendrik> "Jay Tee" wrote: > Hi, > > I have some code that does, essentially, the following: > > - gather information on tens of thousands of items (in this case, jobs > running on a > compute cluster) > - store the information as a list (one per job) of Job items > (essentially wrapped > dictionaries mapping attribute names to values) > > and then does some computations on the data. One of the things the > code needs to do, very often, is troll through the list and find jobs > of a certain class: > > for j in jobs: > if (j.get('user') == 'jeff' and j.get('state')=='running') : > do_something() > > This operation is ultimately the limiting factor in the performance. > What I would like to try, if it is possible, is instead do something > like this: > When you are gathering the data and building the lists - why do you not simultaneously build a dict of running jobs keyed by the Jeffs? - Hendrik From mail at microcorp.co.za Mon Feb 26 00:15:43 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 26 Feb 2007 07:15:43 +0200 Subject: Help on Dict References: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> Message-ID: <014a01c7596d$13f3ca80$03000080@hendrik> "James Stroud" wrote: > Clement wrote: > > Can any body tell how Dict is implemented in python... plz tell what > > datastructure that uses................ > > > > I think it uses a dict. "Groan!" - this answer is like Microsoft documentation - while technically correct, it is useless... : - ) The key of a dict entry is subjected to a bit of magic called a "Hashing algorithm" that yields a "bin" in which the data is kept. So to get hold of a dict entry always takes a similar time. And its the quickest form of random access based on a non integer key that you can get. hth - Hendrik From jstroud at mbi.ucla.edu Wed Feb 28 06:15:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 28 Feb 2007 11:15:12 GMT Subject: Curses sorely lacking an event loop? In-Reply-To: References: Message-ID: <4vdFh.153$8i6.25@newssvr29.news.prodigy.net> Michael Zawrotny wrote: > On Tue, 27 Feb 2007 12:27:17 GMT, James Stroud wrote: >> Is curses really lacking an event loop? Do I have to write my own? I >> infer from the docs that this is the case. For example, I want the >> screen to be updated with resize but I find myself waiting for getch() >> if I want user input, and so the screen must remain ugly until the user >> presses a key. What am I missing? > > I'm not a curses expert, but I can answer this part. When the screen > is resized, SIGWINCH is sent to the process. You can use the normal > signal handling apparatus to install a handler that updates the screen > when that signal arrives. > > > Mike > Thank you. This is good to know. James From steve at REMOVEME.cybersource.com.au Wed Feb 7 19:28:35 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Feb 2007 11:28:35 +1100 Subject: Object type check References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> Message-ID: On Wed, 07 Feb 2007 08:59:12 -0800, king kikapu wrote: > I see what you mean by "duck typing". So you suggest the "do nothing > at all" direction, > better document my code so other can see what is expected, right ? Generally speaking, yes, but not always. The usual Python model is "better to ask forgiveness than permission". For example, these two snippets of code do (more or less) the same thing, but the second is more in the Pythonic style: # Look Before You Leap if isinstance(x, SomeClass): x.somemethod() else: do_something_else() # Better To Ask For Forgiveness Than Permission try: x.somemethod() except AttributeError: # no such method exists do_something_else() Setting up a try...except block is cheap in Python, so it costs very little to try calling the method, then take a different action only if it is one of the rare failures. (However, catching the exception is expensive, so if you have lots of failures, you might want to rethink your strategy.) But sometimes this isn't what you want. Here's a counter example: def modify(list_of_x): for x in list_of_x: x.change_in_place() Note that there's no "do_something_else" to do if an item doesn't have the correct method. That's bad data, and no recovery is possible, so you just let the exception propagate. But there's a problem: if the calling code catches the exception, as it may, you leave the list_of_x in an intermediate state where some of the items have been changed and some haven't. The solution is a form of Look Before You Leap that doesn't break duck-typing: def modify(list_of_x): for x in list_of_x: try: x.change_in_place # don't call the method, just check it exists # we can check as many or as few methods as we need, e.g.: x.__getitem__ # check that x is indexable except AttributeError: raise ValueError("list contains an invalid item") # if we get here, we know it is safe to proceed for x in list_of_x: x.change_in_place() Now each item doesn't have to be an instance of SomeClass, but merely needs to have the right signature. -- Steven D'Aprano From rzantow at gmail.com Fri Feb 2 07:16:50 2007 From: rzantow at gmail.com (rzed) Date: Fri, 02 Feb 2007 07:16:50 -0500 Subject: How do I print out in the standard output coloured lines References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> Message-ID: cniharral at gmail.com wrote in news:1170417631.268771.108090 at v45g2000cwv.googlegroups.com: > Hi, > > I'm interested in printing out coloured lines of my > application and > I don't know what to use. Can anybody give me an idea?? > You could speed up the process if you explain what your application is and what you mean by colored lines. Does your application emit output to a plotter, an ink-jet printer, or a color laser printer? Is it a drawing program? An editor in which you want lines colored to highlight context? It might be useful to know what system you are running as well. Just a little detail here. -- rzed From hg at nospam.org Sun Feb 11 08:12:15 2007 From: hg at nospam.org (hg) Date: Sun, 11 Feb 2007 14:12:15 +0100 Subject: help please!! References: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Message-ID: darren112 wrote: > Hi Im new to python and I desperately need help with this task.... > This is everything of what I need to do....... > > The program to be written in Python obviously...... > > The program should support brute-forcing of the authentication process > for a Telnet server via a dictionary attack. > > The python program is required to take four parameters: a) the IP > address of a Computer, b) the port number that the Telnet server is > running on the computer , c) the name of a file containing a list if > usernames, and b) the name of a file containing a list of word/phrases > to be used as passwords. > > The program should then attempt to authenticate itself to the Telnet > server via trying every password for every username. The program > should report when it is successful. > > Please help me.... And as I am new to all this please post step by > step instructions... That is funny ! From horpner at yahoo.com Fri Feb 9 09:52:36 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 9 Feb 2007 15:52:36 +0100 Subject: doctests for interactive functions References: <45CB77E3.3040108@cc.umanitoba.ca> <87veic9xb2.fsf@benfinney.id.au> Message-ID: On 2007-02-08, Brian van den Broek wrote: > Can I run the rough structure of my code past you to see if it > is in the vicinity of what you mean? (I have removed some > details for sake of a short(er :-)) post.) Yes, this is a good way to think about it. Separate input from validation. The downside is that control flow grows warts. > My .get method looks like: > > def get(self, input_function=raw_input): > while True: > self._prompt_user() > self._input = input_function() > if self._is_valid_input(): > break > else: > self._process_invalid_input() > self._set_data() > > The base class ._prompt_user just displays a prompt. Individual > subclasses might implement ._prompt_user to both display a > prompt, and further information about constraints on valid > inputs, or generate a menu of options on the fly, etc. > > Subclasses implement ._is_valid_input to return True if the > input meets the desired constraints, False otherwise. So, > YesNo._is_valid_input ensures that ._input.lower() is in ['y', > 'n', 'yes', 'no'], for instance. Your scheme may run into trouble with unexpected end of file when input_function is not raw_input. File methods don't raise an exception for EOF, they just return "", the empty string. So you may need to check of that return value, and raise IOError for that case. > ._process_invalid_input is implemented to provide useful > feedback about invalid input. So, > YesNo._process_invalid_input() emits a reminder that a value in > ['y', 'n', 'yes', 'no'] is needed, for instance. > > ._set_data is usually implemented to just store the user's > input as .data, but in some cases, it first subjects it to > further processing. For instance YesNo._set_data sets .data to > True if the user entered a yes value, False if they entered a > no value. > > Is this the sort of thing you mean, or is this the sort of > coupling you suggest I avoid? It has to be coupled somewhere. This seems like a good place to do it. The private methods can all be tested individually, so the doctests for get can be quite simple, or even absent. Note that sequestering the test input in a file doesn't allow for good examples, unfortunately. -- Neil Cerutti From grante at visi.com Sat Feb 10 10:37:18 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 10 Feb 2007 15:37:18 -0000 Subject: [off-topic] Maximum TCP Server Connections References: Message-ID: <12srplenp6gi95@corp.supernews.com> On 2007-02-10, Steve Holden wrote: > Sorry this question isn't strictly Python-related. Does any one know how > many simultaneous TCP connections it's practical to expect a TCP-based > server application to support (on the OS of your choice)? I'm looking > for the restrictions imposed by the operating environment rather than > the application itself. That depends entirely on the operating system environment. For some it's zero. For others it's many thousands. -- Grant Edwards grante Yow! How many retired at bricklayers from FLORIDA visi.com are out purchasing PENCIL SHARPENERS right NOW?? From lbates at websafe.com Thu Feb 22 12:48:18 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 22 Feb 2007 11:48:18 -0600 Subject: How to covert ASCII to integer in Python? In-Reply-To: References: Message-ID: <45DDD762.8060707@websafe.com> John wrote: > Is there any built in function that converts ASCII to integer or vice versa > in Python? > > Thanks! > > You probably should go through the tutorial ASAP that is located here: http://docs.python.org/tut/ Convert ascii string to integer: a='1' b=int(a) Convert integer to ascii string: a=1 b=str(a) or a=1 b="%i" % a -Larry Bates From sjdevnull at yahoo.com Tue Feb 6 16:19:21 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 6 Feb 2007 13:19:21 -0800 Subject: Python does not play well with others In-Reply-To: <1170715521.475189.18330@k78g2000cwa.googlegroups.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> Message-ID: <1170796761.537999.224480@q2g2000cwa.googlegroups.com> On Feb 5, 5:45 pm, "Graham Dumpleton" wrote: > On Feb 6, 8:57 am, "sjdevn... at yahoo.com" wrote: > > > > > On Feb 5, 12:52 pm, John Nagle wrote: > > > > sjdevn... at yahoo.com wrote: > > > > John Nagle wrote: > > > > >>Graham Dumpleton wrote: > > > > >>>On Feb 4, 1:05 pm, Paul Rubin wrote: > > > > >>>>"Paul Boddie" writes: > > > >> Realistically,mod_pythonis a dead end for large servers, > > > >>because Python isn't really multi-threaded. The Global Python > > > >>Lock means that a multi-core CPU won't help performance. > > > > > The GIL doesn't affect seperate processes, and any large server that > > > > cares about stability is going to be running a pre-forking MPM no > > > > matter what language they're supporting. > > > > Pre-forking doesn't reduce load; it just improves responsiveness. > > > You still pay for loading all the modules on every request. > > > No, you don't. Each server is persistent and serves many requests-- > > it's not at all like CGI, and it reuses the loaded Python image. > > > So if you have, say, an expensive to load Python module, that will > > only be executed once for each server you start...e.g. if you have > > Apache configured to accept up to 50 connections, the module will be > > run at most 50 times; once each of the 50 processes has started up, > > they stick around until you restart Apache, unless you've configured > > apache to only serve X requests in one process before restarting it. > > (The one major feature thatmod_python_is_ missing is the ability to > > do some setup in the Python module prior to forking. That would make > > restarting Apache somewhat nicer). > > There would be a few issues with preloading modules before the main > Apache child process performed the fork. > > The first is whether it would be possible for code to be run with > elevated privileges given that the main Apache process usually is > started as root. I'm not sure at what point it switches to the special > user Apache generally runs as and whether in the main process the way > this switch is done is enough to prevent code getting back root > privileges in some way, so would need to be looked into. In our case, the issue is this: we load a ton of info at server restart, from the database. Some of it gets processed a bit based on configuration files and so forth. If this were done in my own C server, I'd do all of that and set up the (read-only) runtime data structures prior to forking. That would mean that: a) The processing time would be lower since you're just doing the pre- processing once; and b) The memory footprint could be lower if large data structures were created prior to fork; they'd be in shared copy-on-write pages. b) isn't really possible in Python as far as I can tell (you're going to wind up touching the reference counts when you get pointers to objects in the page, so everything's going to get copied into your process eventually), but a) would be very nice to have. > The second issue is that there can be multiple Python interpreters > ultimately created depending on how URLs are mapped, thus it isn't > just an issue with loading a module once, you would need to create all > the interpreters you think might need it and preload it into each. All > this will blow out the memory size of the main Apache process. It'll blow out the children, too, though. Most real-world implementations I've seen just use one interpreter, so even a solution that didn't account for this would be very useful in practice. > There is also much more possibility for code, if it runs up extra > threads, to interfere with the operation of the Apache parent process. Yeah, you don't want to run threads in the parent (I'm not sure many big mission-critical sites use multiple threads anyway, certainly none of the 3 places I've worked at did). You don't want to allow untrusted code. You have to be careful, and you should treat anything run there as part of the server configuration. But it would still be mighty nice. We're considering migrating to another platform (still Python-based) because of this issue, but that's only because we've gotten big enough (in terms of "many big fat servers sucking up CPU on one machine", not "tons of traffic") that it's finally an issue. mod_python is still very nice and frankly if our startup coding was a little less piggish it might not be an issue even now--on the other hand, we've gotten a lot of flexibility out of our approach, and the code base is up to 325,000 lines of python or so. We might be able to refactor things to cut down on startup costs, but in general a way to call startup code only once seems like the Right Thing(TM). From edloper at gradient.cis.upenn.edu Tue Feb 27 02:37:47 2007 From: edloper at gradient.cis.upenn.edu (Edward Loper) Date: Tue, 27 Feb 2007 02:37:47 -0500 Subject: Epydoc 3.0 beta release Message-ID: <0907700F-8391-4AA8-9217-527C84BC74F8@gradient.cis.upenn.edu> Epydoc 3.0 beta is now available for download from SourceForge. Epydoc is a tool for generating API documentation for Python modules, based on their docstrings. - The epydoc homepage. - Download epydoc 3.0 beta. For some examples of the documentation generated by epydoc, see: - The API documentation for epydoc. - The API documentation for the Python 2.5 standard library. - The API documentation for NLTK, the natural language toolkit. The most significant change since Epydoc 2.1 has to do with the way that epydoc extracts documentation information about python modules. In previous versions, epydoc extracted information about each module by importing it, and using introspection to examine its contents. The new version of epydoc still supports introspection, but is also capable of extracting information about python modules by parsing their source code. Furthermore, the new version of epydoc can combine these two sources of information (introspection & parsing). This is important because each source has its own advantages and disadvantages with respect to the other. For information about the new features in epydoc 3.0, see the "What's New" page: If you find any bugs, or have suggestions for improving epydoc, please report them on sourceforge: - Bugs: - Features: Or send email to . From mail at timgolden.me.uk Wed Feb 28 15:08:16 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 28 Feb 2007 20:08:16 +0000 Subject: Importing WMI in a child Thread throws an error In-Reply-To: <1172692796.192098.300590@h3g2000cwc.googlegroups.com> References: <1172602368.563302.160060@t69g2000cwt.googlegroups.com> <1172692796.192098.300590@h3g2000cwc.googlegroups.com> Message-ID: <45E5E130.3060103@timgolden.me.uk> kyosohma at gmail.com wrote: > On Feb 27, 3:32 pm, Tim Golden wrote: >> kyoso... at gmail.com wrote: >>> The problem I have is that since I import WMI, it takes a long time >>> and we have users complaining about it. So I stuck the import >>> statement into a separate thread and set it to a daemon so it could do >>> its thing in the background and the rest of the script would finish >>> and exit. >> Two things: >> >> 1) If you run WMI in a thread, you'll need to call >> pythoncom.CoInitialize first: >> >> >> import pythoncom >> import wmi >> >> pythoncom.CoInitialize () >> c = wmi.WMI () >> # >> # do things >> # >> pythoncom.CoUninitialize () >> >> >> 2) If you need a bit of speed running WMI, see the post >> I sent a few days ago to someone else: >> >> http://mail.python.org/pipermail/python-win32/2007-February/005550.html >> >> TJG > > Thanks! This works for my problem. It appears to cut the real time > required for my script to run by 30-50%. I tried to figure out how to > apply your answer to the other fellow, but I am actually querying WMI > for the amount of RAM and the CPU type and I just don't see how to use > your example in these cases. I am new to the WMI paradigm. If you want to post some specific code examples, I'm happy to talk you through possible optimisations. TJG From DustanGroups at gmail.com Sun Feb 11 10:51:51 2007 From: DustanGroups at gmail.com (Dustan) Date: 11 Feb 2007 07:51:51 -0800 Subject: Problem with reimporting modules In-Reply-To: References: Message-ID: <1171209111.551190.146590@a34g2000cwb.googlegroups.com> On Feb 11, 5:53 am, Christoph Zwerschke wrote: > I'm currently investigating a problem that can hit you in TurboGears > when Kid template modules are reloaded in the background, because in > certain situations, global variables suddenly are set to None values. > > I tracked it down to the following behavior of Python. Assume you have a > module hello.py like that: > > ---- hello. py ---- > greeting = 'Hello!' > def print_hello(): > print greeting > ------------------- > > Now run the following code: > > from hello import print_hello > print_hello() > import sys > del sys.modules['hello'] # delete module > import hello # recreate module > print_hello() > > The second print_hello() prints "None" instead of "Hello!". Why is that? > I had expected that it either prints an error or print "Hello!" as well. > > Is this intended behavior of Python? > > -- Christoph You're most likely looking for reload: http://docs.python.org/lib/built-in-funcs.html#l2h-61 The documentation does imply that deleting a module from sys.modules may not be what you want: http://docs.python.org/lib/module-sys.html#l2h-5147 >>> import sys >>> import warnings as previous_warnings # for example >>> # testing whether reload returns the same module object: ... reload(previous_warnings) is previous_warnings True >>> # the following result is rather intuitive, but for ... # the sake of demonstration, I'll do it anyway. ... del sys.modules['warnings'] >>> import warnings as after_warnings >>> after_warnings is previous_warnings False From gandalf at designaproduct.biz Wed Feb 21 10:41:12 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 21 Feb 2007 16:41:12 +0100 Subject: metaclasses (beginner question) In-Reply-To: References: Message-ID: <45DC6818.7090806@designaproduct.biz> > Without looking into the details -- the (subclass of) type is meant to be > the class of the class, or the other way round, your normal classes are > instances of (a subclass of) type. You determine the factory Python uses to > make a class by adding > > __metaclass__ = factory > > to the class body, so you'll probably end with something like > > class ProducerHandlerType(type): > # your code > > class A: > __metaclass__ = ProducerHandlerType > > The subclasses of A will now invoke your customised metaclass machinery. > Thanks, I missed that. I added the __metaclass__ line and it worked like a charm. Laszlo From __peter__ at web.de Tue Feb 27 06:37:14 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Feb 2007 12:37:14 +0100 Subject: what the heck is going on here? References: <1172530959.750822.207140@v33g2000cwv.googlegroups.com> Message-ID: markscala at gmail.com wrote: > I found the following ways to generate permutations on the ASPN: > Python Cookbook page. > > SLOW (two defs): > > def xcombinations(items,n): > if n == 0: yield[] > else: > for i in xrange(len(items)): > for cc in xcombinations(items[:i]+items[i+1:],n-1): > yield [items[i]]+cc > > def xpermutations(items): > return xcombinations(items,len(items)) > > FAST: > > def permutations(L): > if len(L) <= 1: > yield L > else: > a = [L.pop(0)] > for p in permutations(L): > for i in range(len(p)+1): > yield p[:i] + a + p[i:] > > The author of the FAST claimed his method was faster, which I wanted > to test. I ran the test as follows: > > import time > name = list('python') > > faster = time.clock() > for x in range(10000): > map(''.join,list(permutations(name))) > total1 = time.clock() - faster > print "Total time for faster: ", total1 > > xperm_start = time.clock() > for x in range(10000): > map(''.join,list(xpermutations(name))) > total2 = time.clock() - xperm_start > print "Total time for xperm: ", total2 > > If you run these tests in the order above, FAST takes about a .1 > seconds and slow takes about .17 seconds. BUT if you reverse the > order of the test, SLOW takes almost 10 seconds and FAST is about the > same! What's more, if you take map, join and list out of the tests > (there's no reason for them to be there anyway) the order doesn't > matter any more. Without map/join/list, SLOW and FAST are almost > indistinguishable at 10K loops. What's going on? ( This was done > in Python2.4 ) permutations() modifies its argument. Try items = ["a", "b", "c"] for p in permutations(items): pass print items to see why all measurements after the first pass of permutations() are bogus. Then modify your code to have permutations() operate on copies of the 'name' list. Peter From usable.thought at gmail.com Fri Feb 16 06:52:20 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 03:52:20 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! Message-ID: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> My last version of Python was 2.4, running smoothly on XP with path c: \Python24 - no need even to include this path in PATH; everything worked as it's supposed to at the command line. Just installed Python 2.5, after uninstalling 2.4 (and also 2.3 which had lingered). Now if I open a shell in Windows Python is not available! Here are the symptoms: - If I open a shell using "Command line here" with XP Powertools, then enter "python" at the prompt, nothing happens. I don't get a message that the command is not recognized, but neither do I get the Python prompt. Instead the Windows prompt comes back. No messages, no Python, no nothing. - If I go so far as to specify the full path to the Python executable, I do get the Python prompt and Python appears to work properly - except that I can't exit with CTRL-Z. - If I open a shell from the Start menu, e.g. Start > run "command", then try entering "python", the shell simply blows up. What is going on here? I have uninstalled and reinstalled Python 2.5, to no avail. I have gone so far as to specify c:\Python25 (the install path) in my PATH variable, but this makes no difference. Right now Python is unusable to me from the command prompt, meaning all of my automation scripts that I run at the command line are gone too. From http Fri Feb 2 17:16:30 2007 From: http (Paul Rubin) Date: 02 Feb 2007 14:16:30 -0800 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> Message-ID: <7xirek9pdt.fsf@ruckus.brouhaha.com> "George Sakkis" writes: > > What does "batteries included" mean to you? To me, it means you don't > > have to install add-ons. > > So let's make a 500MB executable and add Numpy, Zope, Django, PIL, > pretty much everything actually. Even better, make CheeseShop just a > frontend to a build system that adds and updates automatically > submitted packages to the core. Problem solved ! . Numpy should certainly be included and I think there are efforts in that direction. There is also a movement to choose a web framework to include and Django might be a good choice. I think the Zope maintainers want to keep Zope separate and I think PIL has an incompatible license. I'm not sure what you mean about making CheeseShop a front end to a build system, but I certainly don't think random user contributions should get added to the core automatically. Including a module in the core should carry with it the understanding that the module has undergone some reasonable evaluation by the core maintainers and is maintained. I do think the core should have more stuff than it does, so that its functionality can be on a par with competing language distros like J2SE and PHP. Both of those distros include database connectvity modules and web frameworks. It could be that those other packages can include more stuff because they have more active developer communities and can therefore expend more resources maintaining their libraries. But if that's the case, since the Java and PHP languages themselves suck compared with Python, we have to ask ourselves why Python has not been able to attract similar levels of effort and what it could be doing differently. From jon at ffconsultancy.com Mon Feb 19 14:27:40 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 19 Feb 2007 19:27:40 +0000 Subject: ocaml to python References: Message-ID: <45d9fbae$0$8752$ed2619ec@ptn-nntp-reader02.plus.net> Gigs_ wrote: > Is there any way to convert ocaml code to python? but not manually Translating between dissimilar high-level languages is very difficult, so difficult that it is hard to do such a task justice by hand, let alone automating the procedure. If you must do it then write a compiler that converts OCaml's intermediate representation into Python (after pattern match compilation), or write an OCaml bytecode interpreter in Python. For example, the following simple OCaml code is difficult to write in Python: let rec ( +: ) f g = match f, g with | `Q n, `Q m -> `Q (n +/ m) | `Q (Int 0), e | e, `Q (Int 0) -> e | f, `Add(g, h) -> f +: g +: h | f, g -> `Add(f, g) let rec ( *: ) f g = match f, g with | `Q n, `Q m -> `Q (n */ m) | `Q (Int 0), e | e, `Q (Int 0) -> `Q (Int 0) | `Q (Int 1), e | e, `Q (Int 1) -> e | f, `Mul(g, h) -> f *: g *: h | f, g -> `Mul(f, g) let rec simplify = function | `Q _ | `Var _ as e -> e | `Add(f, g) -> simplify f +: simplify g | `Mul(f, g) -> simplify f *: simplify g;; OCaml compiles the pattern matches first, which gives an intermediate representation much closer to something Python/Lisp can handle: (seq (letrec (+:/71 (function f/72 g/73 (catch (catch (if (isint f/72) (exit 3) (if (!= (field 0 f/72) 81) (exit 3) (let (n/74 (field 1 f/72)) (catch (if (isint g/73) (exit 4) (if (!= (field 0 g/73) 81) (exit 4) (makeblock 0 81 (apply (field 0 (global Num!)) n/74 (field 1 g/73))))) with (4) (switch n/74 case tag 0: (if (!= (field 0 n/74) 0) (exit 3) g/73) default: (exit 3)))))) with (3) (if (isint g/73) (exit 2) (let (variant/113 (field 0 g/73)) (if (!= variant/113 81) (if (!= variant/113 3254785) (exit 2) (let (match/112 (field 1 g/73)) (apply +:/71 (apply +:/71 f/72 (field 0 match/112)) (field 1 match/112)))) (let (match/110 (field 1 g/73)) (switch match/110 case tag 0: (if (!= (field 0 match/110) 0) (exit 2) f/72) default: (exit 2))))))) with (2) (makeblock 0 3254785 (makeblock 0 f/72 g/73))))) (apply (field 1 (global Toploop!)) "+:" +:/71)) (letrec (*:/83 (function f/84 g/85 (catch (catch (catch (catch (catch (if (isint f/84) (exit 10) (if (!= (field 0 f/84) 81) (exit 10) (let (n/86 (field 1 f/84)) (catch (if (isint g/85) (exit 11) (if (!= (field 0 g/85) 81) (exit 11) (makeblock 0 81 (apply (field 5 (global Num!)) n/86 (field 1 g/85))))) with (11) (switch n/86 case tag 0: (if (!= (field 0 n/86) 0) (exit 10) (exit 5)) default: (exit 10)))))) with (10) (if (isint g/85) (exit 9) (if (!= (field 0 g/85) 81) (exit 9) (let (match/121 (field 1 g/85)) (switch match/121 case tag 0: (if (!= (field 0 match/121) 0) (exit 9) (exit 5)) default: (exit 9)))))) with (9) (if (isint f/84) (exit 8) (if (!= (field 0 f/84) 81) (exit 8) (let (match/124 (field 1 f/84)) (switch match/124 case tag 0: (if (!= (field 0 match/124) 1) (exit 8) g/85) default: (exit 8)))))) with (8) (if (isint g/85) (exit 7) (let (variant/130 (field 0 g/85)) (if (!= variant/130 81) (if (!= variant/130 3855332) (exit 7) (let (match/129 (field 1 g/85)) (apply *:/83 (apply *:/83 f/84 (field 0 match/129)) (field 1 match/129)))) (let (match/127 (field 1 g/85)) (switch match/127 case tag 0: (if (!= (field 0 match/127) 1) (exit 7) f/84) default: (exit 7))))))) with (7) (makeblock 0 3855332 (makeblock 0 f/84 g/85))) with (5) [0: 81 [0: 0]]))) (apply (field 1 (global Toploop!)) "*:" *:/83)) (let (*:/83 (apply (field 0 (global Toploop!)) "*:") +:/71 (apply (field 0 (global Toploop!)) "+:")) (letrec (simplify/97 (function e/98 (let (variant/135 (field 0 e/98)) (if (!= variant/135 3254785) (if (!= variant/135 3855332) e/98 (let (match/132 (field 1 e/98)) (apply *:/83 (apply simplify/97 (field 0 match/132)) (apply simplify/97 (field 1 match/132))))) (let (match/131 (field 1 e/98)) (apply +:/71 (apply simplify/97 (field 0 match/131)) (apply simplify/97 (field 1 match/131)))))))) (apply (field 1 (global Toploop!)) "simplify" simplify/97)))) I suspect your best bet is to write an interface between the two (e.g. XMLRPC) and keep the OCaml as OCaml. -- Dr Jon D Harrop, Flying Frog Consultancy OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet From gagsl-py at yahoo.com.ar Sun Feb 11 15:40:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 17:40:36 -0300 Subject: help please!! References: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 16:40:45 -0300, darren112 escribi?: > The program should support brute-forcing of the authentication process > for a Telnet server via a dictionary attack. You should first read the Python Tutorial. After you get proficient with the basic programming structures, reading and writing files, networking, then use the telnetlib module (included with the standard Python library) to write your program. Depending on your previous experience and daily time, that might take from a couple days to one or two months. -- Gabriel Genellina From robert.kern at gmail.com Fri Feb 9 16:22:05 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 09 Feb 2007 13:22:05 -0800 Subject: Django, one more newbie question In-Reply-To: References: Message-ID: Boris Ozegovic wrote: > Umm, can somebody tell me which language is this one: > > {% if latest_poll_list %} >
    > {% for poll in latest_poll_list %} >
  • {{ poll.question }}
  • > {% endfor %} >
> {% else %} >

No polls are available.

> {% endif %} > > Whole tutorial is on this page: > http://www.djangoproject.com/documentation/tutorial3/ > > endfor, endif, {{? :) It's the Django templating language: http://www.djangoproject.com/documentation/templates/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bruno.desthuilliers at gmail.com Fri Feb 9 07:52:26 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 9 Feb 2007 04:52:26 -0800 Subject: Newbie Question In-Reply-To: <1170976573.303441.27460@k78g2000cwa.googlegroups.com> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> Message-ID: <1171025546.002411.213190@q2g2000cwa.googlegroups.com> On 9 f?v, 00:16, Eric.Gabriel... at gmail.com wrote: > On Feb 8, 2:17 pm, Grant Edwards wrote: > > > > > On 2007-02-08, Reid wrote: > > > > I am just starting to play with programing again as a hobby. I have heard > > > good things about python. I have not really looked into the language much. > > > My question is, will python make programs with a gui under windows xp. > > > Yes. > > > There are a number of GUI toolkits for python that will work > > with Windows. Some of the more common ones are listed athttp://www.python.org/about/apps/underthe "Desktop GUIs" > > section. > > > -- > > Grant Edwards grante Yow! Someone is DROOLING > > at on my collar!! > > visi.com > > yes as the guy above stated it does but another fairly easy language > that supports windows gui is pascal inspecific borland delphi which > uses the pascal language I learned some of it and gui development and > coding in it was fun also i found free video tutorials which helped > alot,http://www.3dbuzz.com you can click on delphi classroom, they > will explain the rest Delphi is a (dying) proprietary, MS-Windows-only[1] software relying on a low-level language. [1] Please don't argue about Kylix - it's not dying, it's long dead and buried... From robert.kern at gmail.com Mon Feb 5 01:10:27 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 05 Feb 2007 00:10:27 -0600 Subject: problems loading modules In-Reply-To: <1170654370.545302.277060@k78g2000cwa.googlegroups.com> References: <1170654370.545302.277060@k78g2000cwa.googlegroups.com> Message-ID: Frank wrote: > Hi, > > I have the following weird behavior when I load modules: > > >>>> import random >>>> print random.randrange(10) > 8 > > Everything is fine. > >>>> import random >>>> from numpy import * >>>> >>>> print random.randrange(10) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'randrange' > > Here it does not work. numpy has a subpackage called random. You imported it when you did "from numpy import *". -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jstroud at mbi.ucla.edu Fri Feb 2 15:50:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 02 Feb 2007 12:50:52 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: ardief wrote: > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] > > I have the feeling it's trivial, and I've scoured the group archives - > sets might be a possibility, but I'm not sure how to operate on a list > of lists with sets. > > This function also gives me what I want, more or less, but I don't > know how to make it run until it's covered all the possibilities, if > that makes sense... > > def sigh(list): > for a in list: > i = list.index(a) > if a != list[-1]: ##if a is not the last one, i.e. there is a > next one > n = alist[i+1] > if a[0] == n[0]: > a.append(n[1:]) > del alist[i+1] > > Sorry about the lengthy message and thanks for your suggestions - I'm > trying to learn... > Did someone suggest this? I couldn't find it and it seems simplest to me (no imports, etc.): keys = sorted(set(i[0] for i in alist)) d = [(k,[i[1] for i in alist if i[0]==k]) for k in keys] E.g.: py> alist = [['a', '13'], ... ['a', '3'], ... ['b', '6'], ... ['c', '12'], ... ['c', '15'], ... ['c', '4'], ... ['d', '2'], ... ['e', '11'], ... ['e', '5'], ... ['e', '16'], ... ['e', '7']] py> keys = sorted(set(i[0] for i in alist)) py> d = [(k,[i[1] for i in alist if i[0]==k]) for k in keys] py> d [('a', ['13', '3']), ('b', ['6']), ('c', ['12', '15', '4']), ('d', ['2']), ('e', ['11', '5', '16', '7'])] James From bearophileHUGS at lycos.com Sat Feb 3 13:01:23 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Feb 2007 10:01:23 -0800 Subject: Jython In-Reply-To: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> References: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> Message-ID: <1170525683.045502.225130@h3g2000cwc.googlegroups.com> gregt... at mindspring.com: > Files aren't lists and thus don't have the functions for iteration. > Try: > def go(): > for line in open("bobo.txt", "r").readlines(): > print line > go() CPython 2.1 has xreadlines, maybe Jython has it too. Bye, bearophile From aisaac at american.edu Tue Feb 27 15:56:14 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 27 Feb 2007 20:56:14 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> <1172561344.290126.191530@h3g2000cwc.googlegroups.com> Message-ID: "Arnaud Delobelle" wrote in message news:1172561344.290126.191530 at h3g2000cwc.googlegroups.com... > def __setattr__(self, attr, val): > if hasattr(self, attr): > self.__dict__[attr] = val > else: > # Tell the user off But then you cannot even set attributes during initialization, right? I want that restriction only after an object is initialized. (I realize that I could condition on an attribute set during initialization, but I am asking for the most elegant way to achieve this.) Alan From joshbloom at gmail.com Mon Feb 5 20:49:52 2007 From: joshbloom at gmail.com (joshbloom at gmail.com) Date: 5 Feb 2007 17:49:52 -0800 Subject: Python design project In-Reply-To: <1170673772.977486.172770@a75g2000cwd.googlegroups.com> References: <1170337417.236975.44070@l53g2000cwa.googlegroups.com> <45c313d5$0$8726$ed2619ec@ptn-nntp-reader02.plus.net> <1170673772.977486.172770@a75g2000cwd.googlegroups.com> Message-ID: <1170726592.725078.29030@a34g2000cwb.googlegroups.com> On Feb 5, 4:09 am, solric... at hotmail.com wrote: > I think I need to explain the things better I think, so I do; > > First answering the questions above; I think i have to explain the > project more. > > With type I mean; typography/fonts/characters.. For my final exam I > created the idea to treath fonts as a living organisms. > There for I want to create with the help of somebody, a little program > were i can import vector based fonts, and when they are imported they > "turn alive" > By turn alive I mean; they move random over the work area, opacity > changing, changing of size/color, merge together ans some more things, > little fonts changing. > > Because my python skills are zero, I'm looking for a partner which can > help me. I'm working On mac, but windows is not a problem. Hi Solrick, This sounds like some interesting stuff. I'd love to discuss it some more with you and maybe work with you on it. Some things to think about: 1. Rules for Font interactions. What happens when fonts 'hit' each other, or 'live' long enough to reproduce andmutate maybe? 2. What parts of the fonts can change. height, width, scale, kerning, serifs, color, transparency, etc 3. Python may not be the best environment for this application. Flash might be alot faster to get something going in as its designed for animating vectors and has a solid programming language behind it to write in your rules logic. Best, Josh From bignose+hates-spam at benfinney.id.au Thu Feb 1 01:16:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 17:16:47 +1100 Subject: Can I import a file without file extension .py? References: <1170305999.001998.251390@m58g2000cwm.googlegroups.com> Message-ID: <87r6tatnao.fsf@benfinney.id.au> "Jia Lu" writes: > I wonder if I can import a file with other file extensions ? I use this function in most of my test infrastructures, to import programs as modules for unit testing. def make_module_from_file(module_name, file_name): """ Make a new module object from the code in specified file """ from types import ModuleType module = ModuleType(module_name) module_file = open(file_name, 'r') exec module_file in module.__dict__ return module -- \ "Men never do evil so completely and cheerfully as when they do | `\ it from religious conviction." -- Blaise Pascal (1623-1662), | _o__) Pense'es, #894. | Ben Finney From alain.walter at thalesgroup.com Tue Feb 27 04:56:33 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 27 Feb 2007 01:56:33 -0800 Subject: gtk.mainquit is deprecated Message-ID: <1172570193.721466.286700@8g2000cwh.googlegroups.com> Hello, (environment : python 2.4.2, pyGTK, GTK+ 2.6.9 under HPUX 11.11: unix) On the instruction self.window.destroy(), I get the following message : lookup.py:121: GtkDeprecationWarning: gtk.mainquit is deprecated, use gtk.main_quit instead self.window.destroy() But I don't want to quit the application, I need only to close the window. My application includes others places where "self.window.destroy()" instruction is used and the execution is done without warning. Very strange. Thank you for your help From rajarshi.guha at gmail.com Sun Feb 11 13:15:21 2007 From: rajarshi.guha at gmail.com (Rajarshi) Date: 11 Feb 2007 10:15:21 -0800 Subject: Adding an XML fragment as a child node in a pre-existing Element tree Message-ID: <1171217718.232391.291850@v45g2000cwv.googlegroups.com> Hi, I'm using ElementTree for some RSS processing. The point where I face a problem is that within an I need to add another child node (in addition to etc) which is a well-formed XML document (Chemical Markup Language to be precise). So my code looks like: import cElementTree as ET c = open('x.cml').readlines() c = string.join(c) cml = ET.XML(c) Now I also have the following code: def addItem(self, title, link, description, cml = None): RSSitem = ET.SubElement ( self.RSSchannel, 'item' ) ET.SubElement( RSSitem, 'title' ).text = title ET.SubElement( RSSitem, 'description' ).text = description What I'm confused is how I can add the cml Element object that I generated, to the RSSitem as a child node. Do I need to manually traverse the tree of the CML document and add it one by one to the RSSitem as a child node? Or is there a smarter way to do this? Any pointers would be greatly appreciated Thanks, Rajarshi From gnewsg at gmail.com Sat Feb 3 14:58:23 2007 From: gnewsg at gmail.com (billie) Date: 3 Feb 2007 11:58:23 -0800 Subject: asyncore DoS vulnerability In-Reply-To: References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> <1170422700.309941.203320@a34g2000cwb.googlegroups.com> <1170430334.170669.215150@q2g2000cwa.googlegroups.com> Message-ID: <1170532703.151158.64940@a34g2000cwb.googlegroups.com> On 2 Feb, 17:09, "Chris Mellon" wrote: > Thats like asking why you should have to move your fingers to type or > why you should have to eat food in order to not starve. Windows is > placing a limit of 512 descriptors per process. Call Microsoft if you > want to go over that. ? That's not a select() problem: that's an asyncore problem. I'm just saying that asyncore should handle this event in some other way than raising a not well defined "ValueError". I've discovered this problem accidentally by writing a small test script but personally I've never seen a paper describing it. Not handling such a problem just means that an asyncore based server is vulnerable to DoS attacks and I believe that a lot of servers out there didn't used a try/except statement around "asyncore.loop()". imho, such a problem should merit some attention. Don't you agree? From steve at holdenweb.com Thu Feb 15 08:27:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 13:27:51 +0000 Subject: AUX File Writing Error In-Reply-To: References: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> <1171521299.082449.67940@s48g2000cws.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Thu, 15 Feb 2007 03:34:59 -0300, John Machin > escribi?: > >> On Feb 15, 4:03 pm, thewritersc... at gmail.com wrote: >>> Is there any way I can create an "AUX.csv" file without the error? >> Probably not. AUX, CON, NUL, PRN, LPT, COM1, COM2 etc (with or without >> an extension) are reserved in Windows for specific devices for >> compatibility with MS-DOS 1.00 programs, which did that for >> compatibility with CP/M. > > (This is OT now) Do you know why "AUX.csv" is invalid too? I can accept > that AUX (without extension) is an invalid filename, but it is quite > different from "AUX.csv" > Because Windows is brain-dead? There really is no sense in looking for rationality where none exists. This is the way it is, and there's nothing you can do about it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From http Mon Feb 19 19:52:44 2007 From: http (Paul Rubin) Date: 19 Feb 2007 16:52:44 -0800 Subject: Newbie help looping/reducing code References: Message-ID: <7x1wkl8xb7.fsf@ruckus.brouhaha.com> Lance Hoffmeyer writes: > def even_odd_round(num): > if(round(num,2) + .5 == int(round(num,2)) + 1): > if num > .5: > if(int(num) % 2): > num = round(num,2) + .1 #an odd number > else: > num = round(num,2) - .1 #an even number > else: > num = 1 > rounded_num = int(round(num,0)) > return rounded_num I would also rewrite this function. It's quite hard to figure out what it's intended to do. At minimum it should be carefully documented. I have the impression it's supposed to be something like the IEEE rounding mode, that rounds floating point numbers to the nearest integer, rounding to the even neighbor if the fractional part (sometimes called the mantissa) is close to 0.5. > if(round(num,2) + .5 == int(round(num,2)) + 1): The above is true if the mantissa is >= 0.495. So you're going to round 3.495 up to 4, even though it's actually closer to 3. Is that really what you want? You're rounding based on a printed representation rather than on the actual number. > if num > .5: It looks like for display purposes you're trying to avoid displaying positive numbers as zero if they're slightly below 0.5. However, that doesn't prevent the round-to-even behavior if the number is slightly above 0.5. So you get the anomaly that even_odd_round(0.499) = 1, but even_odd_round(0.501) = 0. My guess is that's not what you wanted and that it's a bug. > if(int(num) % 2): > num = round(num,2) + .1 #an odd number > else: > num = round(num,2) - .1 #an even number If the integer part is odd, round upward, else round downward, ok. So basically you're going to round to the even neighbor if the mantissa is close to 0.5, otherwise round to the nearest integer. I notice also that when num is negative, your function rounds to the odd neighbor (at least sometimes), differing from IEEE rounding. I think it's clearer to just separate out the integer and fractional parts and branch on the fractional part directly. I'll ignore the issue with negative inputs since I'm guessing you only care about positive ones: def even_odd_round(num): assert num >= 0 # separate the number's integer and fractional parts intpart, fracpart = int(num), num % 1.0 # decide what to do based on the fractional part if fracpart < 0.495: return intpart # round downward elif fracpart > 0.505 or intpart==0: return intpart+1 # round upward else: return intpart + intpart % 2 # round to even From rshepard at nospam.appl-ecosys.com Sun Feb 25 13:05:28 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 25 Feb 2007 18:05:28 GMT Subject: Referencing Items in a List of Tuples References: Message-ID: On 2007-02-25, Dennis Lee Bieber wrote: > Item is ALREADY the "current" tuple... > > for tpl in mainlist: > if tpl[0] == "eco" and tpl[1] == "con": > ec.Append(tpl[2:]) #presuming ec is NOT a list, as Append() > #is not a list method (append() is) Of course! As a morning person I don't do as well at night. That's such a silly error I'm embarrassed by having to have the obvious pointed out to me. My apologies to all. And, the .Append comes from list widgets in wxPython. Thank you all for forcing my head straight again. Rich From ms at cerenity.org Fri Feb 2 19:43:40 2007 From: ms at cerenity.org (Michael) Date: Sat, 03 Feb 2007 00:43:40 +0000 Subject: Where Does One Begin? References: Message-ID: <45c3da27$0$8717$ed2619ec@ptn-nntp-reader02.plus.net> Mister Newbie wrote: > I have no programming experience. I want to learn Python so I can make > simple, 2D games. Where should I start? Can you recommend a good book? If that's your goal, there's a perfect book for you - it's called "Python for the Absolute Beginner". It focusses on people with no programming experience, and aims to teach you how to make simple 2D games. Sounds like a perfect match. Even it's first example program is oriented around this and it's a simple program that displays a well worn 2 word phrase known to many a programmer and games player: ---- #!/usr/bin/python print "GAME OVER!" ---- It's relatively gentle, but builds up towards writing simple games in pygame. Michael. From karoly.kiripolszky at gmail.com Mon Feb 5 07:43:14 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 5 Feb 2007 04:43:14 -0800 Subject: C parsing fun Message-ID: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> Helo ppl! At the job I was given the task to make a script to analyze C++ code based on concepts my boss had. To do this I needed to represent C++ code structure in Python somehow. I read the docs for Yapps, pyparsing and other stuff like those, then I came up with a very simple idea. I realized that bracketed code is almost like a Python list, except I have to replace curly brackets with squared ones and surround the remaining stuff with quotes. This process invokes no recursion or node objects, only pure string manipulations so I believe it's really fast. Finally I can get the resulting list by calling eval() with the string. For example when I need to parse a class definition, I only need to look for a list item containing the pattern "*class*", and the next item will be the contents of the class as another list. You can grab the code at: http://kiri.csing.hu/stack/python/bloppy-0.1.zip (test script [test.py] included) From george.sakkis at gmail.com Fri Feb 2 15:12:19 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 2 Feb 2007 12:12:19 -0800 Subject: Fixed length lists from .split()? In-Reply-To: <2007020112400475249-bob@passcalnmtedu> References: <2007012611072716807-bob@passcalnmtedu> <2007012611264650073-bob@passcalnmtedu> <9CCuh.19350$X72.434@newsread3.news.pas.earthlink.net> <2007020112400475249-bob@passcalnmtedu> Message-ID: <1170447139.146710.233920@h3g2000cwc.googlegroups.com> On Feb 1, 2:40 pm, Bob Greschke wrote: > This idiom is what I ended up using (a lot it turns out!): > > Parts = Line.split(";") > Parts += (x-len(Parts))*[""] > > where x knows how long the line should be. If the line already has > more parts than x (i.e. [""] gets multiplied by a negative number) > nothing seems to happen which is just fine in this program's case. > > Bob Here's a more generic padding one liner: from itertools import chain,repeat def ipad(seq, minlen, fill=None): return chain(seq, repeat(fill, minlen-len(seq))) >>> list(ipad('one;two;three;four'.split(";"), 7, '')) ['one', 'two', 'three', 'four', '', '', ''] >>> tuple(ipad(xrange(1,5), 7)) (1, 2, 3, 4, None, None, None) George From bj_666 at gmx.net Mon Feb 5 08:34:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 05 Feb 2007 14:34:57 +0100 Subject: C parsing fun References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> Message-ID: In <1170679559.272656.145660 at v33g2000cwv.googlegroups.com>, karoly.kiripolszky wrote: > and the great thing is that the algorithm can be used with any > language that structures the code with brackets, like PHP and many > others. But it fails if brackets appear in comments or literal strings. Ciao, Marc 'BlackJack' Rintsch From tleeuwenburg at gmail.com Tue Feb 6 21:36:42 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 6 Feb 2007 18:36:42 -0800 Subject: Threading in Python In-Reply-To: References: Message-ID: <1170815802.600716.295960@l53g2000cwa.googlegroups.com> On Feb 7, 11:14 am, "S.Mohideen" wrote: > Python is praised about - me too. But at one instance it fails. It fails to > behave as a true multi-threaded application. That means utilizing all the > CPUs parallely in the SMP efficiently stays as a dream for a Python > Programmer. > > Discussion threads say its due to GIL - global interpreter lock. But nobody > has mentioned any alternative to that apart from suggestions like "Code it > in C" and POSH (http://poshmodule.sf.net). Is there any other way we can > make Python programs really multithreaded in real sense. > > Moin There are two ways. You can use processes, or you can use IronPython. Cheers, -T From boris.smirnov at gmail.com Tue Feb 27 06:00:41 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 27 Feb 2007 03:00:41 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <54ih3nF2143jeU2@mid.uni-berlin.de> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> <1172573562.215310.76760@8g2000cwh.googlegroups.com> <54ih3nF2143jeU2@mid.uni-berlin.de> Message-ID: <1172574041.569357.127440@q2g2000cwa.googlegroups.com> On Feb 27, 11:56 am, "Diez B. Roggisch" wrote: > > Yes that I can deduce, but why I'm asking is why it's different on > > Windows and Linux. Should it not be platform independent? > > It should be. I've got no idea why it seems to work on windows but I can say > one thing for sure: that would be an artifact that you shouldn't rely on. > In Qt, you _always_ need a QApplication for anything. So just do as it > requires you to do: first, construct a QApplication. Then things will work. > > Diez Hmm, as I see the code, I do construct QApplication as first if __name__ == '__main__': a = QApplication (sys.argv) mywidget = Optimizer() a.setMainWidget (mywidget) mywidget.show() Update_StatusLine(mywidget) mywidget.setStartconfig() a.exec_loop () From karajutsu at yahoo.com Mon Feb 19 07:33:12 2007 From: karajutsu at yahoo.com (sidoy) Date: 19 Feb 2007 04:33:12 -0800 Subject: World Funniest Video Message-ID: <1171888392.682796.59740@a75g2000cwd.googlegroups.com> you can find here the World Funniest Video at http://www.supperlaffn.blogspot.com From laurent.pointal at limsi.fr Mon Feb 5 11:07:15 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 05 Feb 2007 17:07:15 +0100 Subject: when will python 2.5 take in mainstream? In-Reply-To: References: Message-ID: Jean-Paul Calderone a ?crit : > On Mon, 05 Feb 2007 10:19:26 +0100, Laurent Pointal > wrote: >> tleeuwenburg at gmail.com a ?crit : >>> When they have to ... >>> >>> One of the big things about Python is that its penetration slows it >>> down. There's more legacy code and interdependant systems around now >>> that Python is more successful and more mature. >>> >>> Here's a thought -- perhaps it would be worth having some good ways to >>> interact with Python from Python. Suppose you have some 2.4 code >>> someplace, interacting with your mysqldb or whatever, and you don't >>> want to rewrite it. So long as you have some kind of object broker, >>> you could (plausibly) leave your 2.4 apps running with the old >>> interpreter, but wrap them for Python 2.5 and use that in your new >>> development. >> >> KISS please. >> > > Requiring change is simpler than not requiring change? > Okay, perhaps > you could make a case, but it's far from obvious this is always true. > IMHO trying to have a binary compatibility with older compiled modules by maintaining an ad-hoc layer to switch between 2.4/2.5 engines make Python code more complex. And more complex code have generally more bugs. This is the reason for my KISS hope about Python. Its simple to require changes, not so sure that doing these modifications keep things simple. Maybe an internal Python hacker can give us his advice on such a modification (ie. staying compatible with legacy modules compiled for previous versions). A+ Laurent. From gagsl-py at yahoo.com.ar Tue Feb 13 00:52:29 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 02:52:29 -0300 Subject: get pid of a nohup command in Python References: <1171342377.456635.203490@q2g2000cwa.googlegroups.com> Message-ID: En Tue, 13 Feb 2007 01:52:57 -0300, escribi?: > I'm new to Python and am evaluating moving a project from Tcl/Tk to > Python and am stuck on one issue. How can I nohup (or any detached > task for that matter) a process and get its PID in Python. The obvious > route of (with a trivial example) > > os.system("nohup ls > junk &") > > returns the status of the command execution (ie. 0). I wish to get the > PID output of the command (e.g. 16617). All the other commands spawn** > also seem to return the execution status not the PID. This is a > showstopper so any help appreciated. The spawn* family will return the pid if you use the P_NOWAIT flag. But the best way is to use the subprocess module; Popen objects have a pid attribute. http://docs.python.org/lib/module-subprocess.html -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Sat Feb 17 13:40:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 17 Feb 2007 19:40:33 +0100 Subject: why I don't like range/xrange In-Reply-To: References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <45d61e34$0$29759$426a74cc@news.free.fr> Message-ID: <45d744ad$0$30359$426a74cc@news.free.fr> Roel Schroeven a ?crit : > Bruno Desthuilliers schreef: > >> stdazi a ?crit : > > >>> for (i = 0 ; i < 10 ; i++) >>> i = 10; >> >> >> for i in range(10): >> i = 10 >> >> What's your point, exactly ? > > > In the first iteration, i is set equal to 10. Then, before starting the > second iteration, i is incremented to 11; then the loop condition is > checked and results in false. So the loop terminates after the first > iteration. oops - my bad. But why would one do so when a break would do the trick: for i in range(10): break > > So, the point is that in C you can influence the loop's behavior by > modifying the loop variable, while you cannot do that in Python (at > least not in a for-loop). A good thing IMHO. > In other words, the point is that you can't translate loops literally > from C to Python. Which is nothing new, and I fail to see how that is > supposed to be a disadvantage. > From cbc at unc.edu Tue Feb 27 15:55:09 2007 From: cbc at unc.edu (Chris Calloway) Date: Tue, 27 Feb 2007 15:55:09 -0500 Subject: Three days left for Zope3 boot camp registration Message-ID: <45E49AAD.1010101@unc.edu> Registration ends Friday: http://trizpug.org/boot-camp/camp5 -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From spedrosa at gmail.com Tue Feb 6 09:27:47 2007 From: spedrosa at gmail.com (Stephen Eilert) Date: 6 Feb 2007 06:27:47 -0800 Subject: Decimating Excel files In-Reply-To: <1170729742.709892.200270@q2g2000cwa.googlegroups.com> References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> <1170725241.634632.100830@v45g2000cwv.googlegroups.com> <1170727172.316685.49980@h3g2000cwc.googlegroups.com> <1170729742.709892.200270@q2g2000cwa.googlegroups.com> Message-ID: <1170772067.790908.272440@m58g2000cwm.googlegroups.com> On Feb 5, 11:42 pm, "John Machin" wrote: > On Feb 6, 1:19 pm, gonzlobo wrote: > > > I tried to open the file with Kate, trust me, it's an Excel file. > > Who or what is Kate? In what sense is trying to open it any evidence > that it's an Excel file? Did you *succeed* in opening the file "with > Kate"? In the sense that Kate is not a girl, but a text editor. I assume he opened the file and got only "gibberish", instead of text, CSV, or whatever. Stephen From kay.schluehr at gmx.net Mon Feb 19 04:22:59 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Feb 2007 01:22:59 -0800 Subject: ANN: java2python 0.2 In-Reply-To: References: Message-ID: <1171876979.192320.271500@q2g2000cwa.googlegroups.com> On 19 Feb., 15:38, Troy Melhase wrote: > java2python - Java to Python Source Code Translator > --------------------------------------------------- > java2python 0.2 Released 18 February 2007 > > What is java2python? > ------------------------------------------------------------------------------ > java2python is a simple but effective tool to translate Java source code into > Python source code. It's not perfect, and does not aspire to be. > > What's new in this release? > ------------------------------------------------------------------------------ > Small enhancement: added converstion of "public static void main" method into > module "if __name__ == '__main__' block. > > Better classmethod support: fixed class/instance member formatting strings to > account for classmethods. > > Slightly more pythonic: replace "x == None" expressions with "x is None" in > output code, also replace "x != None" with "x is not None". > > Bugfix: Fixed dotted type identifiers. > > Better exception translation: added support for mapping java exception types > to python exception types. > > Support for non-local base class members: added support for base class > members via config modules. > > Bugfix: changed single % characters to %% in expression format strings. > > Small enhancement: added support for 'methodPreambleSorter' configuration > item. With this value, config modules can specify how to sort method > preambles (typically decorators). > > Where can I get java2python? > ------------------------------------------------------------------------------ > java2python is available for download from Google code: > > http://code.google.com/p/java2python/downloads/list > > Project page: > > http://code.google.com/p/java2python/ > > How do I use java2python? > ------------------------------------------------------------------------------ > Like this: > > $ j2py -i input_file.java -o output_file.py > > The command has many options, and supports customization via multiple > configuration modules. > > What are the requirements? > ------------------------------------------------------------------------------ > java2python requires Python 2.5 or newer. Previous versions may or may not > work. java2python requires ANTLR and PyANTLR to translate code, but > translated code does not require ANTLR. > > What else? > ------------------------------------------------------------------------------ > java2python is installed with distutils. Refer to the Python distutils > documentation for more information. The digest version is: > > $ tar xzf java2python-0.2.tar.gz > $ cd java2python-0.2 > $ python setup.py install > > java2python is licensed under the GNU General Public License 2.0. No license > is assumed of (or applied to) translated source. > > I'm very interested in your experience with java2python. Please drop me an > note with any feedback you have. > > Troy Melhase > mailto:t... at gci.net > > application_pgp-signature_part > 1KHerunterladen Hi Troy. What is the rationale for your project? From jstroud at mbi.ucla.edu Sat Feb 3 02:59:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 03 Feb 2007 07:59:05 GMT Subject: How much introspection is implementation dependent? In-Reply-To: <1170465120.175164.103350@s48g2000cws.googlegroups.com> References: <1170465120.175164.103350@s48g2000cws.googlegroups.com> Message-ID: George Sakkis wrote: > On Feb 2, 6:56 pm, James Stroud wrote: > >> Hello, >> >> I wanted to automagically generate an instance of a class from a >> dictionary--which might be generated from yaml or json. I came up with this: >> >> (snip) >> >> == >> >> #! /usr/bin/env python >> >> # automagical constructor >> def construct(cls, adict): >> dflts = cls.__init__.im_func.func_defaults >> vnames = cls.__init__.im_func.func_code.co_varnames >> >> argnames = vnames[1:-len(dflts)] >> argvals = [adict.pop(n) for n in argnames] >> >> return cls(*argvals, **adict) >> >> def test(): >> >> class C(object): >> def __init__(self, arg1, arg2, kwa3=3): >> self.argsum = arg1 + arg2 >> self.kwsum = kwa3 >> def __str__(self): >> return "%s & %s" % (self.argsum, self.kwsum) >> >> # now a dict for autmagical generation >> adict = {'arg1':1, 'arg2':2, 'kwa3':42} >> >> print '======== test 1 ========' >> print adict >> print construct(C, adict) >> >> adict = {'arg1':1, 'arg2':2} >> print >> print '======== test 2 ========' >> print adict >> print construct(C, adict) >> >> if __name__ == "__main__": >> test() > > What's the point of this ? You can call C simply by C(**adict). Am I > missing something ? > > George > Maybe there is something wrong with my python. py> class C: ... def __init__(a, b, c=4): ... print a,b,c ... py> C(**{'a':10, 'b':5, 'c':4}) Traceback (most recent call last): File "", line 1, in TypeError: __init__() got multiple values for keyword argument 'a' James From hg at nospam.org Wed Feb 14 09:26:06 2007 From: hg at nospam.org (hg) Date: Wed, 14 Feb 2007 15:26:06 +0100 Subject: f---ing typechecking References: Message-ID: > Its ugly and boring. It's rude, unnecessary _and_ boring From hg at nospam.org Tue Feb 13 02:19:55 2007 From: hg at nospam.org (hg) Date: Tue, 13 Feb 2007 08:19:55 +0100 Subject: Mulig SPAM: float print formatting References: Message-ID: <4OjAh.22047$NI1.19760@newsfe14.lga> NOSPAM plz wrote: > hg skrev: >> Hi, >> >> Considering the float 0.0, I would like to print 00.00. >> >> I tried '%02.02f' % 0.0 ... but I get 0.00 >> >> Any clue ? >> >> Thanks, >> >> hg >> >> > Try this: > > a = 45.45 # the floating number > > print "some text", > print a, > print "some text again" > > or just this: > > print "some text", > print 45.45, > print "some text again" > > Hope it helped :D > > Andreas Sorry, must be very slow or not enough coffee yet ... my purpose is to display a justified report, so I format my floats into strings which I next draw in a bitmap. hg From silovana.vjeverica at com.gmail Tue Feb 6 12:29:59 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Tue, 6 Feb 2007 18:29:59 +0100 Subject: Module problem Message-ID: Hi I am writing some simple script, and when I start my script from command line (python Imenik.py), everything works perfectly. If I double clik the same script in my desktop I get the following error: "No module name import win32clipboard" -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" From nagle at animats.com Sat Feb 24 01:04:45 2007 From: nagle at animats.com (John Nagle) Date: Sat, 24 Feb 2007 06:04:45 GMT Subject: Parsing HTML In-Reply-To: <1172281524.771144.302360@8g2000cwh.googlegroups.com> References: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> <1170963788.882845.124810@k78g2000cwa.googlegroups.com> <1172281524.771144.302360@8g2000cwh.googlegroups.com> Message-ID: <1AQDh.477$m85.408@newssvr29.news.prodigy.net> BeautifulSoup does parse HTML well, but there are a few issues: 1. It's rather slow; it can take seconds of CPU time to parse some larger web pages. 2. There's no error reporting. It tries to do the right thing, but when it doesn't, you have no idea what went wrong. BeautifulSoup would be a good test case for the PyPy crowd to work on. It really needs the speedup. John Nagle sofeng wrote: > On Feb 8, 11:43 am, "metaperl" wrote: >>On Feb 8, 2:38 pm, "mtuller" wrote: >>>I am trying to parse a webpage and extract information. >>BeautifulSoup is a great Python module for this purpose: From steveo at syslang.net Thu Feb 1 16:06:20 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 1 Feb 2007 16:06:20 -0500 (EST) Subject: Question about a single underscore. In-Reply-To: <45c24a89$0$19929$426a74cc@news.free.fr> References: <45c24a89$0$19929$426a74cc@news.free.fr> Message-ID: On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers: =>Steven W. Orr a ?crit : =>> I saw this and tried to use it: =>> =>> ------------------><8------------------- const.py------------- =>> class _const: =>> class ConstError(TypeError): pass =>> def __setattr__(self,name,value): =>> if self.__dict__.has_key(name): =>> raise self.ConstError, "Can't rebind const(%s)"%name =>> self.__dict__[name]=value =>> =>> import sys =>> sys.modules[__name__]=_const() =>> ------------------><8------------------- const.py------------- =>> =>> Then when I go to try to use it I'm supposed to say: =>> =>> const.pi = 3.14159 =>> const.e = 2.7178 =>> =>> =>> Two questions: =>> =>> 1. Why do I not have to say =>> =>> _const.pi = 3.14159 =>> _const.e = 2.7178 => =>Because of the last two lines of module const. sys.modules is a dict of =>already imported modules (yes, Python's modules are objects too), which =>avoids modules being imported twice or more. __name__ is a magic =>variable that is set either to the name of the module - when it's =>imported - or to '__main__' - when it's being directly executed as the =>main program. Here, when you first do 'import const', the module's code =>itself sets sys.modules['const'] to an instance of _const, so what you =>import in your namespace as 'const' is not the const module instance but =>a _const instance. => =>> and is this in the tutorial? => =>Hmmm... Not sure. FWIW, it's mostly a hack !-) => =>> 2. Can I make this behave in such a way that I can create my constants =>> with a classname => =>s/classname/name/ => =>> that is different for different uses? e.g., =>> =>> irrational_const.pi = 3.14159 =>> irrational_const.e = 2.7178 =>> =>> even_const.first = 2 =>> even_const.firstPlus = 4 => =>irrational_const = const.__class__() =>even_const = const.__class__() => =>Now while I find this hack interesting, it's also totally unpythonic =>IMHO. The usual convention is to use ALL_UPPER names for (pseudo) =>symbolic constants, and I don't see any reason to forcefit B&D languages =>concepts into Python. Ok. Now *maybe* we're getting to where I want to be. My const.py now looks like this: class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__[name]=value import sys sys.modules[__name__]=_const() and in a seperate module call key_func_consts I say: import const # Define constants for Key Function Field. KeyFuncConst = const.__class__() KeyFuncConst.NotDefined = 0x00 And in my main module I have #! /usr/bin/python import const import key_func_consts print KeyFuncConst.MSK but the last print fails with The goal is to be able to create classes of global constants. 561 > t_const.py Traceback (most recent call last): File "./t_const.py", line 6, in ? print KeyFuncConst.MSK NameError: name 'KeyFuncConst' is not defined Do I need to get the KeyFuncConst object into sys.modules somehow? I know I'm close. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From sjdevnull at yahoo.com Tue Feb 27 19:14:20 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 27 Feb 2007 16:14:20 -0800 Subject: Python Source Code Beautifier In-Reply-To: References: Message-ID: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> On Feb 27, 3:45 am, Franz Steinhaeusler wrote: > Hello, I did not find any reasonable pyhton source code beautifier > program (preferable gui). > > Some would ask why? Program it immediatly good. > > (BTW: Would be a nice project, if I would have more spare time). > > Ich have some foreign source, which are programed in a way > I don't like, so I would like to have a tool, which automatically > processes following options: > > Use Spaces, size: 4 reindent.py or your editor should handle this, or PythonTidy > convert structs like: if (a > b): to if a > b: If someone put the () around it, they probably have good reason (e.g. clarity or they anticipate it being a multiline condition in the near future) > fill in spaces, but not in functions between operators: > > a+=1 => a += 1 > p(t + 1) => p(t+1) PythonTidy > convert: > > self.scriptcount = self.scriptcount + 1 => self.scriptcount += 1 Those mean different things: >>> a=[1] >>> b=a >>> a += [2] >>> a [1, 2] >>> b [1, 2] >>> a=[1] >>> b=a >>> a = a + [2] >>> a [1, 2] >>> b [1] > from "is" to "==" and "is not" to "!=" (ok a find replace could do that > easily also), but in a program that would be more comfortable. >>> a="hello there" >>> b="hello there" >>> a==b True >>> a is b False > break long lines (in a reasonable way) Not sure how this would be done. > > make from: > if len(string) > 0: => if string: > and > if if len(string) < 1 orr if string == "" => if not string Impossible in a dynamically typed system, you could hack up something that works sometimes with type inference and/or type logging after running the program but it'd be unreliable and hardly seems worth the effort and danger. Especially since it might break other stringlike classes depending on their semantics. > detect mixed line ending > detect tabs mixed with space > trim trailing whitespaces. reindent.py handles those. > Running Pylint or Pycheck automatically afterwards > would be the coronation. :) I have vim automatically call PyFlakes every time I hit enter and highlight any errors (so stupidities like "if a=1:" are caught immediately as I'm editing) From jeff.templon at gmail.com Mon Feb 19 03:07:42 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 19 Feb 2007 00:07:42 -0800 Subject: How to test if one dict is subset of another? Message-ID: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> Hi, I have some code that does, essentially, the following: - gather information on tens of thousands of items (in this case, jobs running on a compute cluster) - store the information as a list (one per job) of Job items (essentially wrapped dictionaries mapping attribute names to values) and then does some computations on the data. One of the things the code needs to do, very often, is troll through the list and find jobs of a certain class: for j in jobs: if (j.get('user') == 'jeff' and j.get('state')=='running') : do_something() This operation is ultimately the limiting factor in the performance. What I would like to try, if it is possible, is instead do something like this: if j.subset_attr({'user' : 'jeff', 'state' : 'running'}) : do_something() where subset_attr would see if the dict passed in was a subset of the underlying attribute dict of j: j1's dict : { 'user' : 'jeff', 'start' : 43, 'queue' : 'qlong', 'state' : 'running' } j2's dict : { 'user' : 'jeff', 'start' : 57, 'queue' : 'qlong', 'state' : 'queued' } so in the second snippet, if j was j1 then subset_attr would return true, for j2 the answer would be false (because of the 'state' value not being the same). Any suggestions? Constraint : the answer has to work for both python 2.2 and 2.3 (and preferably all pythons after that). JT From steve at holdenweb.com Sun Feb 11 16:49:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 21:49:01 +0000 Subject: Regular Expressions In-Reply-To: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> Message-ID: deviantbunnylord at gmail.com wrote: >> That's a little harsh -- regexes have their place, together with pointer >> arithmetic, bit manipulations, reverse polish notation and goto. The >> problem is when people use them inappropriately e.g. using a regex when a >> simple string.find will do. >> >>> A quote attributed variously to >>> Tim Peters and Jamie Zawinski says "Some people, when confronted with a >>> problem, think 'I know, I'll use regular expressions.' Now they have two >>> problems." >> I believe that is correctly attributed to Jamie Zawinski. >> >> -- >> Steven > > So as a newbie, I have to ask. I've played with the re module now for > a while, I think regular expressions are super fun and useful. As far > as them being a problem I found they can be tricky and sometimes the > regex's I've devised do unexpected things...(which I can think of two > instances where that unexpected thing was something that I had hoped > to get into further down the line, yay for me!). So I guess I don't > really understand why they are a "bad idea" to use. I don't know of > any other way yet to parse specific data out of a text, html, or xml > file without resorting to regular expressions. > What other ways are there? > Re's aren't inherently bad. Just avoid using them as a hammer to the extent that all your problems look like nails. They wouldn't exist if there weren't problems it was appropriate to use them on. Just try to use simpler techniques first. For example, don't use re's to find out if a string starts with a specific substring when you could instead use the .startswith() string method. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From S.Mientki-nospam at mailbox.kun.nl Mon Feb 12 09:59:30 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 12 Feb 2007 15:59:30 +0100 Subject: Newbie Question In-Reply-To: <1171282541.900959.261020@a34g2000cwb.googlegroups.com> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> Message-ID: <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> bruno.desthuilliers at gmail.com wrote: > On 9 f?v, 14:06, Stef Mientki wrote: >>>> will explain the rest >>> Delphi is a (dying) proprietary, MS-Windows-only[1] software relying >>> on a low-level language. >> Well it may be dying, >> but for the moment it beats Python with a factor of 10, >> when it comes to user (the majority of PC users) friendly GUI ;-) > > Would you mind explaining yourself and backing your above assertion ? > Like, ie, on which points does Delphi "beats" Python wrt/ GUIs, what > special magic would make so that GUIs designed with Delphi would be > more "user-friendly", and where does this "factor 10" comes from ? > Maybe I should have written it in quotes "factor of 10" ;-) But here are a few points - in Delphi the GUI design itself is done in a graphical environment, making it much easier and faster - auto-scaling of components on a form is very easy (so if the user changes form size ..) - even making everything on a form movable by the end-user is just 1 mouse-click - using the designers style, or the user style is just 1 click - very good feedback, so creating interactive graphs is very easy, cross-hair, slopes, region of interest etc. - a very huge collection of controls is standard available - print / clipboard / export to almost any graphical file format, just 1 line of code but to be honest ... ... I never even tried to write a GUI in Python, ... ... just looked at others examples, ... and still not seen what I can perform in Delphi ;-) cheers, Stef Mientki > Good luck... > From sickcodemonkey at gmail.com Tue Feb 20 13:15:15 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 20 Feb 2007 13:15:15 -0500 Subject: Regd. converting seconds to hh:mm:ss format In-Reply-To: <200702201800.l1KI0j8h024251@nsa.veriwave.com> References: <7x3b50d8ri.fsf@ruckus.brouhaha.com> <200702201800.l1KI0j8h024251@nsa.veriwave.com> Message-ID: <2adc542f0702201015s78fc6995w5b63125d3d290c4c@mail.gmail.com> Do you mean epoch time? if so, the below example would work. >>> import time,datetime >>> t = datetime.datetime.now() >>> print t 2007-02-20 13:09:34.851000 >>> print "Epoch Seconds:", time.mktime(t.timetuple()) Epoch Seconds: 1171994974.0 # go the other way >>> epochtime = 1171994974 >>> now = datetime.datetime.fromtimestamp(epochtime) >>> print now 2007-02-20 13:09:34 On 2/20/07, Vishal Bhargava wrote: > > > Is there an inbuilt library in Python which you can use to convert time in > seconds to hh:mm:ss format? > Thanks, > Vishal > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lbates at websafe.com Wed Feb 21 19:15:38 2007 From: lbates at websafe.com (Larry Bates) Date: Wed, 21 Feb 2007 18:15:38 -0600 Subject: jython import search path In-Reply-To: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> References: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> Message-ID: Russ wrote: > I have a Python program that I want to run in Jython so I can get Java > bytecode output. The program runs fine in Python, but when I change > the first line of the main program to make it run in Jython, it fails > to find some of the imported modules. These are just plain Python > imports of code I wrote myself in another directory. > > Apparently Jython does not use the PYTHONPATH environment variable. I > created an environment variable called JYTHONPATH just to see what > would happen, but it didn't work either. How am I supposed to tell > Jython where to search for imported modules? Thanks. > Maybe Jython expert has the perfect answer but til then. Did you try: sys.path.append('path to search') Usually this works if nothing else does. -Larry From Eric_Dexter at msn.com Sat Feb 3 15:49:17 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 3 Feb 2007 12:49:17 -0800 Subject: Where Does One Begin? In-Reply-To: References: <1170485721.683685.178470@v33g2000cwv.googlegroups.com> Message-ID: <1170535757.121230.48110@a75g2000cwd.googlegroups.com> On Feb 3, 2:16 am, Marc 'BlackJack' Rintsch wrote: > In <1170485721.683685.178... at v33g2000cwv.googlegroups.com>, > > Eric_Dex... at msn.com wrote: > > pygame is probily a good program to start with as long as you keep in > > mind that it is possible that up to 50% of the p.c. laptops may not be > > able to run it. > > Huh? Care to explain this? > > Ciao, > Marc 'BlackJack' Rintsch This is based on the documentation from panda3d explaining why certain functions do not work on pc lap tops. The trend in tek is smaller faster exc exc.. based on what they said at the time of thier documation and I would have to check this certain functions are not available because of memory of the graphics card??? I am going by memory and as promised those panda 3d functions do not work but the program overall is fine. There is no explanation in directpy but the mentioned using several methods and the method they use in the demo showing the island does not work but overall it works fine. For pygame the best I could get on my laptop was the outline of a window I was never able to get any graphics. There is some assumption based on what I read in the panda3d stuff that leads me to believe it is because of a lesser graphics. I could be wrong.. I looked into wxwindows a little further and have noticed more graphics stuff but documentation and tutorials for that sort of thing isn't readily available so hopefully there is a fix of pygame or more docs on wxwindows (or tkinter) that I can use at some time. From snewman18 at gmail.com Sat Feb 17 19:55:15 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: 17 Feb 2007 16:55:15 -0800 Subject: Help Parsing XML Namespaces with BeautifulSoup Message-ID: <1171760115.450909.65550@q2g2000cwa.googlegroups.com> I'm trying to parse out some XML nodes with namespaces using BeautifulSoup. I can't seem to get the syntax correct. It doesn't like the colon in the tag name, and I'm not sure how to refer to that tag. I'm trying to get the attributes of this tag: The only way I've been able to get it is by doing a findAll with regex. Is there a better way? ---------- from BeautifulSoup import BeautifulStoneSoup import urllib2 url = 'http://weather.yahooapis.com/forecastrss?p=33609' page = urllib2.urlopen(url) soup = BeautifulStoneSoup(page) print soup['yweather:forecast'] ---------- From laurent.pointal at limsi.fr Mon Feb 5 10:45:59 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 05 Feb 2007 16:45:59 +0100 Subject: Python 3.0 (Was: when will python 2.5 take in mainstream?) In-Reply-To: References: <4Rrxh.18423$pQ3.12414@newsread4.news.pas.earthlink.net> <1170631417.253200.136330@h3g2000cwc.googlegroups.com> Message-ID: Steven Bethard a ?crit : > Laurent Pointal wrote: >> For Python 3.0, AFAIK its a big rewrite and developers know that it will >> be uncompatible in large parts with existing code. > > Wrong on both counts. ;-) Python 3.0 is not a rewrite. It's based on the > same code base as the 2.X line, but with a lot of the old deprecated > things removed. And, while Python 3.0 is allowing itself to break > backwards compatibility, at least that the Python level, it should be > largely compatible with the 2.X line. There will be some breakages, but > (1) they shouldn't be too extensive and (2) there will be utilities to > help you update your code. In many cases, it will be possible to write > code that works in both Python 2.X and 3.0. > > STeVe Hum my brain just mix 3 and 3000. Sorry, just a factor 1000. From eurleif at ecritters.biz Thu Feb 8 14:22:34 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 08 Feb 2007 14:22:34 -0500 Subject: default mutable arguments In-Reply-To: References: Message-ID: <45cb7879$0$6842$4d3efbfe@news.sover.net> Gigs_ wrote: > I read that this is not the same: > def functionF(argString="abc", argList = None): > if argList is None: argList = [] # < this > ... > def functionF(argString="abc", argList=None): > argList = argList or [] # and this > ... > > Why? If argList is a false value besides None ("", [], {}, False, etc.), the second example will replace it with an empty list. From lbates at websafe.com Mon Feb 26 10:20:47 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 26 Feb 2007 09:20:47 -0600 Subject: convert python scripts to exe file In-Reply-To: References: Message-ID: <45E2FACF.4090503@websafe.com> Eric CHAO wrote: > I know py2exe can make an exe file. But python runtime dll is still > there. How can I combine the dll file into the exe, just make one > file? > > Thanks. You can use the bundle= parameter to get "less" files, but you can't get to only 1 because you need mscvr71.dll and w9xpopen.exe at a minimum as external files. If you want to have only 1 .EXE to distribute, use Inno Installer. Your users will thank you for having a proper installer, uninstaller. -Larry Bates From gagsl-py at yahoo.com.ar Fri Feb 16 17:40:39 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 19:40:39 -0300 Subject: can't load a dll in python 2.5 References: <1171656997.423604.175410@v45g2000cwv.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 18:11:53 -0300, Steven Bethard escribi?: > dwmaillist at gmail.com wrote: >> I am on WindowsXP. I have a dll that I can load in python 2.3 but >> when trying to load it into python 2.5 it complains that there is >> nothing by that name. Is there some aspect of the dll loading >> mechanism between python 2.3 and 2.5 that has changed preventing me >> from loading the dll in 2.5? Thanks in advance for your suggestions. > > Don't know if this is your problem, but as of Python 2.5, ".dll is no > longer supported as a filename extension for extension modules. .pyd is > now the only filename extension that will be searched for". (That's the > last line on http://docs.python.org/whatsnew/ports.html) And remember that extensions must be recompiled for the specific Python version in use (up to the second digit). That is, if you have an extension for Python 2.3, it won't work for 2.5. -- Gabriel Genellina From jessechounard at gmail.com Fri Feb 2 10:31:08 2007 From: jessechounard at gmail.com (Jesse Chounard) Date: Fri, 2 Feb 2007 09:31:08 -0600 Subject: division by 7 efficiently ??? In-Reply-To: <1170299594.491478.310430@a34g2000cwb.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> Message-ID: On 31 Jan 2007 19:13:14 -0800, krypto.wizard at gmail.com wrote: > Its not an homework. I appeared for EA sports interview last month. I > was asked this question and I got it wrong. I have already fidlled > around with the answer but I don't know the correct reasoning behind > it. I think this works: >>> def div7 (N): ... return ((N * 9362) >> 16) + 1 ... >>> div7(7) 1 >>> div7(14) 2 >>> div7(700) 100 >>> div7(70000) 10000 The coolest part about that (whether it works or not) is that it's my first Python program. I wrote it in C first and had to figure out how to convert it. :) Jesse From __peter__ at web.de Wed Feb 28 02:38:41 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Feb 2007 08:38:41 +0100 Subject: Changing directories in oswalk [was Re: Walk thru each subdirectory from a top directory] References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <1172529799.827628.321760@p10g2000cwp.googlegroups.com> <12ua1bo77j0n724@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Tue, 27 Feb 2007 20:31:43 -0800, Scott David Daniels wrote: > >>> def findallfiles(self, base): >>> self.results = [] >>> for root,dirs,files in os.walk(base): >>> os.chdir(root) >> ^^^ Mistake here, don't change directories during os.walk ^^^ > > I came across this problem some time ago. I had to walk a directory tree, > calling an external program on each file. Unfortunately, that external > program wrote directly to the current working directory, which caused all > sorts of havoc. This is how I dealt with it: > > > def unbin(where): > """Walk through a directory tree, calling macunpack to extract the > contents of MacBinary files. > """ > def _unbin(data, dirname, files): > for oldname in files: > fullname = os.path.normpath(os.path.join(dirname, oldname)) > if os.path.isfile(fullname): > # Dammit, macunpack writes directly to the current > # working directory. Changing the cwd breaks the file > # tree walker, so we have to remember the current > # directory, change it to where we want to be, then > # change it back. > wd = os.getcwd() > os.chdir(dirname) > result = os.system('macunpack -f "%s"' % oldname) > if result == 0: > # Unpacking worked, so delete the original. > os.remove(oldname) > os.chdir(wd) # sigh... > > os.path.walk(where, _unbin, None) > > > Is there another (better) way of dealing with this sort of situation? Does the problem occur if you pass an absolute path to os.walk()/os.path.walk()? Peter From eurleif at ecritters.biz Thu Feb 8 14:02:09 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 08 Feb 2007 14:02:09 -0500 Subject: begin to parse a web page not entirely downloaded In-Reply-To: <1170958856.700750.3080@a75g2000cwd.googlegroups.com> References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> <45cb63d4$0$6842$4d3efbfe@news.sover.net> <1170958856.700750.3080@a75g2000cwd.googlegroups.com> Message-ID: <45cb73b0$0$6842$4d3efbfe@news.sover.net> k0mp wrote: > It seems to take more time when I use read(size) than just read. > I think in both case urllib.openurl retrieve the whole page. Google's home page is very small, so it's not really a great test of that. Here's a test downloading the first 512 bytes of an Ubuntu ISO (beware of wrap): $ python -m timeit -n1 -r1 "import urllib" "urllib.urlopen('http://ubuntu.cs.utah.edu/releases/6.06/ubuntu-6.06.1-desktop-i386.iso').read(512)" 1 loops, best of 1: 596 msec per loop From subscriber123 at gmail.com Mon Feb 12 20:38:58 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Mon, 12 Feb 2007 20:38:58 -0500 Subject: Gosper arithmetic in Python In-Reply-To: <4c0048df0702121736j75096631geecfe73eb462531a@mail.gmail.com> References: <4c0048df0702121736j75096631geecfe73eb462531a@mail.gmail.com> Message-ID: <4c0048df0702121738l39a9d087vd2282445241460b0@mail.gmail.com> By the way, there are some commented out portions of code in there which you can just remove, if you want. The last two lines of the program are unnecessary, as well. On 2/12/07, Subscriber123 wrote: > > Speaking of useful home-made modules, I wrote this primitive module which > does limited math with fractions. Anyone is welcome to expand on it or use > it for any purpose. If anyone would like to submit it as a PEP to be added > to the Python library of reference, that would be great. If anyone wishes to > do that, I ask that you at least add me as a coauthor. > > Collin Stocks > > On 2/12/07, Marcin Ciura wrote: > > > > Hello, > > > > I hacked together a module implementing exact real > > arithmetic via lazily evaluated continued fractions. > > You can download it from > > http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py > > an use as an almost drop-in replacement for the math module > > if you don't care too much about performance. > > I'd be happy to hear any feedback and suggestions. > > > > Cheers, > > Marcin > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Mon Feb 26 23:00:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 26 Feb 2007 20:00:53 -0800 Subject: Is type object an instance or class? In-Reply-To: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> References: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> Message-ID: JH wrote: > Hi > > I found that a type/class are both a subclass and a instance of base > type "object". > > It conflicts to my understanding that: > > 1.) a type/class object is created from class statement > 2.) a instance is created by "calling" a class object. > > A object should not be both a class and an instance at the same time. > > Further I found out there is a special type call "type" that is a > subclass of base type "object". All other types are instances of this > type. Even base type "object" is an instance of this special type. > > What is role of this type "type" in object creation? Could someone > there straighten this concept a little? > > For example (Python2.5): > > >>>>issubclass(int, object) > > True > >>>>isinstance(int, object) > > True > >>>>print type(int) > > > >>>>isinstance(int, type) > > True > >>>>issubclass(int, type) > > False > >>>>issubclass(type, object) > > True > >>>>isinstance(type, object) > > True > >>>>isinstance(object, type) > > True > > Here is a primer on the topic: http://www.python.org/download/releases/2.2/descrintro/ James From http Tue Feb 6 16:27:35 2007 From: http (Paul Rubin) Date: 06 Feb 2007 13:27:35 -0800 Subject: Python does not play well with others References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> <1170796761.537999.224480@q2g2000cwa.googlegroups.com> Message-ID: <7xzm7rvuwo.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" writes: > In our case, the issue is this: we load a ton of info at server > restart, from the database. Some of it gets processed a bit based on > configuration files and so forth. If this were done in my own C > server, I'd do all of that and set up the (read-only) runtime data > structures prior to forking. That would mean that: > a) The processing time would be lower since you're just doing the pre- > processing once; and > b) The memory footprint could be lower if large data structures were > created prior to fork; they'd be in shared copy-on-write pages. If you completely control the server, write an apache module that dumps this data into a file on startup, then mmap it into your Python app. From karoly.kiripolszky at gmail.com Mon Feb 5 08:53:18 2007 From: karoly.kiripolszky at gmail.com (=?iso-8859-1?q?K=E1roly_Kiripolszky?=) Date: 5 Feb 2007 05:53:18 -0800 Subject: C parsing fun In-Reply-To: References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> Message-ID: <1170683598.782844.268190@k78g2000cwa.googlegroups.com> Marc 'BlackJack' Rintsch ?rta: > In <1170679559.272656.145660 at v33g2000cwv.googlegroups.com>, > karoly.kiripolszky wrote: > > > and the great thing is that the algorithm can be used with any > > language that structures the code with brackets, like PHP and many > > others. > > But it fails if brackets appear in comments or literal strings. > > Ciao, > Marc 'BlackJack' Rintsch From kar1107 at gmail.com Wed Feb 7 18:42:13 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 7 Feb 2007 15:42:13 -0800 Subject: Running long script in the background In-Reply-To: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> Message-ID: <1170891733.083400.187620@s48g2000cws.googlegroups.com> On Feb 6, 5:26 am, "watter... at gmail.com" wrote: > Hello, > > I am trying to write a python cgi that calls a script over ssh, the > problem is the script takes a very long time to execute so Apache > makes the CGI time out and I never see any output. The script is set > to print a progress report to stdout every 3 seconds but I never see > any output until the child process is killed. > > Here's what I have in my python script: > > command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % > (host, domuname) > output = os.popen(command) Apart from other buffering issues, it could be very well that ssh returns all the output in one single big chunk. Try running the ssh command (with the trailing 'command') from your shell and see if it generates output immediately. There may be some option to make ssh not buffer the data it reads from the remove command execution. If there is no such option, most likely you are out of luck. In this case, even if you making your remote script unbufferred, ssh may be buffering it. If both the machines have any shared filesystem, you can do a trick. Make your script write it's output unbuffered to a file. Since the file is mounted and available on both the machines.. start reading the file from this main python script (note that you may need a thread to do it, as your script will anyway be stuck waiting for the ssh to complete). Karthik > for line in output: > print line.strip() > > Here's a copy of the bash script. > > http://watters.ws/script.txt > > I also tried using os.spawnv to run ssh in the background and nothing > happens. > > Does anybody know a way to make output show in real time? From mralokkp at gmail.com Fri Feb 16 05:59:15 2007 From: mralokkp at gmail.com (mralokkp) Date: 16 Feb 2007 02:59:15 -0800 Subject: Any Idea about thread safe issue with python Message-ID: <1171623555.377250.228240@j27g2000cwj.googlegroups.com> Hi All I need help guys. I have a code running properly and execute again after a certain time. But The thing i am looking for that it should not start from other instance says looking for thread safe In Simple words .................... ........................ self.lock = thread.allocate_lock() .......................... is not solving my purpose. Would any body like to help. Regards Alok From http Thu Feb 8 14:05:24 2007 From: http (Paul Rubin) Date: 08 Feb 2007 11:05:24 -0800 Subject: Functions, parameters References: <45cb6def$0$1014$426a74cc@news.free.fr> Message-ID: <7x4ppwsc5n.fsf@ruckus.brouhaha.com> Boris Ozegovic writes: > > def filter(self, **kw): > > for argname, value in kw.items(): > > fieldname, op = argname.split('__', 1) > > Yes, this is what confused me in the first place: how to separate > arguments. If you call split, and split returns list of String, then you > have fieldname = 'question' and startwith = 'what', and not references at > question and startwith, or am I missing something big. Oh, I understand your question now. The call was: Poll.objects.filter(question__startswith='What') 'filter' receives the argument 'kw', which is a dictionary whose value will be { 'question__startswith' : 'What' } That means the "for argname, value" loop iterates just once, with argname = 'question__startswith' and value = 'What' Since split is applied to argname, it retrieves 'question' and 'startswith'. From cyberco at gmail.com Wed Feb 21 16:28:03 2007 From: cyberco at gmail.com (cyberco) Date: 21 Feb 2007 13:28:03 -0800 Subject: wxPython: non-GUI thread launching new frame? Delegates? In-Reply-To: References: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> <5405fnF1upuuoU1@mid.uni-berlin.de> <1172001661.882918.193600@l53g2000cwa.googlegroups.com> Message-ID: <1172093283.547435.135860@h3g2000cwc.googlegroups.com> Oh boy....I must have hit an all time programmers-low with this.... That was plain stupid. 2B > You don't need the lambda - you can use: > > wx.CallAfter(parent.OnRequest, param) From paul at boddie.org.uk Sun Feb 4 12:08:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Feb 2007 09:08:22 -0800 Subject: Python does not play well with others In-Reply-To: <874pq23prw.fsf@gmail.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <1170546032.316062.133050@m58g2000cwm.googlegroups.com> <1170598859.290983.136300@j27g2000cwj.googlegroups.com> <874pq23prw.fsf@gmail.com> Message-ID: <1170608902.803902.177670@l53g2000cwa.googlegroups.com> Jorge Godoy wrote: > "Paul Boddie" writes: > > > And while Python eggs may be useful for people managing additional > > software as some unprivileged user, hosting providers (and virtual > > private server administrators) will want packages that fit in with the > > rest of the software being managed in the hosting environment. > > And why eggs wouldn't satisfy them? Eggs can be installed globally as well, > making the package available to every client of this hosting server (if they > mount their libs from a unique NFS server then it would automatically be > available for all of their servers). Because Python is just another thing to support for various hosting providers. One of the problems people supposedly have when persuading such companies to add or update packages is, I imagine, a lack of familiarity those companies have with Python technologies. Asking them to use a technology-specific packaging system might be a bit much if they aren't even familiar with (or interesting in knowing more about) the packages required to satisfy their customers' basic needs. Moreover, there's a lot of software in the average GNU/Linux or BSD distribution, but if you had to "break out" into technology-specific package/dependency managers to install some of the more heterogeneous packages, it would be a nightmare: perhaps installing the documentation would have you visit CPAN for some Perl scripts before throwing you into the TeX package manager to get some missing TeX libraries; then you might be off into setuptools for the Python scripting extensions, possibly via equivalent tools for other scripting extensions; finally, you'd be off via any other system thought essential to manage software from a particular parochial technological viewpoint. I've had to install software like this, and it takes huge amounts of time for no good reason if you can use system packages instead. Paul From olivier.feys at gmail.com Tue Feb 6 06:00:23 2007 From: olivier.feys at gmail.com (Olivier Feys) Date: Tue, 06 Feb 2007 12:00:23 +0100 Subject: Repr or Str ? In-Reply-To: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> References: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> Message-ID: <45C85FC7.5070305@gmail.com> str is a text representation of the object, you can see it as a nice print repr is the text representation of the object that you can evaluate to get the same object Johny wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences > Thanks > LL > > From jstroud at mbi.ucla.edu Tue Feb 27 07:27:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 27 Feb 2007 12:27:17 GMT Subject: Curses sorely lacking an event loop? Message-ID: Hello, Is curses really lacking an event loop? Do I have to write my own? I infer from the docs that this is the case. For example, I want the screen to be updated with resize but I find myself waiting for getch() if I want user input, and so the screen must remain ugly until the user presses a key. What am I missing? Also, does anyone have boilerplate for handling mouse events? getmouse() returns an "ERR" of no particular description and also appears to require a preceding getch() and hence does not seem to be wired at all for clicks, although allusion to clicks is found in the descriptions for mouseinterval() and mousemask(). Here is the error message for getmouse() in case anyone wants details: "_curses.error: getmouse() returned ERR". This is much less informative than one might hope. Thanks in advance for any help. James From deets at nospam.web.de Tue Feb 20 08:35:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Feb 2007 14:35:16 +0100 Subject: CherryPy/Turbogears on server not controlled by me References: Message-ID: <540bokF1shej5U1@mid.uni-berlin.de> Brian Blais wrote: > Hello, > > I was wondering if there is a way to run CherryPy/Turbogears on a server > that I don't > have root access to. If I just choose a random port, I think the security > guys on > the server would get annoyed at me. Why should they? Opening anything networking will open a port. And if you have shell access, you can point PYTHONPATH to a directory of your choice and let easy_install install the packages required there. I don't see a problem. And _if_ they get mad at you, well - there isn't anything you can do about that I presume apart from telling them to shut up - because without a port, there is no webapp... Diez From fred at adventistcare.org Mon Feb 5 14:40:38 2007 From: fred at adventistcare.org (Sells, Fred) Date: Mon, 5 Feb 2007 14:40:38 -0500 Subject: How can I access data from MS Access? Message-ID: <1A4BF05172023E468CB6E867923BC90404B0CF89@accmail2.sunbelt.org> Peter, I sadly admit that I was wrong. "Doesn't seem to work" is effectivly even more useless than "doesn't work". I give up. Years ago we used to get our FORTRAN card decks back from the DP center with a piece of scrap paper saysing "She No Work". top that. From S.Mientki-nospam at mailbox.kun.nl Wed Feb 7 08:17:18 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 07 Feb 2007 14:17:18 +0100 Subject: Python editor In-Reply-To: <1170851197.656670.179590@a75g2000cwd.googlegroups.com> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> <1170851197.656670.179590@a75g2000cwd.googlegroups.com> Message-ID: <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> stani.vsvv at gmail.com wrote: > On Feb 6, 11:01 pm, Stef Mientki > wrote: >> BBands wrote: >>> No, no, no, this is not an invitation to the editor wars. > >>> I have been using Jos? Cl?udio Faria's superb Tinn-R,http://www.sciviews.org/Tinn-R/, >>> with the R language,http://www.r-project.org/. This editor allows you >>> to send code to the R shell for execution. You can easily send a line, >>> the selection, the balance after the cursor or the whole script. > > In SPE you can use Edit>Execute in shell (Shift+Ctrl+E). If there is > nothing selected SPE will run the whole script. > > Stani > > hi Stani, it's hard to get your hands on the SPE editor, bad links, server not available etc. When you finally got it, it crashes a lot (at least at my place). And it's even impossible to get a manual, to see if there's a course for these crashes ;-) I read about a free manual with adds, but I can find it no-where. And before I pay for the real manual, I want to see it running for at least 5 minutes ;-) So despite the potentials of SPE look very good, I keep myself to PyScripter ;-) cheers, Stef From grante at visi.com Mon Feb 12 12:04:28 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 12 Feb 2007 17:04:28 -0000 Subject: can't find a way to display and print pdf through python. References: Message-ID: <12t17gsjh6vgh94@corp.supernews.com> On 2007-02-12, Larry Bates wrote: >> I at least need the code for useing some library for >> connecting to acrobat reader and giving the print command on >> windows and some thing similar on ubuntu linux. > Just let the registered .PDF viewer do it for you. > > os.start('myfile.pdf') Eh? I don't see os.start() it either 2.5 or 2.44 documentation, and it's sure not there in 2.4.3: $ python Python 2.4.3 (#1, Dec 10 2006, 22:09:09) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.start Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'start' I did find os.startfile() in the docs, but it's shown as windows-only (it's not present under Linux). > Launches whatever is registered as .PDF viewer and user > can then print, save, zoom, etc. on their own. Really? -- Grant Edwards grante Yow! Civilization is at fun! Anyway, it keeps visi.com me busy!! From R.Brodie at rl.ac.uk Thu Feb 1 08:30:32 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 1 Feb 2007 13:30:32 -0000 Subject: Inconsistent list/pointer problem References: Message-ID: "Doug Stell" wrote in message news:tcp3s2996ukp0439omj70pjug5r8diu8p1 at 4ax.com... > I call the function, passing in a list as the input data. The function > must manipulate and operate on a copy of that list's data, without > altering the list in the calling routine. Then you will want to make a copy: listB = copy.deepcopy( listA) From deets at nospam.web.de Sat Feb 3 11:55:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 03 Feb 2007 17:55:09 +0100 Subject: Python does not play well with others In-Reply-To: <7xk5yz2q42.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> <7xk5yz2q42.fsf@ruckus.brouhaha.com> Message-ID: <52jt3eF1p85tbU1@mid.uni-berlin.de> Paul Rubin schrieb: > "Diez B. Roggisch" writes: >> This is simply not true. J2SE doesn't include a web-framework. J2EE >> does, but it's a separate multi-megabyte-download. > > I thought J2SE comes with JSP. Maybe that's not a "framework" in the > fancy sense though. JSP is also part of J2EE. http://java.sun.com/products/jsp/ """ Another key concern of the Java EE 5 specification has been the alignment of its webtier technologies, namely JavaServer Pages (JSP), JavaServer Faces (JSF), and JavaServer Pages Standard Tag Library (JSTL). """ >> PHP _is_ a web centered language, so to say it "includes" a > >> And _both_ of them don't contain DB connectivity modules! J2SE has >> JDBC - which is just a bunch of interfaces. You need to download each >> and every driver. > > Hmm, I thought it came with drivers. Maybe those come with the db > instead? Might be, for some. For others where the vendor doesn't care about Java, they aren't. And they certainly require special treatment like putting them in the classpath, setting up the project directory and the like - no simple import will work out of the box, as it would witch python standard lib drivers. diez From aspineux at gmail.com Thu Feb 1 19:19:47 2007 From: aspineux at gmail.com (aspineux) Date: 1 Feb 2007 16:19:47 -0800 Subject: how to add class attributes in __new__ In-Reply-To: <1170348611.562439.122780@a34g2000cwb.googlegroups.com> References: <1170348611.562439.122780@a34g2000cwb.googlegroups.com> Message-ID: <1170375587.745220.91540@m58g2000cwm.googlegroups.com> On 1 f?v, 17:50, "jeremito" wrote: > I am subclassing the array class and have __new__ to initialize and > create my class. In that class I create not only do I create an array > object, but I also create some other data in __new__ I want to have > access to outside of __new__. I tried > > self.mydata = mydata > > but that didn't work. > > Can someone point me in the right direction? > Thanks, > Jeremy self ? in __new__ ? What about with this ? def __new__(cls, *args, **kw): newobj=object.__new__(cls) newobj.foo='bar' return newobj From elrondrules at gmail.com Mon Feb 12 13:48:35 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 12 Feb 2007 10:48:35 -0800 Subject: post data using curl Message-ID: <1171306115.033300.22960@v45g2000cwv.googlegroups.com> hi need some help from the experts in this group as to how to do the following i have a http listener (A) that has subscribed to a process (B) and listening on a port.. now based on some command line arguments i need to send a xml file to the process B using curl.. is there a way to do this in python.. thx for the help From steve at holdenweb.com Thu Feb 15 06:14:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 11:14:11 +0000 Subject: Exception In-Reply-To: <854284.81743.qm@web54505.mail.yahoo.com> References: <854284.81743.qm@web54505.mail.yahoo.com> Message-ID: Navid Parvini wrote: > Dear All, > > Would you please tell me if there is a pysignal or method that called > when an exception is occurred? (I don't want to use "try" method) > No such method exists, and signals aren't used to generate exceptions. I'm afraid you want some other language, not Python. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From me at mylife.com Tue Feb 27 17:04:02 2007 From: me at mylife.com (Jason B) Date: Tue, 27 Feb 2007 22:04:02 GMT Subject: Pixel Array => Bitmap File References: Message-ID: Thanks, Roel... The Image.frombuffer() method looks promising, but the "mode" parameter seems a bit too limited for my needs. I must be able to specify not only the order of the bits (RGB in any order) but also whether the format is 565, 555, etc. Maybe I need to work outside the bounds of PIL? - J From robin at reportlab.com Thu Feb 15 05:50:52 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 15 Feb 2007 10:50:52 +0000 Subject: ANN: py lib 0.9.0: py.test, distributed execution, microthreads ... In-Reply-To: <20070214155335.GE16146@solar.trillke> References: <20070214155335.GE16146@solar.trillke> Message-ID: <45D43B0C.7000807@chamonix.reportlab.co.uk> holger krekel wrote: ........... > * py.execnet: ad-hoc code distribution to SSH, Socket and local sub processes ........... Good stuff, but my rather ancient win32 client could not work properly with SshGateway; I think plink might work. I hacked register.py so that the eventual command came out something like plink -ssh "MYSESSION" "python -u -c 'exec input()'" and then I can get a gateway open at least. The following script then works on my win32 box from py.execnet import SshGateway gw = SshGateway('MYSESSION',remotepython='python25') channel = gw.remote_exec('channel.send("Hello From the remote world!")') print channel.receive() and I see C:\tmp>\tmp\tgw.py Hello From the remote world! C:\tmp> -- Robin Becker From gregturn at mindspring.com Fri Feb 23 10:23:54 2007 From: gregturn at mindspring.com (Goldfish) Date: 23 Feb 2007 07:23:54 -0800 Subject: Module trouble [newbie] In-Reply-To: References: Message-ID: <1172244234.806105.273070@q2g2000cwa.googlegroups.com> On Feb 23, 6:44 am, Boris Ozegovic wrote: > Can somebody explaint this to me: > > I have module a.py > A = 100 > import b > print "A printing" > print "B is %s" % b.B > > and module b.py > B = 2000 > import a > print "B printing" > print "A is %s" % a.A > > I thought that output would be: > B printing > A is 100 > A printing > B is 2000 > > Because import b would execute b.py, and in b.py line "import a" would be > ignored, but my output is: > > >>> import a > > 100 > A printing > B is 100 > > ?? > > :) > > --http://www.nacional.hr/articles/view/23894/23 a.py ======= A = 100 import b print "A printing" print "B is %s" % b.B b.py ======= B = 2000 import a print "B printing" print "A is %s" % a.A Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import a B printing A is 100 A printing B is 2000 >>> Looks okay to me. From robin at reportlab.com Wed Feb 7 05:03:13 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 07 Feb 2007 10:03:13 +0000 Subject: Getting a class name from within main In-Reply-To: <1170838959.441543.19720@s48g2000cws.googlegroups.com> References: <1170838959.441543.19720@s48g2000cws.googlegroups.com> Message-ID: <45C9A3E1.1030300@chamonix.reportlab.co.uk> bg_ie at yahoo.com wrote: > Hi, > > Lets say I have the following class - > > class MyClass: > def __init__(self): > print (__name__.split("."))[-1] > > if __name__ == '__main__': > MyClassName = "MyClass" > > I can print the name of the class from within the class scope as seen > above in the init, but is there any way of printing it from within the > main without creating an object of the MyClass type. I need to assign > the name of the class within my script, to a variable in main. > > Thanks, > > Barry. > >>> class A: ... pass ... >>> print A.__name__ A >>> -- Robin Becker From andrea.gavana at gmail.com Fri Feb 9 15:59:14 2007 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Fri, 9 Feb 2007 21:59:14 +0100 Subject: [pywin32] - Excel COM problem Message-ID: Hi All, I have a very simple python script that tries to put a rectangular shape in a worksheet and then add some text inside that shape. The main problem, is that as usual Excel doesn't like input strings longer than 200 and something characters. So, by just recording a macro in Excel, I tried to append the text in the shape by dividing it in chunks. For example, I tried this little script: #---------------------------------- from win32com.client import Dispatch finalText = "A"*1250 xlsapp = Dispatch("Excel.Application") wb = xlsapp.Workbooks.Add() sheet = wb.Sheets[0] myShape = sheet.Shapes.AddShape(1, 315, 200, 400, 300) myShape.Select() xlsapp.Selection.Characters.Text = finalText[0:200] xlsapp.Selection.Characters(200).Insert(finalText[200:400]) excelfile = "Hello.xls" wb.SaveAs(excelfile) wb.Close() xlsapp.Quit() #---------------------------------- And it crashes with an impossible error: Traceback (most recent call last): File "D:\MyProjects\pywin32.py", line 13, in xlsapp.Selection.Characters(200).Insert(finalText[200:400]) File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 172, in __call__ return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_. defaultDispatchName,None) pywintypes.com_error: (-2147352573, 'Member not found.', None, None) However, the macro I recorded in Excel does exactly that: it appends chunks of the string with a maximum length of 200 chars. Am I missing something here? This is with Python 2.5, PythonWin 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32, Windows XP SP2. Thank you for your consideration. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ From larry.bates at websafe.com Tue Feb 6 11:09:35 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 06 Feb 2007 10:09:35 -0600 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: Message-ID: Steven Bethard wrote: > Jean-Paul Calderone wrote: >> Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve I can't think of any of my code that got broken and it fixed a broken SSL problem (on Windows) that I was fighting. -Larry From JoostMoesker at gmail.com Thu Feb 1 04:49:49 2007 From: JoostMoesker at gmail.com (Joost) Date: 1 Feb 2007 01:49:49 -0800 Subject: stlib name clash when using python as ASP language Message-ID: <1170323389.184681.250640@v45g2000cwv.googlegroups.com> Hi guys, I have couple of simple python based active server pages that make use of httplib2 which uses gzip.py. IIS, however, also has a gzip.dll located at the iis/inetsrv path. When using ASP the iis/inetsrv path is placed as the first item in sys.path. Consequently importing httplib2 will cause the following error: import httplib2 File "c:\python24\lib\site-packages\httplib2-0.2.0-py2.4.egg \httplib2\__init__.py", line 25, in ? import gzip ImportError: dynamic module does not define init function (initgzip) This is, of course, because it tries to load the gzip.dll file instead of the gzip.py file. The following per page hack *fixes* the problem most of the time: import sys sys.path[0] = "c:/python24/lib" Strangely, even with this code loaded in every page the import error sporadically occurs. What would be the preferred way to solve this name clash? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Feb 17 17:44:55 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 17 Feb 2007 23:44:55 +0100 Subject: cmd all commands method? References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> Message-ID: <53per7F1t12jjU1@mid.individual.net> placid wrote: > if i want to treat every cmdloop prompt entry as a potential > command then i need to overwrite the default() method ? Excuse me, what's a cmdloop prompt? What's the "default() method"? > What i want to achieve is to be able to support global variable > creation for example; > > res = sum 1 2 > > this would create a variable res with the result of the method > do_sum() ? > > then would i be able to run; > > sum a 5 > > this would return 8 or an error saying that res is not defined Are you sure you're talking about Python here? Regards, Bj?rn -- BOFH excuse #7: poor power conditioning From ian.brady1 at gmail.com Tue Feb 6 13:31:10 2007 From: ian.brady1 at gmail.com (ian.brady1 at gmail.com) Date: 6 Feb 2007 10:31:10 -0800 Subject: Help with multiple key sort Message-ID: <1170786670.535839.118650@s48g2000cws.googlegroups.com> gurus: I want to implement a sql-like sort-by on multiple keys. I've seen many examples of just two keys. I have a list like this 1 one 2 1 one 1 1 two 1 1 one 0 1 xx 0 result should be like this 1 four 2 1 one 0 1 one 1 1 one 2 1 xx 0 It moves right while keeping sorted order to the left. This is the new stable sort in 2.5. I'm not sure what I'm doing wrong. please help. Thanks From bignose+hates-spam at benfinney.id.au Wed Feb 14 07:05:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Feb 2007 23:05:25 +1100 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171437351.206085.236450@q2g2000cwa.googlegroups.com> <1171444128.138234.50640@l53g2000cwa.googlegroups.com> <462097E6-082A-4B22-AD8E-B98C4E5EF051@gmail.com> Message-ID: <87tzxp6j22.fsf@benfinney.id.au> Michael Bentley writes: > # Something just doesn't seem right in those > # "Every kiss begins with 'K'" commercials. > > >>> 'Every Kiss'.startswith('K') > False >>> kisses = ["kiss", "kiss", "kiss", "kiss", "kiss"] >>> kisses == [kiss for kiss in kisses ... if kiss.startswith("k")] True Happy St. Valentine's Day, everyone. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__) Jones | Ben Finney From aleaxit at gmail.com Fri Feb 23 18:29:46 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 23 Feb 2007 15:29:46 -0800 Subject: Rational numbers In-Reply-To: <1172271150.718838.10170@s48g2000cws.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172268954.974348.93540@q2g2000cwa.googlegroups.com> <1172271150.718838.10170@s48g2000cws.googlegroups.com> Message-ID: <1172273386.266919.318150@m58g2000cwm.googlegroups.com> On Feb 23, 2:52 pm, cas... at comcast.net wrote: > > Am I hallucinating? Didn't I see at least some version > > of gmpy for Python 2.5 on SourceForge awhile back? > > I distinctly remember thinking that I don't have to > > direct people to your site, but SourceForge is not > > showing anything beyond vesion 1.01 for Python 2.4. > > Alex released versions 1.02 and 1.03 as CVS updates only. I think he > may have made an announcement that 1.02 included alpha support for > Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there > has been an official release, though. Right: apparently sourceforce doesn't want me to do "releases" any more (quite apart from the utter mess that doing a "release" on sourceforce always was and still is), though I can still update the cvs repository -- that's part of why I'm moving to Google Code hosting. Alex From bearophileHUGS at lycos.com Tue Feb 27 05:53:32 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Feb 2007 02:53:32 -0800 Subject: Preallocate? -- potentially brain dead question about performance In-Reply-To: <45e389aa$1@griseus.its.uu.se> References: <45e368ea$1@griseus.its.uu.se> <1172533460.309061.255590@h3g2000cwc.googlegroups.com> <45e389aa$1@griseus.its.uu.se> Message-ID: <1172573612.150907.78690@8g2000cwh.googlegroups.com> Jan Danielsson: > ...completely avoiding the design issue I raised altogether. Thanks! > Exactly what I was hoping for! :-) Another common way to do it, it may be a little slower because that n,txt is a tuple: items = set(int(n) for n,txt in mylist) Bye, bearophile From steve at holdenweb.com Tue Feb 6 10:53:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 06 Feb 2007 15:53:15 +0000 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> Message-ID: jeremito wrote: > Please excuse me if this is obvious to others, but I can't figure it > out. I am subclassing dict, but want to prevent direct changing of > some key/value pairs. For this I thought I should override the > __setitem__ method as such: > > > class xs(dict): > """ > XS is a container object to hold information about cross sections. > """ > > def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): > """ > """ > x = {} > x['xS'] = xS > x['xF'] = xF > x['nu'] = nu > x['xG'] = xG > x['xA'] = x['xG'] + x['xF'] > x['xT'] = x['xA'] + x['xS'] > > return x > > def __setitem__(self, key, value): > """ > I have overridden this method to prevent setting xT or xA > outside the > class. > """ > print "I am in __setitem__" > if key == 'xT': > raise AttributeError("""Can't change xT. Please change, > xF, xS, or xG""") > > > But I can't even get __setitem__ to run. Example: > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import xs >>>> cs = xs.xs() >>>> cs > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0} >>>> cs['xT'] = 3.1415 >>>> cs > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': > 3.1415000000000002} > > > Is this what the __setitem__ method is for? If not, how can I do what > I want to do? >>> class d(dict): ... def __setitem__(self, k, v): ... print "Setting", k ... dict.__setitem__(self, k, v) ... >>> dd = d() >>> dd['steve'] = 'holden' Setting steve >>> dd['steve'] 'holden' >>> I believe the problem is that your __new__ method does not return an object of type xs but a dict, so it does not inherit the __getitem__ method from xs but instead from dict. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From http Mon Feb 5 11:20:28 2007 From: http (Paul Rubin) Date: 05 Feb 2007 08:20:28 -0800 Subject: when will python 2.5 take in mainstream? References: Message-ID: <7xtzy0wp83.fsf@ruckus.brouhaha.com> Laurent Pointal writes: > IMHO trying to have a binary compatibility with older compiled modules > by maintaining an ad-hoc layer to switch between 2.4/2.5 engines make > Python code more complex. And more complex code have generally more > bugs. This is the reason for my KISS hope about Python. I haven't heard of other languages that seriously try to do that, though maybe some do. I do know that in high-availability systems it's common to expect to be able to upgrade the software without interrupting the running system. Erlang has features for that, and I've worked on C programs that implemented such hot-upgrade in painful ways. It's done (at least in the one I worked on) by making fresh copies in of all the important objects in a new address space, converting if necessary from the old version's data formats to the new version's, then switching from the old software and old space to the new software and new space. I think Python isn't used much for this type of application and so nobody has gone to such extremes. From jura.grozni at gmail.com Thu Feb 8 09:13:08 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 06:13:08 -0800 Subject: uml and python In-Reply-To: References: <1170900832.692717.259160@l53g2000cwa.googlegroups.com> <45caa188$1@news.arcor-ip.de> Message-ID: <1170943988.525743.19770@s48g2000cws.googlegroups.com> tahks guys From haraldarminmassa at gmail.com Fri Feb 2 04:09:56 2007 From: haraldarminmassa at gmail.com (GHUM) Date: 2 Feb 2007 01:09:56 -0800 Subject: win32com.client In-Reply-To: References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170379374.589869.158610@p10g2000cwp.googlegroups.com> <1170379682.386807.99880@a34g2000cwb.googlegroups.com> Message-ID: <1170407396.247914.272890@q2g2000cwa.googlegroups.com> rzed, > 1) In your browser, enter this URL:http://sourceforge.net/projects/pywin32/ > [...] > Try those steps, then try importing win32com again. man, you are SOOOOO 2005. Could'nt you please make a screen cap video, upload it to youtube and give a pointer to it on your blog? *wink* Harald From troy at gci.net Thu Feb 15 06:09:08 2007 From: troy at gci.net (Troy Melhase) Date: Thu, 15 Feb 2007 02:09:08 -0900 Subject: ANN: java2python 0.1 Message-ID: <200702150209.12720.troy@gci.net> java2python - Java to Python Source Code Translator --------------------------------------------------- java2python 0.1 Released 14 February 2007 What is java2python? ------------------------------------------------------------------------------ java2python is a simple but effective tool to translate Java source code into Python source code. It's not perfect, and does not aspire to be. Where can I get java2python? ------------------------------------------------------------------------------ java2python is available for download from Google code: http://code.google.com/p/java2python/downloads/list Project page: http://code.google.com/p/java2python/ How do I use java2python? ------------------------------------------------------------------------------ Like this: $ j2py -i input_file.java -o output_file.py The command has many options, and supports customization via multiple configuration modules. What are the requirements? ------------------------------------------------------------------------------ java2python requires Python 2.5 or newer. Previous versions may or may not work. java2python requires ANTLR and PyANTLR to translate code, but translated code does not require ANTLR. What else? ------------------------------------------------------------------------------ java2python is installed with distutils. Refer to the Python distutils documentation for more information. The digest version is: $ tar xzf java2python-0.1.tar.gz $ cd java2python-0.1 $ python setup.py install java2python is licensed under the GNU General Public License 2.0. No license is assumed of (or applied to) translated source. I'm very interested in your experience with java2python. Please drop me an note with any feedback you have. Troy Melhase mailto:troy at gci.net -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From celiadoug at mchsi.com Thu Feb 1 08:23:16 2007 From: celiadoug at mchsi.com (Doug Stell) Date: Thu, 01 Feb 2007 13:23:16 GMT Subject: Inconsistent list/pointer problem Message-ID: I am having a problem with the corruption of a list. It occurs only the first time that I call a function and never happens on subsequent calls. Any suggestions would be appreciated. I call the function, passing in a list as the input data. The function must manipulate and operate on a copy of that list's data, without altering the list in the calling routine. def myFunc(listA): listB = listA work on & modify listB return(listB) The first time this function touches listB, listA is corrupted. However, I get the right results from the function. On subsequent calls to the function, listA is not corrupted further and the function will always return the same wrong results, which would be correct given the corruption of listA created in the first call. I concluded that it appears that listB is still pointing at elements of listA and I need to force Python to reassign those pointers to point to copies of listA's elements. I've tried copying listA to a tuple and then change the copy back to a list. That sometimes works if the input data is a simple list. It does not work if the input data is a list extracted from a list of lists. listB = tuple(listA) listB = list(listB) I've tried building the copy of listA, element by element, but that doesn't work. listB = [] for x in listA: listB.append(x) I finally had to do some type changing during the element by element copy and that does seem to work. Thanks in advance for any suggestions. Doug From chandrapsg at gmail.com Mon Feb 26 01:41:32 2007 From: chandrapsg at gmail.com (chandrapsg at gmail.com) Date: 25 Feb 2007 22:41:32 -0800 Subject: help regarding python and jsp Message-ID: <1172472092.215780.250560@t69g2000cwt.googlegroups.com> Hi, i am working with jsp .. i wanna help regarding how to import or how to call python modules to jsp if a piece of code is availabe will be very helpful for me chandra From ishoej at gmail.com Fri Feb 2 07:01:14 2007 From: ishoej at gmail.com (Holger) Date: 2 Feb 2007 04:01:14 -0800 Subject: compound statement from C "?:" Message-ID: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> Hi I have not been able to figure out how to do compound statement from C - "?:" But something similar must exist...?! I would like to do the equivalent if python of the C line: printf("I saw %d car%s\n", n, n != 1 ? "s" : "") Please help /Holger From fridrikm at gmail.com Tue Feb 13 05:25:46 2007 From: fridrikm at gmail.com (fridrikm at gmail.com) Date: 13 Feb 2007 02:25:46 -0800 Subject: Testers please In-Reply-To: References: Message-ID: <1171362346.133027.42210@l53g2000cwa.googlegroups.com> On Feb 13, 1:38 am, martien friedeman wrote: > I have written this tool that allows you to look at runtime data and > code at the same time. > And now I need people to test it. > > The easiest way to see what I mean is to look at some videos:http://codeinvestigator.googlepages.com/codeinvestigator_videos > > It requires Apache and Sqlite. > > It works for me with a Firefox browser on Linux. I'm absolutely stunned. This is a great idea, especially because we all hate learning other people's code, and this makes the process so much easier. Got some exams coming up this week, but I'll do some testing in the weekend. I'd like to suggest one thing though. When evaluating conditional statements, it would be very useful to see what "else" meant in terms of the statement itself, for example: if foo == 1: # Instead of showing "true" this would show "foo == 1" elif foo == 2: # This would show "foo == 2" else: # Instead of showing "false". Here comes the tricky part. This should show the opposite of "foo == 1", as well as the following elif statements. So in this case, the tab could show "not (foo == 1) | (foo == 2)". The reason for why showing the negated else in the header (looking for a better word, this refers to the header shown when you click something) would be helpful is because it helps keep track of what statements are being evaluated, since "False" gives no information on what statment is being tested and if the code is long, you have to scroll way up to take a look at the if statement, so it will help a lot with complex code. While this is not hard to implement (unless I'm missing something), the implementation has some problems, because conditional statements can become very long, the else statement's tab could show an exceptionally long statement whereas showing just "False" keeps it at a fair length. I might be missing something in this suggestion though - if so, please set me straight. At any rate, I think you've done a great job on this. When I get around to testing it this weekend I'll post the results on the project's SourceForge forums. Regards, Fri?rik M?r From roman.yakovenko at gmail.com Thu Feb 1 05:54:41 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 1 Feb 2007 12:54:41 +0200 Subject: SWIG overhead In-Reply-To: <1170325295.575450.84340@s48g2000cws.googlegroups.com> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> Message-ID: <7465b6170702010254r5553c008k419994a53a3dfd83@mail.gmail.com> On 1 Feb 2007 02:21:35 -0800, Bart Ogryczak wrote: > Hi, > I?m looking for some benchmarks comparing SWIG generated modules with > modules made directly with C/Python API. Just how much overhead does > SWIG give? Doing profile of my code I see, that it spends quiet some > time in functions like _swig_setattr_nondinamic, _swig_setattr, > _swig_getattr. Before you decide to go "low level" consider to use Boost.Python. According to this( http://tinyurl.com/322d3p ) post it gives pretty good performance. P.S. The post does not contain numbers -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From hg at nospam.org Tue Feb 13 02:17:54 2007 From: hg at nospam.org (hg) Date: Tue, 13 Feb 2007 08:17:54 +0100 Subject: float print formatting References: Message-ID: Neil Cerutti wrote: > On 2007-02-13, hg wrote: >> Hi, >> >> Considering the float 0.0, I would like to print 00.00. >> >> I tried '%02.02f' % 0.0 ... but I get 0.00 >> >> Any clue ? > > Yes. How wide (total) is "0.00", compared to "00.00"? > > -- > Neil Cerutti I do not get it s = '%02.02f' % 0.0 s >> '0.00' len(s) >> 4 From MonkeeSage at gmail.com Tue Feb 27 22:14:08 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 27 Feb 2007 19:14:08 -0800 Subject: Yet another unique() function... In-Reply-To: <1172631825.777298.257980@j27g2000cwj.googlegroups.com> References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <7x8xej80a5.fsf@ruckus.brouhaha.com> <7xzm6z6lf4.fsf@ruckus.brouhaha.com> <1172631825.777298.257980@j27g2000cwj.googlegroups.com> Message-ID: <1172632447.983332.274170@v33g2000cwv.googlegroups.com> On Feb 27, 9:03 pm, "MonkeeSage" wrote: > On Feb 27, 8:55 pm, Paul Rubin wrote: > > > > > Paul Rubin writes: > > > def unique(seq, keepstr=True): > > > t = type(seq) > > > if t==str: > > > t = (list, ''.join)[bool(keepstr)] > > > seen = [] > > > return t(c for c in seq if (c not in seen, seen.append(c))[0]) > > > Preferable: > > > def unique(seq, keepstr=True): > > t = type(seq) > > if t==str: > > t = (list, ''.join)[bool(keepstr)] > > seen = [] > > return t(c for c in seq if not (c in seen or seen.append(c))) > > Wow, nice! Very cool. :) > > Regards, > Jordan I posted this (attributed to you of course) in the comments section for the recipe. From nick at craig-wood.com Fri Feb 23 09:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 23 Feb 2007 08:30:07 -0600 Subject: Creating a daemon process in Python References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Message-ID: Eirikur Hallgrimsson wrote: > def daemonize(): > if (not os.fork()): > # get our own session and fixup std[in,out,err] > os.setsid() > sys.stdin.close() > sys.stdout = NullDevice() > sys.stderr = NullDevice() That doesn't close the underlying file descriptors... Here is another method which does :- null = os.open(os.devnull, os.O_RDWR) os.dup2(null, sys.stdin.fileno()) os.dup2(null, sys.stdout.fileno()) os.dup2(null, sys.stderr.fileno()) os.close(null) > if (not os.fork()): > # hang around till adopted by init > ppid = os.getppid() > while (ppid != 1): > time.sleep(0.5) > ppid = os.getppid() Why do you need hang around until adopted by init? I've never see that in a daemonize recipe before? > else: > # time for child to die > os._exit(0) > else: > # wait for child to die and then bail > os.wait() > sys.exit() -- Nick Craig-Wood -- http://www.craig-wood.com/nick From redvasily at gmail.com Sun Feb 11 23:04:11 2007 From: redvasily at gmail.com (Vasily Sulatskov) Date: 11 Feb 2007 20:04:11 -0800 Subject: Read/write 2D data from/to file..? In-Reply-To: <1171244850.077289.130330@s48g2000cws.googlegroups.com> References: <1171244850.077289.130330@s48g2000cws.googlegroups.com> Message-ID: <1171253051.599558.268780@v45g2000cwv.googlegroups.com> On Feb 12, 6:47 am, "mech point" wrote: > I was able to read the data from file into a two dimensional array > (lists) > > rows=[map(float,line.split())for line in file("data")] > > but How to write them back into the file. Using matplotlib it will be: import pylab rows = pylab.load('src.dat') pylab.save(rows, 'dst.dat') From bill.scherer at verizonwireless.com Tue Feb 6 15:00:05 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Tue, 06 Feb 2007 15:00:05 -0500 Subject: electronics and python In-Reply-To: References: Message-ID: <45C8DE45.8040107@verizonwireless.com> lee wrote: >Hi guys.....Is there any software written using python for >electronics.....i mean any simulation software or something?? > > Here's 'something': http://home.tiscali.be/be052320/Unum.html I find it useful for basic electronics math (Ohm's law, filters, etc). It keeps track of the units for you and does the right thing when you divide and multiply. You might find this recipie useful in combination with Unum: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499350 I'm not aware of anything else in the Python world that fits your query. Wish I was... HTH, Bill From jstroud at mbi.ucla.edu Thu Feb 22 23:34:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Feb 2007 20:34:13 -0800 Subject: What is the best queue implemetation in Python? In-Reply-To: <1172191010.013449.75720@q2g2000cwa.googlegroups.com> References: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> <1172191010.013449.75720@q2g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > On Feb 23, 11:24 am, "John" wrote: > >>Than C or PASCAL >>I mean, list or dictionary in Python are so powerful than the traditional >>array. Maybe I can make use of it? > > > Well, you could wite your own queue manager using Python lists, > but ... > > You have this strange reluctance to look in the documentation. Have > you tried Google? Try http://docs.python.org/lib/deque-objects.html > > Or perhaps you want/need the Queue module or the heapq module. > > *You* find them and *you* work out what is best for *your* needs. > > If you have a question that you could not answer yourself, then ask it > here. > > HTH, > John You could do yourself a favor and not answer. You would also be sparing the rest of us your rude tone. James From gagsl-py at yahoo.com.ar Sun Feb 18 17:10:07 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Feb 2007 19:10:07 -0300 Subject: Getting a class name References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> <1171818881.871094.295870@v33g2000cwv.googlegroups.com> Message-ID: En Sun, 18 Feb 2007 14:14:41 -0300, goodwolf escribi?: > On Feb 18, 9:17 am, "Gabriel Genellina" wrote: >> En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf >> escribi?: >> >> > I suppose that you wont get class name into its code (or before >> > definition end) but not into a method definition. >> >> > import sys >> >> > def getCodeName(deap=0): >> > return sys._getframe(deap+1).f_code.co_name >> >> > class MyClass (object): >> > name = getCodeName() + '!' >> >> What's the advantage over MyClass.__name__? >> >> -- >> Gabriel Genellina > >>>> class C(object): > ... name = C.__name__ > ... > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in C > NameError: name 'C' is not defined >>>> I were asking, why do you want a "name" attribute since "__name__" already exists and has the needed information. And worst, using an internal implementation function to do such task. -- Gabriel Genellina From free.condiments at gmail.com Wed Feb 7 12:28:10 2007 From: free.condiments at gmail.com (Sam) Date: Wed, 7 Feb 2007 17:28:10 +0000 Subject: Socket and array In-Reply-To: References: Message-ID: On 07/02/07, JStoneGT at aol.com wrote: > How to send an array via socket to the other end?Thanks. What you want is a serialisation solution - turning objects into a string format, and vice versa. Python provides a system for this in its standard library, in the pickle module. Some pseudocode might look like: #sender import pickle socket_send(pickle.dumps(my_list)) #receiver import pickle my_list = pickle.loads(read_all_socket_data()) However, this should only be used if you trust where the data is coming from; with untrusted data, a more restrictive format (such as JSON, perhaps, or a similar lightweight notation system if you are only sending lists) would be a good idea. --Sam From bj_666 at gmx.net Sun Feb 25 04:32:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 25 Feb 2007 10:32:47 +0100 Subject: RegExp performance? References: <45e145a0$0$90264$14726298@news.sunsite.dk> Message-ID: In <45e145a0$0$90264$14726298 at news.sunsite.dk>, Christian Sonne wrote: > Long story short, I'm trying to find all ISBN-10 numbers in a multiline > string (approximately 10 pages of a normal book), and as far as I can > tell, the *correct* thing to match would be this: > ".*\D*(\d{10}|\d{9}X)\D*.*" > > (it should be noted that I've removed all '-'s in the string, because > they have a tendency to be mixed into ISBN's) > > however, on my 3200+ amd64, running the following: > > reISBN10 = re.compile(".*\D*(\d{10}|\d{9}X)\D*.*") > isbn10s = reISBN10.findall(contents) > > (where contents is the string) > > this takes about 14 minutes - and there are only one or two matches... First of all try to get rid of the '.*' at both ends of the regexp. Don't let the re engine search for any characters that you are not interested in anyway. Then leave off the '*' after '\D'. It doesn't matter if there are multiple non-digits before or after the ISBN, there just have to be at least one. BTW with the star it even matches *no* non-digit too! So the re looks like this: '\D(\d{10}|\d{9}X)\D' Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Mon Feb 19 11:35:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Feb 2007 11:35:19 -0500 Subject: timeout in urllib.open() In-Reply-To: References: Message-ID: Stefan Palme wrote: >>>> [Peter] >>>> I believe this can only be set globally: >>>> >>>> import socket >>>> socket.setdefaulttimeout(seconds) >>>> >>> [Stefan] >>> ... >>> But when there is a "default timeout" (as indicated by >>> the method name) - isn't there a "per-socket timeout" >>> too? >> [Peter] >> Yes, but it isn't as easily available... >> >> Perhaps you find some ideas here: >> >> http://mail.python.org/pipermail/python-dev/2007-February/070897.html > > Thanks, will have a look at this. > This has recently been discussed on python-dev. It's likely that certain libraries will acquire a timeout keyword argument in the next release, but only if someone is concerned enough to develop the appropriate patches - the principle appears to be accepted. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 15:22:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 21:22:07 +0100 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: <45c78ad8$0$29725$426a74cc@news.free.fr> Larry Bates a ?crit : > > def avg(l): > return float(sum(l))/len(l) > > >>>>avg([1,2,3,4]) > > 2.5 def avg(*args): return float(sum(args)) / len(args)) > > Which can actually be read and debugged in the future! in_my_arms(tm) From gigs at hi.t-com.hr Mon Feb 19 07:10:28 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Mon, 19 Feb 2007 13:10:28 +0100 Subject: ocaml to python Message-ID: Is there any way to convert ocaml code to python? but not manually thx From exarkun at divmod.com Mon Feb 5 09:06:22 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 Feb 2007 09:06:22 -0500 Subject: subprocess stdin encoding In-Reply-To: <45C72918.4040603@branda.to> Message-ID: <20070205140622.25807.1351365980.divmod.quotient.10773@ohm> On Mon, 05 Feb 2007 20:54:48 +0800, Thinker wrote: > [snip] > >in site.py . and change if 0: to if 1: to enable string encoding. >Now, you can execute python interpreter with LC_CTYPE='UTF-8'. > While this is sort of a correct answer to the question asked, it isn't really a correct answer overall. I hope no one actually goes off and does this. Doing so will result in completely unportable code with very difficult to track down bugs. Instead, use the str and unicode methods "encode" and "decode". Jean-Paul From Shawn at Milochik.com Wed Feb 7 16:59:31 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Wed, 7 Feb 2007 16:59:31 -0500 Subject: Python new user question - file writeline error In-Reply-To: <1170876692.167248.244870@s48g2000cws.googlegroups.com> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> Message-ID: <2dc0c81b0702071359h59ef3205kbe8f28afcadb5fb0@mail.gmail.com> On 7 Feb 2007 11:31:32 -0800, James wrote: > Hello, > > I'm a newbie to Python & wondering someone can help me with this... > > I have this code: > -------------------------- > #! /usr/bin/python > > import sys > > month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG': > 8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > infile=file('TVA-0316','r') > outfile=file('tmp.out','w') > > for line in infile: > item = line.split(',') > dob = item[6].split('/') > dob = dob[2]+'-'+str(month[dob[1]])+'-'+dob[0] > lbdt = item[8].split('/') > lbdt = lbdt[2]+'-'+str(month[lbdt[1]])+'-'+lbdt[0] > lbrc = item[10].split('/') > lbrc = lbrc[2]+'-'+str(month[lbrc[1]])+'-'+lbrc[0] > lbrp = item[14].split('/') > lbrp = lbrp[2]+'-'+str(month[lbrp[1]])+'-'+lbrp[0] > item[6] = dob > item[8] = lbdt > item[10]=lbrc > item[14]=lbrp > list = ','.join(item) > outfile.writelines(list) > infile.close > outfile.close > ----------------------------- > > And the data file(TVA-0316) looks like this: > ----------------------------- > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,AST,19,U/L,5,40,, > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,GGT,34,U/L,11,32,h, > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,ALT,31,U/L,5,29,h, > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,ALKP,61,U/L,40,135,, > ----------------------------- > > Basically I'm reading in each line and converting all date fields (05/ > MAR/1950) to different format (1950-03-05) in order to load into MySQL > table. > > I have two issues: > 1. the outfile doesn't complete with no error message. when I check > the last line in the python interpreter, it has read and processed the > last line, but the output file stopped before. > 2. Is this the best way to do this in Python? > 3. (Out of scope) is there a way to load this CSV file directly into > MySQL data field without converting the format? > > Thank you. > > James > > -- > http://mail.python.org/mailman/listinfo/python-list > Your script worked for me. I'm not sure what the next step is in troubleshooting it. Is it possible that your whitespace isn't quite right? I had to reformat it, but I assume it was because of the way cut & paste worked from Gmail. I usually use Perl for data stuff like this, but I don't see why Python wouldn't be a great solution. However, I would re-write it using regexes, to seek and replace sections that are formatted like a date, rather than breaking it into a variable for each field, changing each date individually, then putting them back together. As for how MySQL likes having dates formatted in CSV input: I can't help there, but I'm sure someone else can. I'm pretty new to Python myself, but if you'd like help with a Perl/regex solution, I'm up for it. For that matter, whipping up a Python/regex solution would probably be good for me. Let me know. Shawn From cyberco at gmail.com Sat Feb 3 05:38:02 2007 From: cyberco at gmail.com (cyberco) Date: 3 Feb 2007 02:38:02 -0800 Subject: nokia pys60 contacts + calendar In-Reply-To: References: Message-ID: <1170499082.377190.25650@l53g2000cwa.googlegroups.com> You can most likely find an answer on Nokia's Python forum: http://discussion.forum.nokia.com/forum/forumdisplay.php?f=102 And if there's no answer there you should post the question there :) From paul at boddie.org.uk Fri Feb 23 17:04:49 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Feb 2007 14:04:49 -0800 Subject: Found a product for running Python-based websites off CDROM -have anybody tried it? In-Reply-To: References: Message-ID: <1172268288.954936.255130@t69g2000cwt.googlegroups.com> David Wishnie wrote: > > We've looked at XAMPP, and it has the following disadvantages compared > to Stunnix: I've only read the Stunnix Web site, and I've only seen XAMPP in passing. However... > * it's not targeted for putting to CDs at all (it's "unzip and run apache and > stuff" type of thing). This means it probably can't autochoose port numbers > for mysql and http. It has no functionality for easy stopping of webserver > and stuff from inside a script (that allows to release media on Linux and > OSX). It's seems not to be tested for running from read-only media. It has > no "showing logo at startup" functionality. I guess XAMPP isn't what you're looking for. But then, if it's just an issue of having Apache in a filesystem on a CD, the distance between convenient installation/unpacking of an Apache instance onto a normal disk and the preparation of a ready-to-run instance isn't that great: the two activities overlap, with the former perhaps providing the means to enable the latter. I do wonder how database writes are handled, though, or are bundled databases read-only? > * XAMPP for Linux and OSX is considered beta It shouldn't be too hard to work with anything UNIX-like. CD-ROMs are just read-only filesystems, and we're not even talking about live CD magic here. > * XAMPP is unsupported as a whole > > * XAMPP for Linux and OSX seem not to support Tomcat and mod_python Yes, but do we really care about Tomcat? ;-) > * XAMPP for OSX won't work on OSX 10.3 > > * Even if one will be able to somehow create a CD with XAMPP, the database > files and content of document root needs to be replicated for each platform. Doesn't everything understand ISO-9660 plus various extensions these days? > The only advantage of XAMPP is the price. But given a time needed for > highly-skilled enginer (with good programming skills) to spend on XAMPP > to make it ready for creating commercial CDs for Windows, Mac OSX - > cost of Stunnix tool is very attractive, and don't forget about updates and support. It's up to everyone to decide themselves how they spend their money, but remember that software like Apache doesn't require rocket science to set up in arbitrary locations, and database systems aren't that difficult to install in various places either. Perhaps the most difficult bit might be binary compatibility, and there'd be some discipline required in making sure the library dependencies could be satisfied on the target systems. Either that or you could give up and distribute a virtual machine image - there was a Python Web development image publicised a while back, in fact. Paul From ptmcg at austin.rr.com Thu Feb 1 02:10:15 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 31 Jan 2007 23:10:15 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170308178.823986.322700@h3g2000cwc.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170308178.823986.322700@h3g2000cwc.googlegroups.com> Message-ID: <1170313815.362394.92400@a34g2000cwb.googlegroups.com> On Jan 31, 11:36 pm, "Paddy" wrote: > On Feb 1, 2:42 am, krypto.wiz... at gmail.com wrote: > > > > > How to divide a number by 7 efficiently without using - or / operator. > > We can use the bit operators. I was thinking about bit shift operator > > but I don't know the correct answer. > >>> int.__div__(14,2) > 7 > > Not a minus or division operator in sight ;-) > > - Paddy. Now I'm confused - was the OP trying to divide by 7 or 2? -- Paul From rw at smsnet.pl Wed Feb 14 02:56:33 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 13 Feb 2007 23:56:33 -0800 Subject: calling php function from python In-Reply-To: References: Message-ID: <1171439793.002812.189790@v45g2000cwv.googlegroups.com> mark wrote: > is it possible to call a php function from python and use a class from > php in python? i want to use mmslib which creates mms messages and the > only implementation is a php mmslib implementation. You can consider to use some kind of RPC (remote procedure call) for example XML-RPC. This is a platform and language independent solution. Here you have some information: http://www.faqs.org/docs/Linux-HOWTO/XML-RPC-HOWTO.html http://groups.google.pl/group/comp.lang.python/msg/5a6ae6290593fc97 -- HTH, Rob From rory at campbell-lange.net Thu Feb 22 12:17:27 2007 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Thu, 22 Feb 2007 17:17:27 +0000 Subject: Local class variables? (mod_python problem) In-Reply-To: <20070222154239.GA12709@campbell-lange.net> References: <20070222103151.GA12437@campbell-lange.net> <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> <20070222154239.GA12709@campbell-lange.net> Message-ID: <20070222171727.GA26885@campbell-lange.net> On 22/02/07, Rory Campbell-Lange (rory at campbell-lange.net) wrote: > In essence we use class variables as follows: > > class Part (object): > totalgia = 0 > def __init__(self, gia): > self.gia = gia # gross internal area > self.giaratio = 0 > Part.totalgia += self.gia > def addavgbm(self): > self.giaratio = float(self.gia)/float(Part.totalgia) > def __repr__(self): > return "gia: %0.1f giaratio: %0.2f" % (self.gia, self.giaratio) > > if __name__ == '__main__': > p1 = Part(20) > p2 = Part(30) > for p in p1, p2: > p.addavgbm() > print p > > totalgia keeps incrementing when this code is used under mod_python. > On 22/02/07, Rory Campbell-Lange (rory at campbell-lange.net) wrote: On 22/02/07, Piet van Oostrum (piet at cs.uu.nl) wrote: > >>>>> Rory Campbell-Lange (RC) wrote: > >RC> totalgia keeps incrementing when this code is used under mod_python. > > And also when used outside of mod_python. It is because it is a class level > variable. In fact I think under certain circumstances in mod_python it will > not do that because different requests can run in different Apache > processes (on Linux, Unix, Mac OS X etc.). So it this desired behaviour or > not? Your post isn't clear about that. And if it isn't what is the desired > behaviour? > > And you certainly should do something about the concurrent access. It is not desirable for the class variable to keep incrementing outside of invocations of '__main__', as is the case when it is loaded under mod_python under apache2 on linux. I would be grateful for pointers on dealing with concurrent access. Regards Rory -- Rory Campbell-Lange From marco at waven.com Mon Feb 5 21:12:09 2007 From: marco at waven.com (Marco) Date: Tue, 6 Feb 2007 10:12:09 +0800 Subject: IOError: [Errno 4] Interrupted system call Message-ID: <5c62a320702051812m11994ee5idb5b37924b1171d0@mail.gmail.com> Hello,every one, I meet a question: in my old script, I usually use os.popen2() to get info from standard unix(LinuX) program like ps,ifconfig... Now, I write a OO-based programme, I still use os.popen2( check whether mplayer still working via ps command ), but some things I got the following message: Traceback (most recent call last): File "./mkt.py", line 351, in loop_timeout self.process(self.event.get_next()) File "./mkt.py", line 361, in process self.player.play(command[1]) File "./mkt.py", line 107, in play if self.is_playing(): File "./mkt.py", line 78, in is_playing info = rfd.readlines() IOError: [Errno 4] Interrupted system call why? Thank you! -- LinuX Power From claird at lairds.us Tue Feb 13 10:48:57 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 13 Feb 2007 15:48:57 +0000 Subject: Freeze packaging for Debian Message-ID: <9839a4-vpb.ln1@lairds.us> How is Freeze--freeze.py --packaged for Debian? *Is* it packaged for Debian? From gagsl-py at yahoo.com.ar Sun Feb 11 00:06:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 02:06:53 -0300 Subject: Can anyone explain a part of a telnet client code to me.. References: <1171165737.345518.281160@v45g2000cwv.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 00:48:57 -0300, Jia Lu escribi?: > I have a program that can telnet to a host. > But I cannot understand from [for c in data] part, can anyone explain > it to me? data is the received string. The for statement is used to iterate over a sequence; a string is considered a sequence of characters, so it iterates over all the characters in the string, one by one. py> data = "Hello" py> for c in data: ... print c, ord(c) ... H 72 e 101 l 108 l 108 o 111 py> -- Gabriel Genellina From http Sat Feb 3 00:41:05 2007 From: http (Paul Rubin) Date: 02 Feb 2007 21:41:05 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <7xhcu3hk7i.fsf@ruckus.brouhaha.com> Ben Finney writes: > "Something like it" *is* included in Python. Python 2.5 includes > SQLite in the standard library. Where do we draw the line? You want > MySQL, I want PostgreSQL, he wants Firebird, they want an interface to > something proprietary. Since Python is being touted as good for web apps as a competitor to PHP, it should offer the same db connectivity in its stdlib that PHP offers in its. I think that includes MySQL, PostgreSQL, and Oracle, but I dunno about Firebird. > All the *extra* stuff is what you're paying the hosting company to > take care of in the first place. No. I'm paying the hosting company for access to a computer that's connected to electricity and to the internet and which has a straightforward OS, language package, web server, and db installed. They need to know how to download a distro and type "make" to build and install it and occasionally upgrade to a new version, but they aren't expected to be experts on the intracacies of the software any more than the guy who sells me potatoes at the supermarket is supposed to be a gourmet chef. They shouldn't have to deal with dozens of interdependent modules downloaded from different places just to support one language. The fewer different packages they have to deal with, the better off everyone involved is. And that means that a package like Python should come preconfigured with all the modules that that a typical user would expect to want to use with it. From omelnyk at gmail.com Sat Feb 3 00:54:11 2007 From: omelnyk at gmail.com (Olexandr Melnyk) Date: Sat, 3 Feb 2007 08:54:11 +0300 Subject: python bracket In-Reply-To: References: Message-ID: By indentation: def some_function(): a = 10 print a print b # this statement doesn't belong to the function above --------------------------------- Olexandr Melnyk, http://omelnyk.net/ 2007/2/3, fatwallet961 at yahoo.com : > > there is no bracket in python > > how can i know where a loop or a function ends? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From writetosrj at gmail.com Mon Feb 19 01:04:33 2007 From: writetosrj at gmail.com (srj) Date: 18 Feb 2007 22:04:33 -0800 Subject: bluetooth on windows....... Message-ID: <1171865073.564109.240970@q2g2000cwa.googlegroups.com> hi. i've been trying to access Bluetooth via python in windows Xp. py bluez for windows required something called _msbt. i'm running python 2.5. some problem with vb 7.1 compatibility. what do i do to get bluetooth up and running on Xp? From bj_666 at gmx.net Sat Feb 10 08:59:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 10 Feb 2007 14:59:19 +0100 Subject: Glob returning an empty list when passed a variable References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> <1171113931.544838.103810@a75g2000cwd.googlegroups.com> Message-ID: In <1171113931.544838.103810 at a75g2000cwd.googlegroups.com>, Hieu.D.Hoang at gmail.com wrote: > With some number: > > In [2]: "% 3s" % 'a' > Out[2]: ' a' The space still doesn't have any effect here: In [66]: "%3s" % 'a' Out[66]: ' a' Ciao, Marc 'BlackJack' Rintsch From http Thu Feb 1 13:36:39 2007 From: http (Paul Rubin) Date: 01 Feb 2007 10:36:39 -0800 Subject: Question about a single underscore. References: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> Message-ID: <7xveilzpvs.fsf@ruckus.brouhaha.com> "Steven W. Orr" writes: > to cause a different instantiation a la > foo = _const() > The goal would be to create different instances of consts. The idea of putting it in sys.modules is so it's visible in all modules. > >>> import const > >>> iii=_const() You need iii = const._const From mail at microcorp.co.za Fri Feb 23 00:34:56 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 23 Feb 2007 07:34:56 +0200 Subject: is it possible to remove the ':' symbol in the end of linesstarting with 'if', 'while' etc? References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> <545eh7F1veg84U1@mid.uni-berlin.de> Message-ID: <022401c75716$aaa53800$03000080@hendrik> "Diez B. Roggisch" wrote: > openopt at ukr.net wrote: 8< ---------------- request to remove colon ---------------------- > Won't happen. There have been plenty of discussions about this, and while > technically not necessary, the colon is usually considered "optically > pleasing". So - it will stay. It is also used by text editors to make indentation of the next line happen... - Hendrik From andrewfelch at gmail.com Wed Feb 28 12:49:21 2007 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 28 Feb 2007 09:49:21 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172620060.412942.212130@a75g2000cwd.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> <1172615426.752353.25610@8g2000cwh.googlegroups.com> <1172616850.962166.27480@k78g2000cwa.googlegroups.com> <1172618605.121435.247300@t69g2000cwt.googlegroups.com> <1172619395.282157.187030@a75g2000cwd.googlegroups.com> <1172620060.412942.212130@a75g2000cwd.googlegroups.com> Message-ID: <1172684961.003652.74710@p10g2000cwp.googlegroups.com> On Feb 27, 6:47 pm, "Ziga Seilnacht" wrote: > Andrew Felch wrote: > > Thanks for checking. I think I narrowed the problem down to > > inheritance. I inherit from list or some other container first: > > > class PointList( list, AutoReloader ): > > def PrintHi1(self): > > print "Hi2" > > > class MyPrintingClass( AutoReloader ): > > def PrintHi2(self): > > print "Hi2v2" > > > Automatic reloading works for MyPrintingClass but not for PointList. > > Any ideas? > > > -Andrew > > Ah yes, this is the problem of list.__new__ not calling the next > class in MRO. Try to switch the bases, so that AutoReloader's > __new__ method will be called first. > > Ziga- Hide quoted text - > > - Show quoted text - So there is another bug crippling Python (see https://sourceforge.net/tracker/?func=detail&atid=105470&aid=628925&group_id=5470 ). Pickle and cPickle get confused after reloading, and won't let you dump the objects to file using protocol 2. The bug occurred for me when an instance of an AutoReloader class had a member not derived from AutoReloader (error text: "it's not the same object" ). The workaround is to use text mode, which I assume means not using protocol 2. After that, you can reload them in text mode, and then dump them using protocol 2. This is not so bad since you only do it when you were going to dump objects to file anyway, so it really only takes 3x as long on those occassions. The metaclass adaptation is still incredibly useful because it avoids having to do pickle dump- loads when you wouldn't otherwise have had to (approaching an infinite speedup in those cases, thanks Ziga! :-). Another caveat is that pickle dumping doesn't work if there is a pointer to a global function (that changes) that is a member of an instance of a class derived from AutoLoader. The error message has subtext: "it's not the same object ". That doesn't seem so bad to me, since you don't have to do that type of thing (function pointers) so much now that you can use classes! The best solution would be to make pickle protocol 2 have the same behavior as the text protocol (i.e. actually work in this case). Regarding the function pointers, anybody (Ziga :-) know why it is that pickle chokes so hard on this? Is there some adaptation of the metaclass or a less beautiful hack that could fix it? Thanks to those readers following me down the rabbit hole. Ziga's metaclass adaptation has saved Python in my mind, and these nits seem to be worth discussing. - Andrew Felch From gandalf at designaproduct.biz Tue Feb 13 14:49:10 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 13 Feb 2007 20:49:10 +0100 Subject: _ssl.pyd is buggy? In-Reply-To: References: <45D1F804.8050609@designaproduct.biz> Message-ID: <45D21636.1080903@designaproduct.biz> > Services usually run under the LOCAL_SERVICE account, which is rather > limited on what it is allowed to do (It has no access to network shares, > by example). Perhaps this is afecting your program. > I'm sorry, it is not. My service only uses the standard output, writes into different files and uses the http and https protocol. It does not use microsoft networking, only TCP/IP. It is actually a spider that downloads information from some web sites. The most strange thing is that the main thread is enclosed in a try - except statement, and it should log all exceptions into a file. The file is even not created, and I see no way to debug it. Can a python win32 service program be debugged? Thanks, Laszlo From python at gakman.com Fri Feb 9 10:19:29 2007 From: python at gakman.com (Gerald Kaszuba) Date: Sat, 10 Feb 2007 02:19:29 +1100 Subject: pycallgraph 0.1.0 In-Reply-To: References: Message-ID: <108b15f0702090719i170c76b9jd17770b4afb53a25@mail.gmail.com> On 2/10/07, Stef Mientki wrote: > ... but isn't "__main__." non-information ? Good point -- I'll consider removing it in the next version. Gerald From python at hope.cz Wed Feb 7 15:53:36 2007 From: python at hope.cz (Johny) Date: 7 Feb 2007 12:53:36 -0800 Subject: string.find for case insensitive search Message-ID: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Is there a good way how to use string.find function to find a substring if I need to you case insensitive substring? Thanks for reply LL From mail at timgolden.me.uk Wed Feb 14 11:31:40 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 14 Feb 2007 16:31:40 +0000 Subject: How to ping and shutdown a remote computer? In-Reply-To: <1171469222.163242.157040@q2g2000cwa.googlegroups.com> References: <1171469222.163242.157040@q2g2000cwa.googlegroups.com> Message-ID: <45D3396C.1070209@timgolden.me.uk> joja15 at gmail.com wrote: > Here is my current setup: > > [... BSD ...] > - Windows XP machine with folder share (What packet is sent over the > network to remotely shutdown a Windows XP machine?) > > My hope is to have a script then when you start it will list all your > remote computers/servers and show if they are currently on/off. Then > you can select a server and turn it off if it is on or turn it on if > it is off. Couple of bits of info, speaking only about Windows. First, I'd be quite worried if someone could send me a packet (maliciously or otherwise) which simply shut my machine down. Is this possible? Second, machines -- or networks -- may be configured to reject or swallow pings so the lack of a ping may not indicate vitality. Since you specify that the machine has a folder share, that means it's running SMB/NMB/whatever it's called across a few well-known ports, including 135 and 137-139 and 445. So you could attempt a socket connection to one of those: import socket s = socket.socket () s.settimeout (0.25) try: s.connect (("192.168.100.84", 135)) except socket.error: print "not alive" else: print "alive" To shut it down, someone has already suggested the shutdown command, although I think you'd have to specify the -m param to pass the remote machine name. Alternatively, you could use WMI (which inadvertently provides a means of determining vitality): http://timgolden.me.uk/python/wmi_cookbook.html#reboot_remote_machine (adapted a bit, but you get the idea) TJG From http Thu Feb 22 13:06:13 2007 From: http (Paul Rubin) Date: 22 Feb 2007 10:06:13 -0800 Subject: when will python 2.5 take in mainstream? References: <7xtzy0wp83.fsf@ruckus.brouhaha.com> <45DDD9E1.6010809@v.loewis.de> Message-ID: <7xmz36nk2y.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > I haven't heard of other languages that seriously try to do that, > > though maybe some do. > Languages typically achieve this by specifying an ABI (in addition > to the API), and then sticking to that. Oh yes, at that level, it's reasonable and desirable. From adminsec at ejercito.mil.co Sat Feb 17 17:30:51 2007 From: adminsec at ejercito.mil.co (Correo Ejercito Nacional de Colombia) Date: Sat, 17 Feb 2007 17:30:51 -0500 Subject: Mensaje Eliminado por contener virus Message-ID: Este es un aviso del servicio de ANTIVIRUS DEL EJERCITO NACIONAL DE COLOMBIA, informando que el mensaje (e-mail) adjunto, fue eliminado por contener algun clase de virus. Cualquier inquietud por favor contactar el ?REA DE SEGURIDAD INFORMATICA DEL EJERCITO. Email: adminsec at ejercito.mil.co -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: RETURNED MAIL: DATA FORMAT ERROR Date: Sat, 17 Feb 2007 17:28:58 -0500 Size: 1987 URL: From steve at REMOVE.THIS.cybersource.com.au Tue Feb 27 09:58:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Feb 2007 01:58:38 +1100 Subject: Lists: Converting Double to Single References: <%6QEh.6362$_73.1862@newsread2.news.pas.earthlink.net> Message-ID: On Tue, 27 Feb 2007 10:06:29 +0000, Duncan Booth wrote: > Adding up a long list of values > and then dividing by the number of values is the classic computer > science example of how to get an inaccurate answer from a floating point > calculation. I'm not entirely ignorant when it comes to computational mathematics, but I must admit this is a new one to me. If the values vary greatly in magnitude, you probably want to add them from smallest to biggest; other than that, how else can you calculate the mean? The only alternative I thought of was to divide each value by the count before summing, but that would be horribly inaccurate. Or would it? >>> def mean1(*args): ... return sum(args)/len(args) ... >>> def mean2(*args): ... n = len(args) ... return sum([x/n for x in args]) ... >>> L = range(25, 597) # 572 values >>> L = [x/3.3 for x in L] >>> >>> mean1(*L) 94.090909090909108 >>> mean2(*L) 94.090909090909108 The first calculation has 571 additions and one division; the second calculation has 571 additions and 572 divisions, but they both give the same result to 15 decimal places. -- Steven. From google at mrabarnett.plus.com Thu Feb 15 20:25:12 2007 From: google at mrabarnett.plus.com (MRAB) Date: 15 Feb 2007 17:25:12 -0800 Subject: builtin set literal In-Reply-To: References: Message-ID: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> On Feb 15, 4:12 pm, Sch?le Daniel wrote: > [...] > > >>> In Python 3.0, this looks like:: > > >>> s = {1,2,3} > > >> jepp, that looks not bad .. as in a mathe book. > >> the only disadvantage I see, that one may confuse it with a dict. > > > Perhaps with a very cursory inspection. But the lack of any ':' > > characters is a pretty quick clue-in. > > there is one a bigger disadvantage though > {} empty set clashes with empty dict {} > set() still must be used to generate the empty set > or a hack like > s = {None}.clear() > > I think something like {-} as the substitution for empty set > will seem bit to perlish for most of us? :) > What about "{,}"? For consistency "(,)" and "[,]" might also have to be permissible, and maybe even "{:}" for an empty dict. Or perhaps not. From donmorrison at gmail.com Mon Feb 5 17:16:02 2007 From: donmorrison at gmail.com (Don Morrison) Date: Mon, 5 Feb 2007 14:16:02 -0800 Subject: lambda functions ? In-Reply-To: References: Message-ID: Maybe you would like a generator: >>> def f(n): ... while True: ... n += 1 ... yield n ... >>> a = f(5) >>> >>> a.next() 6 >>> a.next() 7 >>> a.next() 8 >>> a.next() 9 >>> On 2/5/07, Maxim Veksler wrote: > Hello, > I'm new on this list and in python. > > It seems python has some interesting concept of "ad hoc" function > which I'm trying to understand without much success. > > Take the following code for example: > > """ > >>> def make_incrementor(n): > ... return lambda x: x + n > ... > >>> f = make_incrementor(42) > >>> f(0) > 42 > >>> f(1) > 43 > """ > > I really don't understand whats going on here. > On the first instantiating of the object "f" where does "x" gets it's > value? Or is it evaluated as 0? ie "x: 0 + 42" > > And what is the "f" object? An integer? a pointer? an Object? > I'm coming from the C world... > > Could some please try (if even possible) to implement the above code > without using "lambda" I believe it would help me grasp this a bit > faster then. > > Thank you, > Maxim. > > > -- > Cheers, > Maxim Veksler > > "Free as in Freedom" - Do u GNU ? > -- > http://mail.python.org/mailman/listinfo/python-list > From boyandin at gmail.com Fri Feb 9 03:10:06 2007 From: boyandin at gmail.com (Sagari) Date: 9 Feb 2007 00:10:06 -0800 Subject: Referencing vars, methods and classes by name In-Reply-To: <7xbqk52gt8.fsf@ruckus.brouhaha.com> References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> <7xbqk52gt8.fsf@ruckus.brouhaha.com> Message-ID: <1171008606.012968.106680@p10g2000cwp.googlegroups.com> > For your other examples there are gross hacks using the dictionaries > that represent the local and global symbol tables, so we translate > your examples fairly directly, but stylistically we'd usually stay > away from that kind of thing. Thanks to everyone for all the comments. I am migrating from PHP to Python and I am looking for the means to port a controller code that would, roughly speaking, call a certain method of a certain class (both class and method names taken from user input). Putting aside input verification (by the moment I perform the call input must have been verified), what would be the recommended way of doing the trick? Thanks! All the best, Konstantin From __peter__ at web.de Thu Feb 15 11:56:08 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 15 Feb 2007 17:56:08 +0100 Subject: filecmp.cmp() cache References: <1171554885.517477.316470@s48g2000cws.googlegroups.com> Message-ID: Mattias Br?ndstr?m wrote: > I have a question about filecmp.cmp(). The short code snippet blow > does not bahave as I would expect: > > import filecmp > > f0 = "foo.dat" > f1 = "bar.dat" > > f = open(f0, "w") > f.write("1:2") > f.close() > > f = open(f1, "w") > f.write("1:2") > f.close() > > print "cmp 1: " + str(filecmp.cmp(f0, f1, False)) > > f = open(f1, "w") > f.write("2:3") > f.close() > > print "cmp 2: " + str(filecmp.cmp(f0, f1, False)) > > I would expect the second comparison to return False instead of True. > Looking at the docs for filecmp.cmp() I found the following: "This > function uses a cache for past comparisons and the results, with a > cache invalidation mechanism relying on stale signatures.". I guess > that this is the reason for my test case failing. > > Is there someone here that can tell me how I should invalidate this > cache? If that is not possible, what workaround could I use? I guess > that I can write my own file comparison function, but I would not like > to have to do that since we have filecmp. > > Any ideas? You can clear the cache with filecmp._cache = {} as a glance into the filecmp module would have shown. If you don't want to use the cache at all (untested): class NoCache: def __setitem__(self, key, value): pass def get(self, key): return None filecmp._cache = NoCache() Alternatively an update to Python 2.5 might work as the type of os.stat(filename).st_mtime was changed from int to float and now offers subsecond resolution. Peter From gagsl-py at yahoo.com.ar Mon Feb 5 18:47:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:47:17 -0300 Subject: .pth configuration method not working References: <1170543783.843044.22670@k78g2000cwa.googlegroups.com> Message-ID: En Sat, 03 Feb 2007 20:03:03 -0300, Mark escribi?: > Sys.path doesn't recognize any directories that I add using the .pth > method. I'm running Windows XP if that helps diagnose the problem. Using Python 2.4.3 on WinXP too. My Python is on C:\apps\Python. Works fine for me: C:\APPS\PYTHON>python -c "import sys; print sys.path" ['', 'D:\\WINDOWS.0\\system32\\python24.zip', 'C:\\APPS\\PYTHON', 'C:\\APPS\\PYT HON\\DLLs', 'C:\\APPS\\PYTHON\\lib', 'C:\\APPS\\PYTHON\\lib\\plat-win', 'C:\\APP S\\PYTHON\\lib\\lib-tk', 'C:\\APPS\\PYTHON\\lib\\site-packages', 'C:\\APPS\\PYTH ON\\lib\\site-packages\\PIL', 'C:\\APPS\\PYTHON\\lib\\site-packages\\win32', 'C: \\APPS\\PYTHON\\lib\\site-packages\\win32\\lib', 'C:\\APPS\\PYTHON\\lib\\site-pa ckages\\Pythonwin', 'C:\\APPS\\PYTHON\\lib\\site-packages\\wx-2.6-msw-ansi'] C:\APPS\PYTHON>echo c:\apps\Python\MyModules > MyPaths.pth C:\APPS\PYTHON>type MyPaths.pth c:\apps\python\MyModules C:\APPS\PYTHON>python -c "import sys; print sys.path" ['', 'D:\\WINDOWS.0\\system32\\python24.zip', 'C:\\APPS\\PYTHON', 'C:\\APPS\\PYT HON\\DLLs', 'C:\\APPS\\PYTHON\\lib', 'C:\\APPS\\PYTHON\\lib\\plat-win', 'C:\\APP S\\PYTHON\\lib\\lib-tk', 'c:\\apps\\Python\\MyModules', 'C:\\APPS\\PYTHON\\lib\\ site-packages', 'C:\\APPS\\PYTHON\\lib\\site-packages\\PIL', 'C:\\APPS\\PYTHON\\ lib\\site-packages\\win32', 'C:\\APPS\\PYTHON\\lib\\site-packages\\win32\\lib', 'C:\\APPS\\PYTHON\\lib\\site-packages\\Pythonwin', 'C:\\APPS\\PYTHON\\lib\\site- packages\\wx-2.6-msw-ansi'] -- Gabriel Genellina From http Thu Feb 1 21:46:33 2007 From: http (Paul Rubin) Date: 01 Feb 2007 18:46:33 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> Message-ID: <7x64alp986.fsf@ruckus.brouhaha.com> Ben Finney writes: > > Python still isn't ready for prime time in the web hosting world. > That doesn't follow. It's just as valid to say that the web hosting > providers (that you've interacted with so far) aren't ready to support > the Python functionality you want. I'd say the functionality that John wants is the same that pretty much everyone wants, and it's much easier to get for other languages than for Python. From S.Mientki-nospam at mailbox.kun.nl Sat Feb 17 19:12:07 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 18 Feb 2007 01:12:07 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: <53b70$45d799c3$d443bb3a$30116@news.speedlinq.nl> > I would love to see: > - a comparison between wx and gtk (QT doesn't have a very inviting > license ;-) I just found this: http://www.wxwidgets.org/wiki/index.php/WxWidgets_Compared_To_Other_Toolkits From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Feb 16 16:48:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 16 Feb 2007 22:48:41 +0100 Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> Message-ID: <53mn5pF1s9fcmU1@mid.individual.net> Stef Mientki wrote: > Although the GUI of Python is not as good as VB, What is the GUI of a language? Regards, Bj?rn -- BOFH excuse #334: 50% of the manual is in .pdf readme files From deets at nospam.web.de Thu Feb 22 12:40:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 18:40:59 +0100 Subject: Possible to set cpython heap size? References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> Message-ID: <5462tbF1vfhfrU1@mid.uni-berlin.de> Andy Watson wrote: > I have an application that scans and processes a bunch of text files. > The content I'm pulling out and holding in memory is at least 200MB. > > I'd love to be able to tell the CPython virtual machine that I need a > heap of, say 300MB up front rather than have it grow as needed. I've > had a scan through the archives of comp.lang.python and the python > docs but cannot find a way to do this. Is this possible to configure > the PVM this way? Why do you want that? And no, it is not possible. And to be honest: I have no idea why e.g. the JVM allows for this. Diez From seandavi at gmail.com Wed Feb 7 08:50:53 2007 From: seandavi at gmail.com (Sean Davis) Date: 7 Feb 2007 05:50:53 -0800 Subject: Graphs, bar charts, etc In-Reply-To: <45c87a32@griseus.its.uu.se> References: <45c87a32@griseus.its.uu.se> Message-ID: <1170856253.744121.213750@k78g2000cwa.googlegroups.com> On Feb 6, 7:57 am, Jan Danielsson wrote: > Hello all, > > I have some data in a postgresql table which I view through a web > interface (the web interface is written in python -- using mod_python > under apache 2.2). Now I would like to represent this data as graphs, > bar charts, etc. > > I know about matplotlib, and it seemed like exactly what I was > looking for. I tried importing it in my script, but it gave me some > error about a home directory not being writable. I'm not sure I like the > idea of it require to be able to write somewhere. Am I using it wrong? > > Is there something else I can use which can produce graphs easily? > > -- > Kind regards, > Jan Danielsson You might want to look at RPy (http://rpy.sourceforge.net), an interface to R (statistical programming environment). Sean From buzzard at urubu.freeserve.co.uk Thu Feb 22 20:49:53 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 23 Feb 2007 01:49:53 +0000 Subject: What is the best queue implemetation in Python? In-Reply-To: References: Message-ID: <45de4e9e.0@entanet> John wrote: > I want to write a code for Breadth First Traveral for Graph, which needs a > queue to implement. > > I wonder that for such a powerful language as Python, whether there is a > better and simpler implementation for a traditional FIFO queue? > For a BFS I coded up a while back iterating over a list of nodes (and appending nodes to the list as dictated by the algorithm) did the job. Duncan From garrickp at gmail.com Wed Feb 21 17:06:36 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 21 Feb 2007 14:06:36 -0800 Subject: Creating a daemon process in Python In-Reply-To: References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Message-ID: <1172095596.050555.225750@j27g2000cwj.googlegroups.com> On Feb 21, 9:33 am, Eirikur Hallgrimsson wrote: > Sakagami Hiroki wrote: > > What is the easiest way to create a daemon process in Python? I've found it even easier to use the built in threading modules: import time t1 = time.time() print "t_poc.py called at", t1 import threading def im_a_thread(): time.sleep(10) print "This is your thread speaking at", time.time() thread = threading.Thread(target=im_a_thread) thread.setDaemon(True) thread.start() t2 = time.time() print "Time elapsed in main thread:", t2 - t1 Of course, your mileage may vary. From guettli.usenet at thomas-guettler.de Thu Feb 8 10:36:38 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 8 Feb 2007 15:36:38 GMT Subject: python linux distro References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: <530uc6F1qihfuU1@mid.individual.net> azrael wrote: > Hy guys > > last night i was lying in my bed and thinking about something. is > there any linux distro that is primary oriented to python. you know > what i mean. no need for php, java, or something like this. pure > python and containig all the funky modules like scipy, numpy, > boaconstructor (wx of course). something like the python enthought > edition, but all this on a distro included. maybe psql but persistant > predered, zope of course. everything a developer is ever going to > need. On debian base distributions you can create a task. A task list all packages you need. You could make a task all-python-stuff. But I don't think many people will use it. I use Python daily, but at the moment I never use Zope, scipy or twisted. Ubuntu is a very python friendly environment. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From skpeterson at nospam.please.ucdavis.edu Mon Feb 12 00:24:54 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 21:24:54 -0800 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: James Stroud on Sun, 11 Feb 2007 16:53:16 -0800 didst step forth and proclaim thus: > agent-s wrote: > > Basically I'm programming a board game and I have to use a list of > > lists to represent the board (a list of 8 lists with 8 elements each). > > I have to search the adjacent cells for existing pieces and I was > > wondering how I would go about doing this efficiently. Thanks > > > > This isn't very clear. What do you mean by "I have to search the > adjacent cells for existing pieces"? > > If piece is 1 and empty is 0 and piece is at ary[row][col]: > > import operator > srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)] > is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]]) Wow, maybe it's just me (I'm a pretty bad programmer) but this is where list comprehensions begin to look unreadable to me. Here's a C-like way to do it, (warning, untested in python): for i in range(8): for j in range(8): for offset_i in range(-1,2): for offset_j in range(-1, 2): row = i + offset_i col = j + offset_j if (row < 0 or row > 7) or (col < 0 or col > 8) \ or ((row,col) == (i,j)): continue # else do something with board[row][col] I realize this is gross and un-Pythonic and does the same thing the above code does, but it's probably the way I'd choose to do it :). Then again, I've been negatively influenced by doing a game of life in C a few months back. -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From zefirek at Speacock.Pau.Apoznan.Mpl Tue Feb 20 03:34:52 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Tue, 20 Feb 2007 09:34:52 +0100 Subject: builtin set literal In-Reply-To: <7xd54a6jof.fsf@ruckus.brouhaha.com> References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <7xd54a6jof.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > There's even a sentiment in some pythonistas to get rid of the [] and {} > notations for lists and dicts, using list((1,2,3)) and dict((1,2),(3,4)) > for [1,2,3] and {1:2, 3:4} respectively. Wow. This makes Python twice more LISPy, than <1, 2, 3> and {-} make it C-ish and Perlish. Frop Python-zen: Simple is better than complex. Flat is better than nested. Sets are good. Sets are fun. Sets are pythonish (the programmer codes the logical side of a data structure, bothering less 'bout the technical). I think, they deserve their literal notation. zefciu From hayes.tyler at gmail.com Wed Feb 28 00:15:55 2007 From: hayes.tyler at gmail.com (Tyler) Date: 27 Feb 2007 21:15:55 -0800 Subject: f2py and Fortran90 gfortran_filename error Message-ID: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> Hello All: Since my last post I have attempted to use the f2py program which comes with numpy. I am able to create a .so file fine; however, when I import it into Python, I receive the following message: >>> import matsolve2 Traceback (most recent call last): File "", line 1, in ? ImportError: ./matsolve2.so: undefined symbol: _gfortran_filename The steps I used to create the matsolve2.so file are as follows: (1) Created a Fortran90 program matsolve.f90 Note: The program compiles fine and prints the proper output for the simple matrix specified. I have also attached below the file matsolve.f90 if it helps at all. (2) f2py matsolve.f90 -m matsolve2 -h matsolve2.pyf (3) f2py -c matsolve2.pyf --f90exec=/usr/bin/gfortran matsolve.f90 Note: I had to specify the f90 path as f2py did not automatically find it. Any suggestions are greatly appreciated. Cheers, t. ! MATSOLVE.f90 ! ! Start main program PROGRAM MATSOLVE IMPLICIT NONE INTEGER,PARAMETER :: n=3 INTEGER :: i,j REAL,DIMENSION(n) :: x,b REAL,DIMENSION(n,n) :: A,L,U ! Initialize the vectors and matrices with a test case from text ! Using the one given in Appendix A from Thompson. ! Known vector "b" b(1) = 12. b(2) = 11. b(3) = 2. ! Known coefficient matrix "A", and initialize L and U DO i=1,n DO j=1,n L(i,j) = 0. U(i,j) = 0. END DO END DO A(1,1) = 3. A(1,2) = -1. A(1,3) = 2. A(2,1) = 1. A(2,2) = 2. A(2,3) = 3. A(3,1) = 2. A(3,2) = -2. A(3,3) = -1. ! Call subroutine to create L and U matrices from A CALL lumake(L,U,A,n) ! Print results PRINT *, '-----------------------' DO i=1,n DO j=1,n PRINT *, i, j, A(i,j), L(i,j), U(i,j) END DO END DO PRINT *, '-----------------------' ! Call subroutine to solve for "x" using L and U CALL lusolve(x,L,U,b,n) ! Print results PRINT *, '-----------------------' DO i=1,n PRINT *, i, x(i) END DO PRINT *, '-----------------------' END PROGRAM MATSOLVE ! Create subroutine to make L and U matrices SUBROUTINE lumake(LL,UU,AA,n1) IMPLICIT NONE INTEGER,PARAMETER :: n=3 INTEGER :: i,j,k REAL :: LUSUM INTEGER,INTENT(IN) :: n1 REAL,DIMENSION(n,n),INTENT(IN) :: AA REAL,DIMENSION(n,n),INTENT(OUT) :: LL,UU ! We first note that the diagonal in our UPPER matrix is ! going to be UU(j,j) = 1.0, this allows us to initialize ! the first set of expressions UU(1,1) = 1. ! Find first column of LL DO i = 1,n1 LL(i,1) = AA(i,1)/UU(1,1) END DO ! Now find first row of UU DO j = 2,n1 UU(1,j) = AA(1,j)/LL(1,1) END DO ! Now find middle LL elements DO j = 2,n1 DO i = j,n1 LUSUM = 0. DO k = 1,j-1 LUSUM = LUSUM + LL(i,k)*UU(k,j) END DO LL(i,j) = AA(i,j) - LUSUM END DO ! Set Diagonal UU UU(j,j) = 1. ! Now find middle UU elements DO i = j+1,n1 LUSUM = 0. DO k = 1,j-1 LUSUM = LUSUM + LL(j,k)*UU(k,i) END DO UU(j,i) = (AA(j,i) - LUSUM)/LL(j,j) END DO END DO END SUBROUTINE lumake ! Make subroutine to solve for x SUBROUTINE lusolve(xx,L2,U2,bb,n2) IMPLICIT NONE INTEGER,PARAMETER :: n=3 INTEGER :: i,j,k REAL :: LYSUM,UXSUM REAL,DIMENSION(n):: y INTEGER,INTENT(IN) :: n2 REAL,DIMENSION(n),INTENT(IN) :: bb REAL,DIMENSION(n,n),INTENT(IN) :: L2,U2 REAL,DIMENSION(n),INTENT(OUT) :: xx ! Initialize DO i=1,n2 y(i) = 0. xx(i) = 0. END DO ! Solve L.y = b y(1) = bb(1)/L2(1,1) DO i = 2,n2 LYSUM = 0. DO k = 1,i-1 LYSUM = LYSUM + L2(i,k)*y(k) END DO y(i) = (bb(i) - LYSUM)/L2(i,i) END DO ! Now do back subsitution for U.x = y xx(n2) = y(n2)/U2(n2,n2) DO j = n2-1,1,-1 UXSUM = 0. DO k = j+1,n2 UXSUM = UXSUM + U2(j,k)*xx(k) END DO xx(j) = y(j) - UXSUM END DO END SUBROUTINE lusolve From samuel.y.l.cheung at gmail.com Tue Feb 27 10:37:09 2007 From: samuel.y.l.cheung at gmail.com (samuel.y.l.cheung at gmail.com) Date: 27 Feb 2007 07:37:09 -0800 Subject: How to use cmp() function to compare 2 files? In-Reply-To: References: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> <1172550136.069527.103600@t69g2000cwt.googlegroups.com> <1172551987.182502.94000@p10g2000cwp.googlegroups.com> <1172553141.665287.65280@8g2000cwh.googlegroups.com> Message-ID: <1172590629.400500.192670@q2g2000cwa.googlegroups.com> On Feb 27, 12:07 am, Marc 'BlackJack' Rintsch wrote: > In <1172553141.665287.65... at 8g2000cwh.googlegroups.com>, ying... at gmail.com > wrote: > > > File "./scripts/regressionTest.py", line 30, in getSnapShot > > if (difflib.context_diff(f1.readlines(), f2.readlines()).len() == > > 0): > > # no difference > > else: > > # files are different > > AttributeError: 'generator' object has no attribute 'len' > > > Can you please help? > > The function returns a generator/iterator over the differences which has > no `len()` method. If you just want to know if two files are equal or not > use `filecmp.cmp()`. Read the docs about the `shallow` argument of that > function. > > Ciao, > Marc 'BlackJack' Rintsch Thanks. I use that before, it does not work for me, since it always return 1, regardless if the file content of 2 files are different or not. From grante at visi.com Wed Feb 21 19:12:21 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 22 Feb 2007 00:12:21 -0000 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <12tpnv5mjm9b100@corp.supernews.com> On 2007-02-21, Harlin Seritt wrote: > I would like to take a string like > 'supercalifragilisticexpialidocius' and write it to a file in > binary forms -- this way a user cannot read the string in case > they were try to open in something like ascii text editor. Why wouldn't they be able to read it? ASCII _is_ binary. > I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is > there any way to do this in Python? What you're describing as "this" doesn't seem to make any sense. -- Grant Edwards grante Yow! Kids, don't gross me at off... "Adventures with visi.com MENTAL HYGIENE" can be carried too FAR! From casevh at gmail.com Mon Feb 26 11:33:02 2007 From: casevh at gmail.com (casevh at gmail.com) Date: 26 Feb 2007 08:33:02 -0800 Subject: Python / Socket speed In-Reply-To: <1172502342.047416.280140@k78g2000cwa.googlegroups.com> References: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> <1172502342.047416.280140@k78g2000cwa.googlegroups.com> Message-ID: <1172507581.993376.61270@z35g2000cwz.googlegroups.com> On Feb 26, 7:05 am, "Paul Boddie" wrote: > On 26 Feb, 15:54, "m... at infoserv.dk" wrote: > > > Seems like sockets are about 6 times faster on OpenSUSE than on > > Windows XP in Python. > > >http://pyfanatic.blogspot.com/2007/02/socket-performance.html > > > Is this related to Python or the OS? > >From the output: > > TCP window size: 8.00 KByte (default) > > TCP window size: 49.4 KByte (default) > > I don't pretend to be an expert on TCP/IP, but might the window size > have something to do with it? > > Paul Tuning the TCP window size will make a big difference with Windows XP performance. I'm more curious about the original script. Either the test was against the loopback address, or he has a very impressive netork to sustain 1.8Gbit/s. casevh From pyscripter at gmail.com Tue Feb 13 05:27:24 2007 From: pyscripter at gmail.com (PyScripter) Date: 13 Feb 2007 02:27:24 -0800 Subject: favourite editor In-Reply-To: References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> <45D08DAB.6080908@websafe.com> <1171307483.481407.167480@a75g2000cwd.googlegroups.com> Message-ID: <1171362443.953104.273260@a34g2000cwb.googlegroups.com> A beta version of PyScripter with remote debugging is actually out. See http://pyscripter.googlepages.com/ and http:// pyscripter.googlepages.com/remotepythonengines for details. ?/? Stef Mientki ??????: > azrael wrote: > > I expirienced some big craches. tra running some aplication vith using > > Vpython. when you close the vpython window, pyscripter also crashes. > > sometimes im writing some code and suddenly get about 300 error > > messages without running anything. I like pyscripter, but sometimes it > > drives me crazy > did you read the help file: > if you use a GUI platform (e.g. tknter, wxpython etc.). As the help file says under the topic > "known issues" you should not run or debug such scripts internally. Instead use the > Run, External Run command. > > and form the author of PyScripter jan-2007: > I hope that such problems will be resolved when I release the remote debugging facility, which > should happen quite soon. > > cheers, > Stef Mientki From ahmerhussain at gmail.com Mon Feb 19 13:41:41 2007 From: ahmerhussain at gmail.com (Ahmer) Date: 19 Feb 2007 10:41:41 -0800 Subject: PyDev on Mac In-Reply-To: <53qlrtF1tm3brU1@mid.uni-berlin.de> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> Message-ID: <1171910501.783846.196300@v45g2000cwv.googlegroups.com> On Feb 18, 4:50 am, "Diez B. Roggisch" wrote: > Ahmer schrieb: > > > I've been trying to set up PyDev on my new MacBook Pro, but i have not > > had an success. > > > Could you please help! > > Just wait until my crystal ball comes back from the cleaners, and I will > start looking at your problem. > > As you can lay back and do nothing while that happens, I suggest you > take this highly entertaining read: > > http://www.catb.org/~esr/faqs/smart-questions.html > > Diez The error I am getting is: Check your error log for more details. More info can also be found at the bug report: http://sourceforge.net/tracker/index.php?func=detail&aid=1523582&group_id=85796&atid=577329 I am trying to use Jython since I am mainly a Java programmer. The bug report is not very helpful.... From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 09:32:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Feb 2007 01:32:21 +1100 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: On Fri, 16 Feb 2007 06:07:42 -0600, Edward K Ream wrote: >> I'm pretty sure you're mistaken. Python 3 will be the release that breaks >> code. Hopefully very little, but there almost certainly will be some. > > Pep 3105 breaks a *lot* of code, despite the bland assertion that most > production programs don't use print. > > Presumably, Guido wanted to improve print in such a way that *more* people > would use it. I don't think Guido cares about _how many_ people use print. I think he cares about making print better. If that leads to more people using it, that's a bonus. But your and my guesses about what Guido cares about aren't terribly important. > But the effect of the pep is that *less* people will be able > to use print, *regardless* of how backward compatible Python 3.x is > 'allowed' to be. I don't think that follows at all. print is only a problem if you expect your code to work under both Python 2.x and 3.x. I wouldn't imagine that many people are going to expect that: I know I don't. There are likely to be a whole lot of things which change, sometimes radically, from one to the other. They'll support one or the other, or fork the code, or in extreme cases take over maintenance of Python 2.x (it is open source, you can do that). If you want to "future-proof" your Python code, well, you can't fully because nobody yet knows all the things which will change. But you can start by not calling print directly. There are a number of alternatives, depending on what you're doing. Here's a simple function that does very close to what print currently does: def print_(*args, where=None, newline=True): if where is None: where = sys.stdout args = [str(arg) for arg in args] where.write(' '.join(args)) if newline: where.write('\n') -- Steven. From http Mon Feb 19 21:53:12 2007 From: http (Paul Rubin) Date: 19 Feb 2007 18:53:12 -0800 Subject: pylab, integral of sinc function References: <7xwt2d7g83.fsf@ruckus.brouhaha.com> Message-ID: <7x3b5135gn.fsf@ruckus.brouhaha.com> Sch?le Daniel writes: > > return dx * sum(map(func, arange(a,b,dx))) > yes, this should be faster :) You should actually use itertools.imap instead of map, to avoid creating a big intermediate list. However I was mainly concerned that the original version might be incorrect. I don't use pylab and don't know what happens if you pass the output of arange to a function. I only guessed at what arange does. From petercable at gmail.com Wed Feb 7 02:25:18 2007 From: petercable at gmail.com (petercable at gmail.com) Date: 6 Feb 2007 23:25:18 -0800 Subject: Running long script in the background In-Reply-To: <1170832410.532362.90160@p10g2000cwp.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170832410.532362.90160@p10g2000cwp.googlegroups.com> Message-ID: <1170833118.543624.246800@a34g2000cwb.googlegroups.com> On Feb 6, 11:13 pm, "peterca... at gmail.com" wrote: > output = os.popen(command, 'r', 1) OOPS... I imagine the ridiculous buffer size is unnecessary... I was trying to get it to work with the original for loop iterating on output, it should work fine without it. Pete From jura.grozni at gmail.com Mon Feb 12 14:11:23 2007 From: jura.grozni at gmail.com (azrael) Date: 12 Feb 2007 11:11:23 -0800 Subject: favourite editor In-Reply-To: <45D08DAB.6080908@websafe.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> <45D08DAB.6080908@websafe.com> Message-ID: <1171307483.481407.167480@a75g2000cwd.googlegroups.com> I expirienced some big craches. tra running some aplication vith using Vpython. when you close the vpython window, pyscripter also crashes. sometimes im writing some code and suddenly get about 300 error messages without running anything. I like pyscripter, but sometimes it drives me crazy On Feb 12, 4:54 pm, Larry Bates wrote: > azraelwrote: > > Since i'm new on this forum, and first time meeting a python comunity, > > i wanted to ask you for your python editors. > > > Im looking for some good python editor, with integrated run function, > > without having to set it up manualy like komodo. > > I found the pyscripter, and it has all i need, but it's unsatble. > > bloated. it crashes when i close an yplication window run by python > > from pyscripter. please. tell me a good one with buil in run (<-very > > important) and nice gui. if possible to suport projects, code > > highlighting, code completition, class browser, python comand line > > (>>>), traceback. > > > I didn't take a look on vista (and i dont want to), but i hope they > > improved the notepad. > > I use pyscripter as my primary editor and have NEVER had it crash > or do anything that could be considered "unstable". It has best > GUI of any Windows editor I've seen. I have to admit that I tend > to run my programs from a console window because it forces a clean > load of the program (no runtime environment "leftovers") and if > I'm doing wxPython or other GUI apps, they almost always interfere > in some way with the editors (same was true for ActiveState). Maybe > you could give that a try. > > -Larry From gagsl-py2 at yahoo.com.ar Wed Feb 28 21:39:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Feb 2007 23:39:09 -0300 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> <1172561344.290126.191530@h3g2000cwc.googlegroups.com> <3c5Fh.3664$Tg7.2156@trnddc03> Message-ID: En Wed, 28 Feb 2007 09:41:47 -0300, Alan Isaac escribi?: > However I will observe that > - entire languages are structured on the premise that dynamic > attribute creation can be hazardous That's why we have so many languages to choose from. What is highly important for someone is irrelevant for others. [PL/1 was destined to be The Programming Language...] If you actually dislike the concept of dynamic attribute creation, you're using the wrong language. > - debuggers watch out for dynamic attribute creation, which > tells us it is a common source of bugs Which debugger, please? Might be interesting. (As a debugging tool, not as a design technique). > - I sincerely doubt that anyone who has written more than > a couple scripts in Python has never accidentally created an > attribute dynamically while intending to assign to an existing > attribute. That *might* happen, but not so frequently as to fight against the dynamic nature of Python. > I know the response: write good unit tests. OK, but right now > I am writing code where this restriction will serve as a reasonable > error check, and the design I offered allows very easy removal > of the restriction in the future. Say, once I have written adequate > unit tests. If it suits your needs, fine! But you'll find that most Python programmers won't agree with your approach. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Tue Feb 13 18:46:04 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 14 Feb 2007 00:46:04 +0100 Subject: What does "del" actually do? In-Reply-To: <8bnzh.74754$qO4.52439@newssvr13.news.prodigy.net> References: <8bnzh.74754$qO4.52439@newssvr13.news.prodigy.net> Message-ID: <45d24667$0$25611$426a74cc@news.free.fr> John Nagle a ?crit : > The Python "reference manual" says, for "del", "Rather that spelling > it out in full details, here are some hints." That's not too helpful. > > In particular, when "del" is applied to a class object, what happens? > Are all the instance attributes deleted from the object? It would have been simpler to just test: >>> class Ghost(object): ... def __init__(self, name): ... self.name = name ... say = "whoo" ... def greetings(self): ... print "%s from %s %s" \ ... %(self.say, self.__class__.__name__, self.name) ... >>> g1 = Ghost("Albert") >>> g2 = Ghost("Ivan") >>> g1.greetings() whoo from Ghost Albert >>> del Ghost >>> g1.greetings() whoo from Ghost Albert >>> g1.__class__ >>> the del statement remove a name from the current namespace. period. It's also used for removing keys from dicts. > Is behavior > the same for both old and new classes? Should it be different ? > I'm trying to break cycles to fix some memory usage problems. GC and/or Weakrefs should do. From http Thu Feb 15 18:21:55 2007 From: http (Paul Rubin) Date: 15 Feb 2007 15:21:55 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> Message-ID: <7xfy97uhv0.fsf@ruckus.brouhaha.com> Donn Cave writes: > If t is a valid argument tuple for function f, then can t[1:] > also be a valid argument tuple for function f? > > For ordinary functions without special argument handling, no. > We know that without having to know anything about t, and not > much about f. This is characteristic of tuple applications. I'm not sure what you're saying. The current situation is if I say def f(*args): print args f (1,2,3,4,5,6,7) f receives a 7-element tuple, but if I say f (8, 9, 10) f receives a 3-element tuple. I'm asking whether f should receive a list instead. I think that is more in keeping with the notion of a tuple being like a structure datatype. How can there be a structure datatype with an unpredictable number of members? It might have come across as a different question-sorry for any confusion. From http Sat Feb 24 21:26:30 2007 From: http (Paul Rubin) Date: 24 Feb 2007 18:26:30 -0800 Subject: Referencing Items in a List of Tuples References: <1172370015.018827.296720@q2g2000cwa.googlegroups.com> Message-ID: <7xmz33geg9.fsf@ruckus.brouhaha.com> "Rune Strand" writes: > if you want numeric adressing, try: > for i in range(len(mainlist)): > if mainlist[i][0] == 'eco' etc. Preferable: for i,m in enumerate(mainlist): if m[0] == 'eco' etc. From randomgeek at cyberspace.net Mon Feb 26 16:31:30 2007 From: randomgeek at cyberspace.net (Dan Bensen) Date: Mon, 26 Feb 2007 15:31:30 -0600 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: Tech HR wrote: > easier to train a Java programmer or a Perler on Python than Lisp. Are your technical problems simple enough to be solved by Python trainees? -- Dan www.prairienet.org/~dsb From max at alcyone.com Wed Feb 21 00:17:51 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 20 Feb 2007 21:17:51 -0800 Subject: eval('000052') = 42? In-Reply-To: References: Message-ID: Astan Chee wrote: > I just tried to do > eval('00052') and it returned 42. > Is this a known bug in the eval function? Or have I missed the way eval > function works? String literals beginning with a 0 are in octal. Besides, using eval for such a narrow case is extremely unwise. Instead use int: >>> int('00052') 52 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis God grant me to contend with those that understand me. -- Thomas Fuller From __peter__ at web.de Sat Feb 3 05:35:22 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 11:35:22 +0100 Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" References: Message-ID: Gabriel Genellina wrote: > En Sat, 03 Feb 2007 06:12:33 -0300, Peter Otten <__peter__ at web.de> > escribi?: > >> John Nagle wrote: >> >>> How do I suppress "DeprecationWarning: Old style callback, use >>> cb_func(ok, >>> store) instead". A library is triggering this message, the library is >>> being fixed, but I need to make the message disappear from the output >>> of a >>> CGI program. >> >> import warnings >> warnings.filterwarnings("ignore", message="Old style callback, use >> cb_func(ok, store) instead") > > Or you can be more aggressive and filter out all DeprecationWarnings: > warnings.simplefilter("ignore",DeprecationWarning) > (same as using option -Wignore::DeprecationWarning on the python command > line) The latter might be interesting for a cgi. I didn't mention it because I didn't get it to work with my test case (importing sre) and Python's cgi server. Trying again, I found that you must not quote the -W argument. #!/usr/local/bin/python2.5 -Wignore:The sre module is deprecated, please import re. >From that follows that you can pass at most one commandline arg. If you are using #!/usr/bin/env python2.5 python2.5 will be that single argument and no options are possible at all. What might be the reasons for such a seemingly arbitrary limitation? Peter From Wendy.Tyrrell at Camden.gov.uk Wed Feb 14 11:07:38 2007 From: Wendy.Tyrrell at Camden.gov.uk (Tyrrell, Wendy) Date: Wed, 14 Feb 2007 16:07:38 -0000 Subject: how do "real" python programmers work? Message-ID: <0EC8A68FD54CDD4FB6B92EE7B713ED3601331455@SAN-THC-NODE02.lbcamden.net> _________________________ Wendy Tyrrell WRL Adviser Camden Education Business Partnership Children, Schools and Families London Borough of Camden The Medburn Centre 136 Chalton Street NW1 1RX Streetmap: http://www.streetmap.co.uk/streetmap.dll?G2M?X=529491&Y=183342&A=Y&Z=1 Phone: 020 7974 8249 Fax: 020 7383 0875 Mobile: 07815 502 024 e-mail: wendy.tyrrell at camden.gov.uk Website: www.camden.gov.uk **Volunteer for our Mentoring Programmes** ** Call or email me for details** This e-mail may contain information which is confidential, legally privileged and/or copyright protected. This e-mail is intended for the addressee only. If you receive this in error, please contact the sender and delete the material from your computer From rridge at caffeine.csclub.uwaterloo.ca Wed Feb 28 00:27:37 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 28 Feb 2007 00:27:37 -0500 Subject: Running Python scripts from BASH References: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> Message-ID: Ishpeck wrote: >': [Errno 22] Invalid argumentopen file 'foo.py The problem is that Python is using the standard Windows CRLF line endings, while Cygwin bash expects Unix LF-only line endings. Your script ends up trying run the script "foo.y\r" instead of "foo.y", and since CR is isn't allowed in Windows filename you get the "Invalid argument" error when Python tries to open the file. >Maybe this is a better question for a BASH-related group. The Cygwin list probably would've been the best. >How do I get around this? Don't mix Cygwin tools and native Windows tools. Either use the Cygwin version of Python or don't use Cygwin bash. Ross Ridge From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 11:17:29 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Feb 2007 03:17:29 +1100 Subject: why I don't like range/xrange References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: On Fri, 16 Feb 2007 07:30:15 -0800, stdazi wrote: > Hello! > > Many times I was suggested to use xrange and range instead of the > while constructs, and indeed, they are quite more elegant - but, after > calculating the overhead (and losen flexibility) when working with > range/xrange, and while loops, you get to the conclusion that it isn't > really worth using range/xrange loops. I prefer to _measure_ the overhead instead of guessing. import timeit whileloop = """i = 0 while i < N: i += 1 pass """ forloop = """for i in xrange(N): pass """ Now let's see how fast the loops are. >>> timeit.Timer(whileloop, "N = 10000").repeat(3, 1000) [3.5716907978057861, 3.5263650417327881, 3.5975079536437988] >>> timeit.Timer(forloop, "N = 10000").repeat(3, 1000) [1.3608510494232178, 1.341961145401001, 1.3180010318756104] Looks to me that a for loop using xrange is more than twice as fast as a while loop. The advantage is about the same for small N: >>> timeit.Timer(whileloop, "N = 100").repeat(3, 1000) [0.052264213562011719, 0.049374103546142578, 0.041945934295654297] >>> timeit.Timer(forloop, "N = 100").repeat(3, 1000) [0.012259006500244141, 0.013512134552001953, 0.015196800231933594] What makes you think that a while loop has less overhead? > I'd like to show some examples and I'll be glad if someone can suggest > some other fixes than while a loop :-) > > a) range overfllow : > > > for i in range(0, 1 << len(S)) : > ..... > OverflowError: range() result has too many items > > ok, so we fix this one with xrange ! By the way, you don't need to write range(0, N). You can just write range(N). Yes, you're correct, range(some_enormous_number) will fail if some_enormous_number is too big. > b) xrange long int overflow : > > for i in xrange(0, 1 << len(S)) : > ........ > OverflowError: long int too large to convert to int Are you really doing something at least 2147483647 times? I'm guessing that you would be better off rethinking your algorithm. > Next thing I miss is the flexibility as in C for loops : > > for (i = 0; some_function() /* or other condition */ ; i++) This would be written in Python as: i = 0 while some_function(): i += 1 A more flexible way would be to re-write some_function() as an iterator, then use it directly: for item in some_function(): # do something with item > or, > > for (i = 0 ; i < 10 ; i++) > i = 10; This would be written in Python as: for i in xrange(10): i = 10 > I don't think range/xrange sucks, but I really think there should be > some other constructs to improve the looping flexibility. Every loop can be turned into a while loop. If you have while, you don't _need_ anything else. But for elegance and ease of use, a small number of looping constructs is good. Python has: while condition: block else: # runs if while exits *without* hitting break statement block for item in any_sequence: block else: # runs if for exits *without* hitting break statement block Nice, clean syntax. any_sequence isn't limited to mere arithmetic sequences -- it can be any sequence of any objects. But if you need a C-style for loop, using integers, range/xrange([start, ] stop [, step]) is provided. -- Steven. From edreamleo at charter.net Thu Feb 15 17:32:36 2007 From: edreamleo at charter.net (Edward K Ream) Date: Thu, 15 Feb 2007 16:32:36 -0600 Subject: Pep 3105: the end of print? References: Message-ID: > You could offer up a patch for Python 2.6 so that you can do:: > from __future__ import print_function This would only work for Python 2.6. Developers might want to support Python 2.3 through 2.5 for awhile longer :-) > why can't you use ``file.write()`` instead of ``print``? Precisely my point: pep 3105 will force the elimination of the name 'print'. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From bignose+hates-spam at benfinney.id.au Tue Feb 27 17:10:00 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 09:10:00 +1100 Subject: import parent References: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> Message-ID: <877iu3z1zb.fsf@benfinney.id.au> Greg at bag.python.org, Hoover at bag.python.org writes: > How does one get access to the class that imported a module. For > example: foo imports bar -- how does bar access foo? If bar needs to know something specific from foo, then bar should expose an interface that asks explicitly for that information, so that foo can explicitly provide it. -- \ "Laurie got offended that I used the word 'puke.' But to me, | `\ that's what her dinner tasted like." -- Jack Handey | _o__) | Ben Finney From rodolfo.ueg at gmail.com Mon Feb 5 14:43:54 2007 From: rodolfo.ueg at gmail.com (Rodolfo S. Carvalho) Date: Mon, 5 Feb 2007 17:43:54 -0200 Subject: Python module question Message-ID: Hi folks I have a question for this mailing list. When I'm writing a class, I can rewrite the method __getattr__() to modify the object's method/attribute access behavior. My question is: can I code a method __getattr__() to change the behavior of the 'import' command? -- Rodolfo Carvalho Web Developer rodolfo.ueg at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From matt.waite at gmail.com Thu Feb 1 15:13:20 2007 From: matt.waite at gmail.com (Matt Waite) Date: 1 Feb 2007 12:13:20 -0800 Subject: Newbie question: replacing nulls in CSV with preceding value Message-ID: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> My first post, my first real python use, please be gentle: I have a CSV file, exported from Excel, that has blank records in it, and I need to fill them in with the values from the record just above it until it hits a non-blank value. Here's an example of the data, which is in a file called test2.csv: Zone,City,Event 1,Anytown,Event ,,Event1 ,,Event2 ,,Event44 2,Anothertown,Event3 ,,Event5 ,,Event7 What I need it to look like is: Zone,City,Event 1,Anytown,Event1 1,Anytown,Event2 1,Anytown,Event44 2,Anothertown,Event3 2,Anothertown,Event5 2,Anothertown,Event7 Pretty much everything I've tried has failed, and I've been searching for hours for something similar and haven't found anything. The best I've come up with --which is half baked and I don't even know if it works -- is this: import csv citynew='' reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb")) for row in reader: row['CITY'] == citynew else: citynew=row['CITY'] The logic here -- in this case trying to fill in the city information -- would seem to work, but I'm not sure. And I'm not sure how to write the results of this back to the file. Any help anyone can offer is greatly appreciated. I'm trying hard to learn, but have been frustrated by this problem. Matt Matthew Waite www.mattwaite.com From deets at nospam.web.de Thu Feb 22 13:19:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 19:19:46 +0100 Subject: Possible to set cpython heap size? References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <5462tbF1vfhfrU1@mid.uni-berlin.de> <1172166768.967422.225960@p10g2000cwp.googlegroups.com> Message-ID: <546562F1uqe64U1@mid.uni-berlin.de> Andy Watson wrote: > > Why do you want that? And no, it is not possible. And to be honest: > I have >> no idea why e.g. the JVM allows for this. > > The reason why is simply that I know roughly how much memory I'm going > to need, and cpython seems to be taking a fair amount of time > extending its heap as I read in content incrementally. I'm not an expert in python malloc schemes, I know that _some_ things are heavily optimized, but I'm not aware that it does some clever self-management of heap in the general case. Which would be complicated in the presence of arbitrary C extensions anyway. However, I'm having doubts that your observation is correct. A simple python -m timeit -n 1 -r 1 "range(50000000)" 1 loops, best of 1: 2.38 sec per loop will create a python-process of half a gig ram - for a split-second - and I don't consider 2.38 seconds a fair amount of time for heap allocation. When I used a 4 times larger argument, my machine began swapping. THEN things became ugly - but I don't see how preallocation will help there... Diez From gagsl-py at yahoo.com.ar Fri Feb 9 00:36:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Feb 2007 02:36:52 -0300 Subject: Dictionary Question In-Reply-To: <2adc542f0702081950h34d7030ckbc2745ef0d029de6@mail.gmail.co m> References: <2adc542f0702081832k2b917a86pede0f419d5ff7be4@mail.gmail.com> <2adc542f0702081950h34d7030ckbc2745ef0d029de6@mail.gmail.com> Message-ID: <20070209053707.36D3E1E4010@bag.python.org> At Friday 9/2/2007 00:50, you wrote: >Hey Gabriel, Please keep posting on the list - you'll reach a whole lot of people there... >Thanks again for the help....... but im still having some issues..... >For some reason the "domsrch.search(key)" is pointing to a memory >reference....... so when I do this: >[...] > print domsrch.search(key) > if domain == domsrch.search(key): > utp.write(key + '\n') ><_sre.SRE_Match object at 0xb7f7b0e0> This is the standard str()/repr() of an object that doesn't care to provide it's own __str__/__repr__ method. Let's look at the docs. From http://docs.python.org/lib/re-objects.html we see that the search() method returns a MatchObject. And what's that...? See http://docs.python.org/lib/match-objects.html , you might be interested in using group(1) But doing the search that way, means that you must traverse the dict many times, once per domain searched. Doesn't look so good. Two approaches: 1) Build a specific re that matches exactly all the domains you want (and not others). This way you don't even need to use any method in the returned MatchObject: simply, if it's not None, there was a match. Something like this: domains = ["yahoo.com", "google.com", "gmail.com"] domainsre = "|".join(["(%s)" % re.escape("@"+domain)]) # that means: put an @ in front of each domain, make it a group, and join all groups with | # (\@yahoo\.com)|(\@google\.com)|(\@gmail\.com) domsrch = re.compile(domainsre, re.IGNORECASE) for key in d1: if domsrch.search(key): print key 2) Forget about regular expressions; you already know they're email addresses, just split on the @ and check the right side against the desired domains: domains = ["yahoo.com", "google.com", "gmail.com"] domainsSet = set(domains) for key in d1: name, domain = key.split("@",1) if domain.lower() in domainsSet: print key -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From redvasily at gmail.com Sun Feb 11 23:14:24 2007 From: redvasily at gmail.com (Vasily Sulatskov) Date: 11 Feb 2007 20:14:24 -0800 Subject: Help with Optimization of Python software: real-time audio controller In-Reply-To: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> References: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> Message-ID: <1171253664.762124.85220@j27g2000cwj.googlegroups.com> Perhaps boosting priorities for time critical threads will help. I don't know about MacOS but for Win32 something like that helps: thread = win32api.GetCurrentThread() win32process.SetThreadPriority(thread, win32process.THREAD_PRIORITY_TIME_CRITICAL) current_process = win32process.GetCurrentProcess() win32process.SetPriorityClass(current_process, win32process.REALTIME_PRIORITY_CLASS) From steve at holdenweb.com Tue Feb 20 13:11:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 20 Feb 2007 13:11:22 -0500 Subject: Regd. converting seconds to hh:mm:ss format In-Reply-To: <200702201800.l1KI0j8h024251@nsa.veriwave.com> References: <7x3b50d8ri.fsf@ruckus.brouhaha.com> <200702201800.l1KI0j8h024251@nsa.veriwave.com> Message-ID: <45DB39CA.8050505@holdenweb.com> Vishal Bhargava wrote: > Is there an inbuilt library in Python which you can use to convert time in > seconds to hh:mm:ss format? > Thanks, > Vishal > Please don't ask a question by editing a reply to an existing thread: your question is now filed on many people's computers under "How to test if one dict us a subset of another". Look at the strftime() function in the time module. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From edreamleo at charter.net Fri Feb 16 07:25:10 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 06:25:10 -0600 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: > Is that what you intend to say? I intended to say what I did say: "Python releases have generally been backwards compatible with previous releases, with a few minor exceptions." Imo, this is compatible with what you are saying. > So long as it's done in a well-documented way, with a change in major > version number, it's a reasonable way (probably the *only* reasonable way) > to remove particular kinds of cruft from any application. Agreed. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From archaegeo at gmail.com Sat Feb 10 09:47:11 2007 From: archaegeo at gmail.com (archaegeo at gmail.com) Date: 10 Feb 2007 06:47:11 -0800 Subject: Can't import Stackless in Pythonwin In-Reply-To: References: <1171039856.077320.163610@s48g2000cws.googlegroups.com> Message-ID: <1171118831.573543.231200@m58g2000cwm.googlegroups.com> On Feb 9, 2:06 pm, "Gabriel Genellina" wrote: > En Fri, 09 Feb 2007 13:50:56 -0300, escribi?: > > > I am getting started in Python, and I have looked on both the > > stackless page and python.org and cannot find the answer to what I > > think is a simple problem. > > > If I start the python command line or idle, i can > >>>> import stackless > > > If I start pythonwin I get the following error > > ...No Module named Stackless > > > Any help? > > Maybe they are different versions, or installed on different places. > > In those three environments, execute: > > import sys > print sys.version > print sys.executable > > All should report the same version. > The executables for both python and IDLE should reside on the same > directory; for pythonwin, you should get the *same* directory plus > "Lib\site-packages\pythonwin\Pythonwin.exe" > > -- > Gabriel Genellina Ok, for Idle I get: IDLE 1.2 >>> import sys >>> print sys.version 2.5 Stackless 3.1b3 060516 (python-2.5:53557:53567, Jan 25 2007, 22:01:46) [MSC v.1310 32 bit (Intel)] >>> print sys.executable C:\Python25\pythonw.exe >>> And for the command line i get the same thing except the executable is python.exe But for pythonwin i get >>> import sys >>> print sys.version 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] >>> print sys.executable C:\Python25\Lib\site-packages\pythonwin\Pythonwin.exe >>> So does this mean stackless is not usable with pythonwin? Also, is pythonwin needed for the win32 extensions and mfc? Thanks From pythonnews at nospam.jmbc.fr Sun Feb 4 04:31:14 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Sun, 04 Feb 2007 10:31:14 +0100 Subject: Decimating Excel files In-Reply-To: References: Message-ID: <45c5a808$0$21143$7a628cd7@news.club-internet.fr> Hi, > We have a data acquisition program that saves its output to Excel's > ..xls format. Unfortunately, the programmer was too stupid to write > files the average user can read. > > I'd like some advice on how to go about: > 1. Reading a large Excel file and chop it into many Excel files (with > only 65535 lines per file) > or > 2. Decimate an Excel file & write... say every other line (user > selectable)... to a new file. > > I'm pretty experienced at reading and writing simple text files, but > this is my first foray into using COM. I would imagine either choice 1 > or 2 is pretty simple once I can get the file open. When I have Excel stuff to do, I use : http://sourceforge.net/projects/pyexcelerator May be it can cover your needs ? From my point of view, COM is something to avoid : no docs, lot of investigations, weak results. Regards jm From robert at dollinger.it Mon Feb 12 09:27:53 2007 From: robert at dollinger.it (Robert Dollinger) Date: Mon, 12 Feb 2007 15:27:53 +0100 Subject: Win98 - exceptions.IOError: (13, 'Permission denied') In-Reply-To: References: Message-ID: Ok, I have solved the problem. You have to set to something different than "Local System account" under properties of the service. bye Robert Robert Dollinger schrieb: > Hi to everyone, > > I have a Service, that runs on a WinXP machine. The service read a file > on a Win98 machine and write the content in a file on the WinXP machine. > After tree times I get the error message exceptions.IOError: (13, > 'Permission denied'). > > The following things I have already tested: > > - The file on Win98 machine could be deleted, so the file is closed > correctly. > - Stop an restart the service on WinXP, will have no effect > - Reboot the Win98 machine solve the problem for three times. So I have > the same issue explained above. > - I have changed the intervall from 5 sec to 1 minute. After ther first > time I get the error message. > - Using a Win2000 or WINXP machine instead of the Win98 machine. That > works. But unfortunatly the PC to access is a Win98 and I have no > influence to decide for upgrade. > > I can't figure out, what's the problem. > > This is the code to simulate my actual problem: > > # -*- coding: iso-8859-1 -*- > > import win32serviceutil > import win32service > import win32event > import pywintypes > import win32file > import win32pipe > import win32api > import win32con > import thread > import ntsecuritycon > import os > import sys > > class MyService(win32serviceutil.ServiceFramework): > """NT Service.""" > > _svc_name_ = "TCTest" > _svc_display_name_ = "TCTest" > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.stop_event = win32event.CreateEvent(None, 0, 0, None) > self.overlapped = pywintypes.OVERLAPPED() > self.overlapped.hEvent = win32event.CreateEvent(None,0,0,None) > self.thread_handles = [] > > def SvcDoRun(self): > import servicemanager > > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STARTED, > (self._svc_name_, '') > ) > > while 1: > datei = open(r'\\ipcwin98\test\test.txt', 'r') > log = open(r'c:\log.txt', 'a') > log.write(datei.read()) > datei.close() > log.close() > > if win32event.WaitForSingleObject(self.stop_event, 5000) == > win32event.WAIT_OBJECT_0: > break > > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STOPPED, > (self._svc_name_, '') > ) > > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > win32event.SetEvent(self.stop_event) > > if __name__ == '__main__': > win32serviceutil.HandleCommandLine(MyService) > > > Thanks in advanced for your help. > bye > Robert > From thegeoffmeister at gmail.com Sun Feb 11 02:51:55 2007 From: thegeoffmeister at gmail.com (Geoff Hill) Date: Sun, 11 Feb 2007 07:51:55 GMT Subject: can't find a way to display and print pdf through python. References: Message-ID: Are you trying to: a) Make the PDF file open in it's default application? b) Create a PDF-reader in Python? ...because your question is somewhat unclear. Report Lab has no PDF viewer. You would need a PDF/PostScript parser to do that and that's more of a job than I think you're looking for. From http Sat Feb 3 11:05:14 2007 From: http (Paul Rubin) Date: 03 Feb 2007 08:05:14 -0800 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> Message-ID: <7xbqkb2pmt.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > iceberg.) The Pylons, web.py, Karrigell, Webware and TurboGears people > might (rightly) feel slighted if you include Django but not their > frameworks. Yeah well, the Wxpython, PyQt, PyGTK etc. people may feel slighted that Tkinter got included and their stuff didn't, and the Eric, Eclipse, Komodo etc. people may feel slighted that IDLE got included, but that doesn't stop Tkinter and IDLE from being useful and worth shipping in Python. We were talking about db connectivity modules which are quite a bit simpler than tkinter. We were also talking about an SSL wrapper, which *is* included with Python, but is broken (doesn't examine certificates) so people use external modules instead, which is just lame. > Where would you stop? At the boundaries of your particular application > interests? Basic competitive analysis. People ask here all the time "I'm trying to write application XYZ, should I use language L or should I use Python" (L is usually Java or PHP but can be other things). There's always immediately a flood of responses about why Python is better than language L for application XYZ. If the Pythonistas are serious about such a claim, competitive analysis says they should be willing to look at what language L does to support application XYZ (example: PHP includes database connectivity), make a checklist of L's features, and see to it that Python achieves (at least) parity in those areas. From m_tayseer82 at yahoo.com Mon Feb 26 11:36:21 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Mon, 26 Feb 2007 08:36:21 -0800 (PST) Subject: newbie question(file-delete trailing comma) In-Reply-To: <729614.98659.qm@web7811.mail.in.yahoo.com> Message-ID: <595502.96598.qm@web31113.mail.mud.yahoo.com> kavitha thankaian wrote: > and i need the output also in the same input.txt just add import os os.remove('in.txt') os.rename('out.txt', 'in.txt') --------------------------------- Don't be flakey. Get Yahoo! Mail for Mobile and always stay connected to friends. -------------- next part -------------- An HTML attachment was scrubbed... URL: From inq1ltd at verizon.net Sun Feb 18 18:43:27 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Sun, 18 Feb 2007 18:43:27 -0500 Subject: window opens with os.system() In-Reply-To: References: <1171757251.224765.171800@s48g2000cws.googlegroups.com> <200702181609.23862.inq1ltd@verizon.net> Message-ID: <200702181843.28044.inq1ltd@verizon.net> On Sunday 18 February 2007 17:27, Gabriel Genellina wrote: > En Sun, 18 Feb 2007 18:09:23 -0300, > jim-on-linux > > escribi?: > > I have a simple module that sends text files > > to a printer. Then, it moves the file to the > > 'Fprtd' directory. The module contains the > > following code; > > > > > > ##### > > > > for n in PrtList: > > os.system('type '+n+ ' > prn' > > os.system('move '+n+ ' Fprtd') > > Thanks Geneilina, It works fine. shutil.copyfile(xxx,prn) jim-on-linux > > ##### > > > > os.system opens and closes a window for each > > file it sends to the printer and again for > > each time it moves a file to the Fprtd > > directory. If there were only a few files, > > this wouldn't be so bad. But, when the files > > number 300 to 400 it becomes objectionable. > > Just code the above in Python itself. > type xxx > prn == copy xxx prn == > shutil.copyfile(xxx,prn) move xxx Fprtd == > shutil.move(xxx, Fprtd) > > -- > Gabriel Genellina From jonathan.sabo at gmail.com Wed Feb 21 18:13:48 2007 From: jonathan.sabo at gmail.com (jonathan.sabo at gmail.com) Date: 21 Feb 2007 15:13:48 -0800 Subject: pexpect regex help Message-ID: <1172099628.074816.61980@q2g2000cwa.googlegroups.com> I have a pexpect script to walk through a cisco terminal server and I was hoping to get some help with this regex because I really suck at it. This is the code: index = s.expect(['login: ', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: m = re.search('((#.+\r\n){20,25})(\s.*)', s.before) #<---------- MY PROBLEM print m.group(3), print ' %s %s' % (ip[0], port) s.send(chr(30)) s.sendline('x') s.sendline('disco') s.sendline('\n') elif index == 1: print s.before elif index == 2: print print '%s %s FAILED' % (ip[0], port) print 'This host may be down or locked on the TS' s.send(chr(30)) s.sendline('x') s.sendline('disco') s.sendline('\n') This is attempting to match the hostname of the connected host using the output of a motd file which unfortunately is not the same everywhere... It looks like this: ######################################################################### # This system is the property of: # # # # DefNet # # # # Use of this system is for authorized users only. # # Individuals using this computer system without authority, or in # # excess of their authority, are subject to having all of their # # activities on this system monitored and recorded by system # # personnel. # # # # In the course of monitoring individuals improperly using this # # system, or in the course of system maintenance, the activities # # of authorized users may also be monitored. # # # # Anyone using this system expressly consents to such monitoring # # and is advised that if such monitoring reveals possible # # evidence of criminal activity, system personnel may provide the # # evidence of such monitoring to law enforcement officials. # ######################################################################### pa-chi1 console login: And sometimes it looks like this: ######################################################################### # This system is the property of: # # # # DefNet # # # # Use of this system is for authorized users only. # # Individuals using this computer system without authority, or in # # excess of their authority, are subject to having all of their # # activities on this system monitored and recorded by system # # personnel. # # # # In the course of monitoring individuals improperly using this # # system, or in the course of system maintenance, the activities # # of authorized users may also be monitored. # # # # Anyone using this system expressly consents to such monitoring # # and is advised that if such monitoring reveals possible # # evidence of criminal activity, system personnel may provide the # # evidence of such monitoring to law enforcement officials. # ######################################################################### pa11-chi1 login: The second one works and it will print out pa11-chi1 but when there is a space or console is in the output it wont print anything or it wont match anything... I want to be able to match just the hostname and print it out. Any ideas? Thanks, Jonathan From gagsl-py at yahoo.com.ar Fri Feb 16 03:03:14 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 05:03:14 -0300 Subject: I'm faint why this can't work References: Message-ID: En Fri, 16 Feb 2007 03:38:43 -0300, escribi?: > Hello, > I got this similar sample script from books: > $ cat sampdict.py > #!/usr/bin/python > class SampDict(dict): > def __init__(self, filename=None): > self["name"] = filename Are you sure you copied it exactly as it appears? Where did you find it? > But when I run it I got the errors: > >>>> from sampdict import SampDict >>>> SampDict("/etc/passwd") > Traceback (most recent call last): > File "", line 1, in ? > File "sampdict.py", line 4, in __init__ > self["name"] = filename > AttributeError: SampDict instance has no attribute '__setitem__' Usually, when you inherit from another class, you have to call the base class __init__ from inside your own. That is, put this line: dict.__init__(self) as the firt statement on your __init__ -- Gabriel Genellina From devicerandom at gmail.com Tue Feb 13 04:48:33 2007 From: devicerandom at gmail.com (devicerandom at gmail.com) Date: 13 Feb 2007 01:48:33 -0800 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> Message-ID: <1171360113.585827.17440@v45g2000cwv.googlegroups.com> On 13 Feb, 09:14, Peter Otten <__pete... at web.de> wrote: > deviceran... at gmail.com wrote: > > Thanks both for suggestions. I still think that using inheritance is > > somehow cleanest in this case (I always hear the mantra "avoid > > multiple inheritance!", but this is one of the cases it seems to make > > a lot of sense to me), but it's nice food for thought/code anyway. > > "Avoid inheritance" would be almost as justified :-) Why? > Problems that may arise with this case of multiple inheritance: > > - If you need initializers, ensure that they are all invoked Yes, I figured it out. This should be easy in this case. > - What would you do about name clashes? To avoid them your plugins need to > know about each other. Yes, I know, but I can't see any simple solution to this (if you can, please share it with me!). The cmd module works by interpreting any method starting with "do_" as a command, so "do_blah" becomes the "blah" command. If two people write a "do_blah" command, and both plugins are used, I see no easy way to solve the issue (apart rewriting a cmd module). Perhaps there can be some previous sanity check in each modules dict to see if there are obvious namespace clashings, and in this case issue a warning. I don't know. > - State (instance attributes) is shared among all your plugins. Since you > call all base classes Commands, Python's double-underscore hack won't work. What double-underscore hack are you referring to? (sigh, my python limits are all arising...) I can call all base classes PluginNameCommand, however, this wouldn't break the thing (I'm still at the very early planning stage) and would maybe work. m. From grante at visi.com Wed Feb 14 09:46:45 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Feb 2007 14:46:45 -0000 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171431443.737052.183960@j27g2000cwj.googlegroups.com> <1171435541.291367.299290@j27g2000cwj.googlegroups.com> <1171437351.206085.236450@q2g2000cwa.googlegroups.com> Message-ID: <12t686lo3p07p5a@corp.supernews.com> On 2007-02-14, Terry Reedy wrote: >| Wit has nothing to do with it. The fact that you are a Python noob is >| also irrelevant. Your problem statement was unintelligible, as is your >| response. What does "pwn" mean? > > I believe that it is a misspelling of 'own' used by pvp (person versus > person, as opposed to person versus monster) gamers to demonstrate their > in-ness. But perhaps agent-s can enlightenment us further. Mis-spelling things is witty now? Wow. I've been witty all these years and didn't even know it... -- Grant Edwards grante Yow! I'm EXCITED!! I want at a FLANK STEAK WEEK-END!! I visi.com think I'm JULIA CHILD!! From metaperl at gmail.com Thu Feb 8 15:20:28 2007 From: metaperl at gmail.com (metaperl) Date: 8 Feb 2007 12:20:28 -0800 Subject: Latest approach to controlling non-printable / multi-byte characters Message-ID: <1170966028.403341.252770@p10g2000cwp.googlegroups.com> There is no end to the number of frantic pleas for help with characters in the realm beyond ASCII. However, in searching thru them, I do not see a workable approach to changing them into other things. I am dealing with a file and in my Emacs editor, I see "MASSACHUSETTS- AMHERST" ... in other words, there is a dash between MASSACHUSETTS and AMHERST. However, if I do a grep for the text the shell returns this: MASSACHUSETTS?€“AMHERST and od -tc returns this: 0000540 O F M A S S A C H U S E T T 0000560 S 342 200 223 A M H E R S T ; U N I So, the conclusion is the "dash" is actually 3 octal characters. My goal is to take those 3 octal characters and convert them to an ascii dash. Any idea how I might write such a filter? The closest I have got it: unicodedata.normalize('NFKD', s).encode('ASCII', 'replace') but that puts a question mark there. From jura.grozni at gmail.com Sun Feb 11 15:24:18 2007 From: jura.grozni at gmail.com (azrael) Date: 11 Feb 2007 12:24:18 -0800 Subject: help please!! In-Reply-To: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> References: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Message-ID: <1171225457.964450.105830@k78g2000cwa.googlegroups.com> well, this sounds funn. 1) dont expect someone to do your homework. 2) dont expect someone to do dirty homework 3) dont expect someone to do your home work especially when it's something that could make you problems, or the person that is helping you 4) from your message i can "read" that you need the application, and not some knowledge. I don't know what other guys here think about it, if my opinion can considered, you are on your own. i suggest you take a python tutorial and learn how to do it yourself. This situation stinks. On Feb 11, 8:40 pm, "darren112" wrote: > Hi Im new to python and I desperately need help with this task.... > This is everything of what I need to do....... > > The program to be written in Python obviously...... > > The program should support brute-forcing of the authentication process > for a Telnet server via a dictionary attack. > > The python program is required to take four parameters: a) the IP > address of a Computer, b) the port number that the Telnet server is > running on the computer , c) the name of a file containing a list if > usernames, and b) the name of a file containing a list of word/phrases > to be used as passwords. > > The program should then attempt to authenticate itself to the Telnet > server via trying every password for every username. The program > should report when it is successful. > > Please help me.... And as I am new to all this please post step by > step instructions... From MonkeeSage at gmail.com Tue Feb 27 21:10:30 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 27 Feb 2007 18:10:30 -0800 Subject: Yet another unique() function... Message-ID: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> Here's yet another take on a unique() function for sequences. It's more terse than others I've seen and works for all the common use cases (please report any errors on the recipe page): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263 Regards, Jordan From jura.grozni at gmail.com Fri Feb 9 01:40:16 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 22:40:16 -0800 Subject: Is Python for me? In-Reply-To: <1171003042.853235.210090@k78g2000cwa.googlegroups.com> References: <1171003042.853235.210090@k78g2000cwa.googlegroups.com> Message-ID: <1171003216.399685.74000@v45g2000cwv.googlegroups.com> i forgot a query language. something like postgre or mysql On Feb 9, 7:37 am, "azrael" wrote: > i hope you know that for this task, if you want it to be successfull, > you need a really big database. it sounds very simple to this. it > sounds like go through all possible permutations. before you start > writing any code take a pencil and a big paper and do some maths. i > sugesst you read and practise this for about a year about data > structures, algorithms and graph theory (just for the begining). Then > take a look on data mining and then incpect the era model so you can > design a good database. > Tic Tac Toe is a much easier problem and there are a lot of possible > different games (9*8*7*6*5*4*3*2*1=362 880 i dont consider the > rotations). > > it's true that you learn best by solving a problem, but if stoped on > basic on higjschool, then you will need a lot of time to solve this > problem. If you remember basic than you should learn python according > to basic's possibillities in maximum a month. depending on talent and > spare time. > > i sugesst you take some a "a little bit" easier problem to learn > python. > > For this speciffic problem it shold be good to learn on other games. I > started about 7 years ago on tic tac toe and then with reversi. > > You are from USA? I come from a differtent continent so i don't know > what you learn in schools. But if you didn't learn it, take a look on > statistics. very usefull. you should at least know what specific terms > mean althought python has them in the numpy module. > > don't be afraid of all that i said. keep learning and it will pay off. > at the end when you crack the poker machine :-) > that's the life of a geek. learn , learn, learn and one day comes the > jackpot. > > -------------------------------------------------------------- > and no, I am not a junkee, I'm addicted to Python From ian.inglis at gmail.com Thu Feb 1 12:22:27 2007 From: ian.inglis at gmail.com (Cruelemort) Date: 1 Feb 2007 09:22:27 -0800 Subject: LDAP/LDIF Parsing Message-ID: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> All, I am hoping someone would be able to help me with a problem. I have an LDAP server running on a linux box, this LDAP server contains a telephone list in various groupings, the ldif file of which is - dn: dc=example,dc=com objectClass: top objectClass: dcObject objectClass: organization dc: example o: Example Organisation dn: ou=groupa,dc=example,dc=com ou: groupa objectClass: top objectClass: organizationalUnit description: Group A dn: cn=johnsmith,ou=groupa,dc=example,dc=com cn: johnsmith objectClass: top objectClass: person sn: Smith telephoneNumber: 112 dn: cn=davesteel,ou=groupa,dc=example,dc=com cn: davesteel objectClass: top objectClass: person sn: Steel telephoneNumber: 113 dn: ou=groupb,dc=example,dc=com ou: groupb objectClass: top objectClass: organizationalUnit description: Group B dn: cn=williamdavis,ou=groupb,dc=example,dc=com cn: williamdavis objectClass: top objectClass: person sn: Davis telephoneNumber: 122 dn: cn=jamesjarvis,ou=groupb,dc=example,dc=com cn: jamesjarvis objectClass: top objectClass: person sn: Jarvis telephoneNumber: 123 I am creating a python client program that will display the telephone list in the same directory structure as is on the LDAP server (i.e. it starts with buttons of all the groups, when you click on a group it comes up with buttons of all the numbers or groups available, and you can continually drill down). I was wondering the best way to do this? I have installed and used the python-ldap libraries and these allow me to access and search the server, but the searches always return a horrible nesting of lists, tuples and dictionaries, below is an example of returning just one record - ('dc=example,dc=com', {'objectClass': ['top', 'dcObject', 'organization'], 'dc': ['example'], 'o': ['Example Organisation']}) Basically i think i need to parse the search results to create objects and build the python buttons around this, but i was hoping someone would be able to point me in the correct direction of how to do this? Is there a parser available? (there is an ldif library available but it is not obvious how this works, i cannot see much documentation, and it seems to be deprecated...). Many thanks. Ian From gagsl-py at yahoo.com.ar Fri Feb 16 17:28:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 19:28:46 -0300 Subject: output to console and to multiple files References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171645473.844315.152020@k78g2000cwa.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 14:04:33 -0300, Bart Ogryczak escribi?: > On Feb 14, 11:28 pm, "nathan.sh... at gmail.com" > wrote: >> I'm looking for a way to output stdout/stderr (from a subprocess or >> spawn) to screen and to at least two different files. > > I'd derive a class from file, overwrite it's write() method to send a > copy to the log, and then assign sys.stdout = newFile(sys.stdout). > Same for stderr. That's ok inside the same process, but the OP needs to use it "from a subprocess or spawn". You have to use something like tee, working with real file handles. -- Gabriel Genellina From usenet at nicko.org Fri Feb 2 11:42:07 2007 From: usenet at nicko.org (Nicko) Date: 2 Feb 2007 08:42:07 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170433268.115386.189280@k78g2000cwa.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170433268.115386.189280@k78g2000cwa.googlegroups.com> Message-ID: <1170434527.289121.175280@j27g2000cwj.googlegroups.com> On Feb 2, 4:21 pm, "Bart Ogryczak" wrote: > On Feb 1, 2:00 pm, "Nicko" wrote: > > > precision and the answer that they were looking for was: > > a = (b * 04444444445L) >> 32 > > Note that the constant there is in octal. > > 04444444445L? Shouldn?t it be 04444444444? > Or more generally, > const = (1< a = (b * const)>>bitPrecision It's to do with rounding. What you actually need is ceiling((1< Hi, I have compressed files compressed using different techniques (especially unix compress). So I want to have a module that reads any of these (.Z,.bz,.tgz files) files and manipulates the data. The data has a syntax.It contains HEADER (some information) BODY (some information) FOOTER (some information) If it were a normal text file I can get the values corresponding to HEADER BODY and FOOTER by open function. But here the files are in different format .Z , .bz ,.tgz,.gz .But I know these are the only formats.Also I cannot rely upon the extensions of the file (a .Z file can have no extension at all).Is there a way to identify which file am I reading and then read it?If so how to read it? Thanks and Regards, Shadab. Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Thu Feb 1 18:27:10 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 20:27:10 -0300 Subject: Odd import behavior References: <312cfe2b0702011433t17e7e3e0nbcd0a210980dd022@mail.gmail.com> Message-ID: En Thu, 01 Feb 2007 19:33:50 -0300, Gregory Pi?ero escribi?: > I didn't realize Python behaved like this. Is there an FAQ I can read > on this? > > FILE module1.py: > VAR1='HI' > > FILE MAIN.py: > from module1 import * > import module1 > > print VAR1 > print module1.VAR1 > > VAR1='bye' > print VAR1 > print module1.VAR1 > > And the results are: > >>>> HI > HI > bye > HI > > It seems to use module1.VAR1 for VAR1 until I assign something to VAR1 > in which case they become seperate. There is no magic here. It's like this: class Module: pass module1 = Module() # this is like `import module1` module1.VAR1 = 'HI' VAR1 = module1.VAR1 # this is like `from module1 import VAR1` print VAR1 print module1.VAR1 VAR1='bye' print VAR1 print module1.VAR1 -- Gabriel Genellina From http Sat Feb 24 04:33:14 2007 From: http (Paul Rubin) Date: 24 Feb 2007 01:33:14 -0800 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <7xy7mpz6df.fsf@ruckus.brouhaha.com> Message-ID: <7xabz3kihx.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > > s += chr(reduce(operator.xor, ar)) > Yikes! - someday soon I am going to read the docs on what reduce does... Reduce just intersperses an operator over a sequence. For example, reduce(operator.add, (a,b,c,d,e)) is a+b+c+d+e. > Won't this be slow because of the double function call on each char? I think there's the same number of func calls, one xor per char. From duncan.booth at invalid.invalid Fri Feb 2 04:21:29 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Feb 2007 09:21:29 GMT Subject: Sorting a list References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> <45c254a2$0$674$426a34cc@news.free.fr> Message-ID: Steven Bethard wrote: > You don't need to use sorted() -- sort() also takes the key= and > reverse= arguments:: > > >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), > ... ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), > ... ('1996', 'aaa')] > >>> from operator import itemgetter > >>> lines.sort(key=itemgetter(0), reverse=True) > >>> lines > [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), > ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')] I suspect you want another line in there to give the OP what they actually want: sort the list alphabetically first and then reverse sort on the year. The important thing to note is that the reverse flag on the sort method doesn't reverse elements which compare equal. This makes it possible to sort on multiple keys comparatively easily. >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')] >>> from operator import itemgetter >>> lines.sort(key=itemgetter(1)) >>> lines.sort(key=itemgetter(0), reverse=True) >>> lines [('1997', 'aaa'), ('1997', 'bbb'), ('1996', 'aaa'), ('1996', 'ccc'), ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')] From http Sat Feb 3 20:50:22 2007 From: http (Paul Rubin) Date: 03 Feb 2007 17:50:22 -0800 Subject: Python does not play well with others References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <7xk5yyelnl.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > > languages do. PHP hosting providers don't have to install a separate > > PHP to MySQL interface gizmo as far as I know. > > Really? Then why does the MySQL AB download site at > http://dev.mysql.com/downloads/connector/php/ list both a > "Connector/PHP" AND a "native MySQL driver" for PHP? Along with ODBC, > .NET, and two variations of Java connectors. Beats me. It does look like PHP5 has stopped bundling the MySQL client library for licensing reasons: http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.php5 It does say "there will always be MySQL support in PHP of one kind or another" but I'm not sure what that means in this context. On the other hand if MySQL itself supplies the client library, that's almost as good. Remember that this isn't purely about minimizing the number of downloads. It's also about minimizing the number of places to download from, i.e. the number of different development entities one has to deal with. So if you're using Python with MySQL, and you can get everything you need from python.org and mysql.com, then even if it takes multiple downloads it's better than having to get additional stuff from random third party sites, especially when Python's own docs haven't said where to get the stuff. Therefore, if someone can persuade mysql.com to offer downloadable MySQL client drivers for Python at the same place where they supply the PHP drivers, that's better than the current situation where the drivers come from some totally unrelated party. From tiedon_jano at hotmail.com Mon Feb 5 15:08:41 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Mon, 05 Feb 2007 20:08:41 GMT Subject: "flushing"/demanding generator contents - implications for injection of control In-Reply-To: <1170704863.646629.156310@h3g2000cwc.googlegroups.com> References: <1170704863.646629.156310@h3g2000cwc.googlegroups.com> Message-ID: metaperl kirjoitti: > For this program: > > def reverse(data): > for index in range(len(data)-1, -1, -1): > yield data[index] > > r = reverse("golf") > > for char in r: > print char > > > I'm wondering if the line: > > r = reverse("golf") > > "demands" the contents of the function reverse() all at once and if I > must write > > for char in reverse("golf"): > print char > > if I want the results streamed instead of generated complely. > > ** CONTEXT ** > > The simple example above is not what I am really doing. My real > program parses very large > data files using pyparsing. Pyparsing can generate incremental/yielded > results with no problem: > > http://pyparsing.wikispaces.com/message/view/home/248539#248852 > > but because I believe in injection of control (pushing data around as > opposed to having > the target pull it), I get the parse and then inject it into the > generator: > > parse = parsing.parse(fp.read()) > txt = textgen.generate(self.storage.output, patent_key, > parse, f.basename(), debug=False) > I don't know, I'm guessing: ... r = reverse("golf") ... type(r) ... print r.next() f So r is not the string 'flog', it is the generator producing it HTH, Jussi From arnd.zapletal at googlemail.com Sun Feb 4 05:42:17 2007 From: arnd.zapletal at googlemail.com (Arnd) Date: 4 Feb 2007 02:42:17 -0800 Subject: Decimating Excel files In-Reply-To: <52kn9eF1odticU1@mid.individual.net> References: <52kn9eF1odticU1@mid.individual.net> Message-ID: <1170585737.044166.155920@v45g2000cwv.googlegroups.com> > Every other line would be bicimating or something, > wouldn't it? Good observation, but as we have numbers of type Cardinalia, Ordinalia, Distributiva & Multiplicativa in Latin I would prefer secundating or secondating. (Bisimating or bicimating would multiply the lines by a factor 2) ;) Arnd From thn at mail.utexas.edu Mon Feb 12 13:00:51 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 12 Feb 2007 10:00:51 -0800 Subject: c++ for python programmers Message-ID: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> I realize I'm approaching this backwards from the direction most people go, but does anyone know of a good c/c++ introduction for python programmers? Thanks, Thomas From gagsl-py at yahoo.com.ar Tue Feb 6 02:33:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 04:33:36 -0300 Subject: Taint (like in Perl) as a Python module: taint.py References: <1170713584.199237.22210@v33g2000cwv.googlegroups.com> <87iregcacw.fsf@benfinney.id.au> Message-ID: En Mon, 05 Feb 2007 23:01:51 -0300, Ben Finney escribi?: > "Gabriel Genellina" writes: > >> I suppose you don't intend to publish the SafeString class - but if >> anyone can get a SafeString instance in any way or another, he can >> convert *anything* into a SafeString trivially. > > The point (in Perl) of detecting taint isn't to prevent a programmer > from deliberately removing the taint. It's to help the programmer find > places in the code where taint accidentally remains. I'm not convinced at all of the usefulness of tainting. How do you "untaint" a string? By checking some conditions? Let's say, you validate and untaint a string, regarding it's future usage on a command line, so you assume it's safe to use on os.system calls - but perhaps it still contains a sql injection trap (and being untainted you use it anyway!). Tainting may be useful for a short lived string, one that is used on the *same* process as it was created. And in this case, unit testing may be a good way to validate the string usage along the program. But if you store input text on a database or configuration file (username, password, address...) it may get used again by *another* process, maybe a *different* program, even months later. What to do? Validate all input for any possible type of unsafe usage before storing them in the database, so it is untainted? Maybe... but I'd say it's better to ensure things are *done* *safely* instead of trusting a flag. (Uhmm, perhaps it's like "have safe sex; use a condom" instead of "require an HIV certificate") That is: - for sql injection, use parametrized queries, don't build SQL statements by hand. - for html output, use any safe template engine, always quoting inputs. - for os.system and similar, validate the command line and arguments right before being executed. and so on. -- Gabriel Genellina From martin at v.loewis.de Sun Feb 25 13:07:53 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 25 Feb 2007 19:07:53 +0100 Subject: convert strings to utf-8 In-Reply-To: References: Message-ID: <45E1D079.8080804@v.loewis.de> Niclas schrieb: > I'm having trouble to work with the special charcters in swedish (? ? ? > ? ? ?). The script is parsing and extracting information from a webpage. > This works fine and I get all the data correctly. The information is > then added to a rss file (using xml.dom.minidom.Document() to create the > file), this is where it goes wrong. Letters like ? ? ? get messed up and > the rss file does not validate. How can I convert the data to UTF-8 > without loosing the special letters? You should convert the strings from the webpage to Unicode strings. You can see that a string is unicode of print isinstance(s,unicode) prints True. Make sure *every* string you put into the Document actually is a Unicode string. Then it will just work fine. Regards, Martin From sickcodemonkey at gmail.com Wed Feb 28 13:09:24 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 28 Feb 2007 13:09:24 -0500 Subject: Py2EXE problem In-Reply-To: <2adc542f0702271839u472dc57aj8c9bc6d7ad3c660d@mail.gmail.com> References: <2adc542f0702271839u472dc57aj8c9bc6d7ad3c660d@mail.gmail.com> Message-ID: <2adc542f0702281009i2fd2c5e9nc626b7e34b80c270@mail.gmail.com> Ok I found an extremely easy way to resolving this issue (I cannot believe I did not think of it sooner). After Py2exe created the .exe file I noticed a "library.zip" file. I took a look at the Py2exe output, and saw all of the libraries that it failed to insert. I copied all of the .pyc that my application needed and inserted them in the "email folder" within the library.zip. I fired up the application and it worked like a champ. On 2/27/07, Sick Monkey wrote: > > Maybe this is not the board to post this, but hopefully with all of the > python experts out there maybe one of you have encountered this. > > I wrote an application that sends an email with an attachment. When I run > it, it runs great with no issues what-so--ever. > > When I thought I was finally finished, I created an executable file using > py2exe. > > Now, when I run the application, I am getting the following error: > --------------------------------------------------- > Exception in Tkinter callback > Traceback (most recent call last): > File "Tkinter.pyc", line 1403, in __call__ > File "Suppression.py", line 401, in startProc > File "Suppression.py ", line 318, in emailInfo > File "email\__init__.pyc", line 79, in __getattr__ > ImportError: No module named multipart > --------------------------------------------------- > Any ideas on how to get around this one? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Wed Feb 28 18:30:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Mar 2007 10:30:14 +1100 Subject: Extract String From Enclosing Tuple References: <87slcqvskr.fsf@benfinney.id.au> Message-ID: <87hct5x3ll.fsf@benfinney.id.au> Ben Finney writes: > orders = ( > [...] > ) > > order_items = ( > [...] > ) For clarity, these sequences of records should be lists (with each item being a tuple containing the record fields), not tuples. A tuple implies a meaning associated with each position in the sequence (like a record with a positional meaning for each field), a list implies the opposite (a sequence with order but not meaning associated with each position). -- \ "If you were going to shoot a mime, would you use a silencer?" | `\ -- Steven Wright | _o__) | Ben Finney From paddy3118 at netscape.net Sun Feb 4 00:31:38 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 21:31:38 -0800 Subject: main In-Reply-To: References: <1170481031.861396.248680@j27g2000cwj.googlegroups.com> Message-ID: <1170567098.677534.101920@s48g2000cws.googlegroups.com> On Feb 3, 10:53 pm, Dennis Lee Bieber wrote: > On Sat, 03 Feb 2007 05:51:56 -0300, "Gabriel Genellina" > declaimed the following in comp.lang.python: > > > menction that at all. And no one should expect that a beginner would have > > to read section 26.3 on the Language Reference (__main__ -- Top-level > > script environment) just to know what's that stuff about __name__ and > > "__main__"... > > OTOH: a true beginner, working out of the tutorial, is unlikely to > be writing anything that really needs to know about this feature. For > the most part, all this feature does is allow one to write safely > importable modules (ie; modules that only define constants, classes, and > functions when imported) that can also be used as stand-alone programs > (often done to add test capability). Maybe, but viewing their profile of past posts on Google I got the feeling that fatwallet could be trying to understand existing code soehow. - Pad. From nagle at animats.com Mon Feb 12 13:33:41 2007 From: nagle at animats.com (John Nagle) Date: Mon, 12 Feb 2007 18:33:41 GMT Subject: standardized us address In-Reply-To: References: Message-ID: <9q2Ah.7251$gj4.1942@newssvr14.news.prodigy.net> Chris Mellon wrote: > On 2/11/07, mark wrote: > >> Hi >> Is there any python module that will convert address to standard US >> address >> format: >> for ex: >> >> 314 south chauncey avenue >> >> should be: >> 314 s chauncey ave >> >> >> thanks >> mark >> > > This isn't standardization, it's normalization. The USPS maintains > databases that you can use to help you do this, and they'll point you > to third parties who sell software that does it. It's a non-trivial > task. There's a US address normalizer written in Perl available. http://cpan.uwinnipeg.ca/htdocs/Geo-StreetAddress-US/Geo/StreetAddress/US.html Not too big, too; it's mostly tables. Might not be too bad to convert. John Nagle From kibleur.christophe at gmail.com Sat Feb 3 08:02:54 2007 From: kibleur.christophe at gmail.com (Tool69) Date: 3 Feb 2007 05:02:54 -0800 Subject: Vim scripting with python Message-ID: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Hi, I saw several old posts speaking of vim scripting in Python. This one in particular : http://www.velocityreviews.com/forums/t351303-re-pythonising-the-vim-eg-syntax-popups-gt-vimpst.html But I didn't find where to put this "vimrc.py" on my Windows machine. My "normal" _vimrc file is in C:\Documents and Settings\my_name . Does anyone have any advice, and more genraly how to script Vim with Python ? I know I can put some python functions inside my vimrc file like this : function! My_function() python << EOF import vim, string ...blablabla EOF endfunction but I would like to use external ".py" files. Thanks. From mfmorss at aep.com Mon Feb 19 12:56:06 2007 From: mfmorss at aep.com (Mark Morss) Date: 19 Feb 2007 09:56:06 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <1171907766.635204.161240@h3g2000cwc.googlegroups.com> On Feb 16, 4:22 pm, ifti_cr... at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language but i > am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net > > so will you please guide me which GUI based language has worth with > complete OOPS Characteristics > > will wait for the answer > > hope to have a right direction from you Programmer > > Regards > Iftikhar > itzon... at yahoo.com Good grief. I suppose it is Microsoft to whom we owe the idea that there could be such a thing as a "GUI based" programming language. From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 04:54:25 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 16 Feb 2007 20:54:25 +1100 Subject: rot13 in a more Pythonic style? References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <7xps8cjt8s.fsf@ruckus.brouhaha.com> <1171538985.045430.317190@v45g2000cwv.googlegroups.com> <381Bh.2463$Jl.1669@newsread3.news.pas.earthlink.net> <1171566653.207307.213490@k78g2000cwa.googlegroups.com> <7NaBh.1982$x74.571@newsread4.news.pas.earthlink.net> Message-ID: On Fri, 16 Feb 2007 04:53:23 +0000, Dennis Lee Bieber wrote: > On 15 Feb 2007 11:10:53 -0800, "Andy Dingley" > declaimed the following in comp.lang.python: > >> >> Fortunately I don't think it's _quite_ that bad. > > Possibly not, but that description of the problem would likely have > gotten more applicable help than a debate on the merits of > reimplementing translate(). The Original Poster did say in his first post that he knew about translate and encode and he wasn't looking for those solutions: [quote] Yes, I know of .encode() and .translate(). No, I don't actually need rot13 itself, it's just a convenient substitute example for the real job-specific task. [end quote] Perhaps rot13 wasn't the best choice in the world, but how was Andy to know people would answer his post without reading it in full? Oh wait, this is Usenet... *wink* -- Steven. From markscala at gmail.com Mon Feb 26 18:02:39 2007 From: markscala at gmail.com (markscala at gmail.com) Date: 26 Feb 2007 15:02:39 -0800 Subject: what the heck is going on here? Message-ID: <1172530959.750822.207140@v33g2000cwv.googlegroups.com> I found the following ways to generate permutations on the ASPN: Python Cookbook page. SLOW (two defs): def xcombinations(items,n): if n == 0: yield[] else: for i in xrange(len(items)): for cc in xcombinations(items[:i]+items[i+1:],n-1): yield [items[i]]+cc def xpermutations(items): return xcombinations(items,len(items)) FAST: def permutations(L): if len(L) <= 1: yield L else: a = [L.pop(0)] for p in permutations(L): for i in range(len(p)+1): yield p[:i] + a + p[i:] The author of the FAST claimed his method was faster, which I wanted to test. I ran the test as follows: import time name = list('python') faster = time.clock() for x in range(10000): map(''.join,list(permutations(name))) total1 = time.clock() - faster print "Total time for faster: ", total1 xperm_start = time.clock() for x in range(10000): map(''.join,list(xpermutations(name))) total2 = time.clock() - xperm_start print "Total time for xperm: ", total2 If you run these tests in the order above, FAST takes about a .1 seconds and slow takes about .17 seconds. BUT if you reverse the order of the test, SLOW takes almost 10 seconds and FAST is about the same! What's more, if you take map, join and list out of the tests (there's no reason for them to be there anyway) the order doesn't matter any more. Without map/join/list, SLOW and FAST are almost indistinguishable at 10K loops. What's going on? ( This was done in Python2.4 ) From B.Ogryczak at gmail.com Wed Feb 28 06:38:02 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 28 Feb 2007 03:38:02 -0800 Subject: finding out the precision of floats In-Reply-To: <1172602729.777210.23070@a75g2000cwd.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> Message-ID: <1172662682.590738.301630@k78g2000cwa.googlegroups.com> On Feb 27, 7:58 pm, "Arnaud Delobelle" wrote: > On 27 Feb, 14:09, "Bart Ogryczak" wrote: > > > On Feb 27, 1:36 pm, Facundo Batista wrote: > > > > Arnaud Delobelle wrote: > > > > (and I don't want the standard Decimal class :) > > > > Why? > > > Why should you? It only gives you 28 significant digits, while 64-bit > > float (as in 32-bit version of Python) gives you 53 significant > > digits. Also note, that on x86 FPU uses 80-bit registers. An then > > Decimal executes over 1500 times slower. > > Actually 28 significant digits is the default, it can be set to > anything you like. Moreover 53 significant bits (as this is what 53 > counts) is about 16 decimal digits. My mistake. > > >>> from timeit import Timer > > >>> t1 = Timer('(1.0/3.0)*3.0 - 1.0') > > >>> t2 = Timer('(Decimal(1)/Decimal(3))*Decimal(3)-Decimal(1)', > > > 'from decimal import Decimal')>>> t2.timeit()/t1.timeit() > > > 1621.7838879255889 > > Yes. The internal representation of a Decimal is a tuple of one-digit > strings! > This is one of the reasons (by no means the main) why I decided to > write my own class. Why not GMP? > > If that's not enough to forget about Decimal, take a look at this: > > > >>> (Decimal(1)/Decimal(3))*Decimal(3) == Decimal(1) > > False > > >>> ((1.0/3.0)*3.0) == 1.0 > > > True > > OTOH float is not the panacea: My point is, that neither is Decimal. It doesn't solve the problem, creating additional problem with efficiency. > >>> 0.1+0.1+0.1==0.3 > False > >>> 3*0.1==0.3 > > False > > Decimals will behave better in this case. Decimal will work fine as long as you deal only with decimal numbers and the most basic arithmetic. Any rational number with base that is not power of 10, or any irrational number won't have an exact representation. So as long as you're dealing with something like invoices, Decimal does just fine. When you start real calculations, not only scientific, but even financial ones[1], it doesn't do any better then binary float, and it's bloody slow. [1] eg. consider calculating interests rate, which often is defined as math.pow(anualRate,days/365.0). It's not rational number (unless days happen to be mutliple of 365), therefore has no exact representation. BTW, math.* functions do not return Decimals. From deets at nospam.web.de Thu Feb 1 10:02:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Feb 2007 16:02:10 +0100 Subject: SWIG overhead References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> <1170328902.611668.271550@k78g2000cwa.googlegroups.com> <52e2bsF1nlgutU1@mid.uni-berlin.de> <1170340876.890010.184840@a75g2000cwd.googlegroups.com> Message-ID: <52ednjF1npm6bU1@mid.uni-berlin.de> Bart Ogryczak wrote: > On Feb 1, 12:48 pm, "Diez B. Roggisch" wrote: >> > Yeah, found that one googling around. But I haven?t fund anything more >> > up to date. I imagine, that the performance of all of these wrappers >> > has been improved since then. But the performance of Python/C API >> > would too? >> > Anyways, it?s not about exact number, it?s more about taking decision >> > if doing rewrite is worth it?s time. >> >> The wrappers essentially create the boilerplate-code that invokes the >> Python C-API. So whatever improvements the latter has been developed, the >> wrappers will benefit from it. > > Without doubt it?s true in case of SWIG, but if I understand > Python.Boost documentation correctly, it does *not* use Python/C API. It has to. In the end, marshalling data between e.g. python datastructures and C++ is done that way. >> I doubt that there are major performance penalties associated with any of >> them. > > Take a look at pages 23 and 24 of http://people.web.psi.ch/geus/talks/ > europython2004_geus.pdf Ok, I see. I really wonder what SWIG does. > Well, SWIG is easy to use. But I?ve gotta make hundreds of millions of > calls, which do tasks as simple, as getting one int from an array and > returning it. With functions that simple SWIG?s overhead seems to be a > problem. Still I think you should first use wrappers for ease of use. Then when you hit a performance bottleneck, it might be worth wrapping that class manually. However, it _might_ of course be that this isn't integrating too seamless with the wrapped classes, but I can't say anything about that really. Diez From steve at REMOVEME.cybersource.com.au Mon Feb 12 01:44:30 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 12 Feb 2007 17:44:30 +1100 Subject: randomly generate n of each of two types References: <3YOzh.1133$yg7.205@trnddc08> <7x3b5bzyl3.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 11 Feb 2007 22:20:24 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> If you want to avoid shuffle, here's an alternative: >> >> def random_values(n, valuelist=[True, False]): >> N = len(valuelist) >> for _ in range(N*n): >> yield valuelist[random.randrange(0, N)] > > That is not guaranteed to yield exactly equal numbers of true and false. Neither is any random number generator. That's why because it's *random*. Ah, I see what you mean... you're reminding me that the Original Poster seems to want a biased set of almost-but-not-quite-randomly chosen values, so that random_values(1) must return one each of True and False and never True, True or False, False. You're right, that's how the O.P. implicitly specified the problem. But it may not be what he wants. -- Steven D'Aprano From duncan.booth at invalid.invalid Tue Feb 13 08:28:27 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Feb 2007 13:28:27 GMT Subject: Lazy container References: Message-ID: Cristiano Paris wrote: > May be someone has faced this problem before and came up with some > obscure language feature to solve this elegantly :D Yes. Try using weak references. Specifically a weakref.WeakValueDictionary should meet your needs. From tiedon_jano at hotmail.com Tue Feb 6 13:48:53 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 06 Feb 2007 18:48:53 GMT Subject: Help with multiple key sort In-Reply-To: <1170786670.535839.118650@s48g2000cws.googlegroups.com> References: <1170786670.535839.118650@s48g2000cws.googlegroups.com> Message-ID: ian.brady1 at gmail.com kirjoitti: > gurus: > > I want to implement a sql-like sort-by on multiple keys. I've seen > many examples of just two keys. > > I have a list like this > > 1 one 2 > 1 one 1 > 1 two 1 > 1 one 0 > 1 xx 0 > > result should be like this > > 1 four 2 > 1 one 0 > 1 one 1 > 1 one 2 > 1 xx 0 > > It moves right while keeping sorted order to the left. This is the > new stable sort in 2.5. > > I'm not sure what I'm doing wrong. please help. > > Thanks > I'm not a guru. Maybe that's why I don't understand which "sql-like sort-by on multiple keys" would produce output that lacks some of the input but has additional items. ;) In other words: why don't you show your concrete program and the input and output data to use. Is the data a list of tuples or lists or what? Cheers, Jussi From gagsl-py at yahoo.com.ar Wed Feb 21 01:37:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Feb 2007 03:37:58 -0300 Subject: converting u'11\xa022' to '11\xa022' References: Message-ID: En Wed, 21 Feb 2007 00:31:32 -0300, alf escribi?: > one more question, once a unicode object is created e.g. > > u=unicode('hello', 'iso-8859-1') > > is there any way to find: > 1-original encoding of u No. It's like, if you have variable "a" with value 10, you can't know if it came from: a = 10 a = 0x0A a = 012 or even a = len(sys.version_info)<<1, or whatever > 2-list of supported encodings? I don't know how to query the list, except by reading the documentation for the codecs module. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 19:03:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Mar 2007 01:03:06 +0100 Subject: class declaration shortcut In-Reply-To: <54mh20F21ho3eU1@mid.individual.net> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> Message-ID: <45e61068$0$30655$426a34cc@news.free.fr> Bjoern Schliessmann a ?crit : (snip) > In Python, classes have no name. class Toto(object): pass print Toto.__name__ From nagle at animats.com Thu Feb 8 01:00:03 2007 From: nagle at animats.com (John Nagle) Date: Thu, 08 Feb 2007 06:00:03 GMT Subject: Does the world need another v0.1 python compiler? In-Reply-To: References: Message-ID: Grant Olson wrote: > The basic approach I took was compiling to bytecode, and then > transliterating python bytecode to x86 asm. And it is working a little bit. An interesting option might be to generate the byte code used by the SpiderMonkey engine in Mozilla. That's used to handle both Javascript in Firefox and ActionScript in Flash. It has a just-in-time compiler, so you get x86 machine code when you need it. And the run time engine is tiny; there's a copy inside Flash, which is only 2MB. That could be a way to get a faster Python without bringing excess baggage. John Nagle From bignose+hates-spam at benfinney.id.au Mon Feb 5 01:13:43 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 05 Feb 2007 17:13:43 +1100 Subject: problems loading modules References: <1170654370.545302.277060@k78g2000cwa.googlegroups.com> Message-ID: <87sldlqgh4.fsf@benfinney.id.au> "Frank" writes: > >>> import random > >>> print random.randrange(10) > 8 > >>> > > Everything is fine. > > >>> import random > >>> from numpy import * > >>> > >>> print random.randrange(10) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'randrange' > >>> > > Here it does not work. "Don't do that, then." More specifically, 'from foo import *' is deprecated for exactly the reason you found here: you risk clobbering an existing name in the current namespace, and there's no way to determine that by looking at the code. Instead, import modules preserving a module namespace, which is the behaviour you get from 'import foo'. That way, all names remain explicit and you can see where you might be re-binding an existing name. >>> import random >>> random >>> import numpy >>> random >>> numpy.random Alternatively, if you want *specific* attributes from a module or package to be in the current namespace, import them explicitly by name; the same applied above, that you can see which names in particular are being re-bound. >>> import random >>> random >>> from numpy import random >>> random Again: don't use 'from foo import *', without knowing exactly why you're doing it. 'import foo' or 'from foo import bar' are always available, and usually better. -- \ "I always wanted to be somebody. I see now that I should have | `\ been more specific." -- Lily Tomlin | _o__) | Ben Finney From steve at holdenweb.com Fri Feb 16 22:29:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 22:29:38 -0500 Subject: saving path to modules permanently In-Reply-To: <1171667715.610158.90570@a75g2000cwd.googlegroups.com> References: <1171667715.610158.90570@a75g2000cwd.googlegroups.com> Message-ID: Frank wrote: > Hi, > > I want to create some modules to use them in my programs. Now the > problem is, how to add the path to these modules permanently to the > python search path. > > For example: > > import sys > sys.path.append('path to my modules') > > > works fine for one session but does not save this path permanently. I > also tried alreday to set the PYTHONPAHT variable to my modules but > for some reason this does not work either. > > Question: > Can one add a permenent path via pathon commands (I checked already > sys, but it does not seem to have a function for this). > > If not, how to do it otherwise. > > It would be great to give the precise commands if someone knows how. > (BTW, I use linux) > Use export PYTHONPATH=/path/to/module/directory in your shell initialization file. Note that PYTHONPATH (not PYTHONPAHT) must be an /environment/ variable, not just a shell variable. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From sjmachin at lexicon.net Thu Feb 1 02:43:59 2007 From: sjmachin at lexicon.net (John Machin) Date: 31 Jan 2007 23:43:59 -0800 Subject: division by 7 efficiently ??? In-Reply-To: References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> Message-ID: <1170315839.209035.219860@h3g2000cwc.googlegroups.com> On Feb 1, 2:36 pm, John Nagle wrote: > krypto.wiz... at gmail.com wrote: > > Its not an homework. I appeared for EA sports interview last month. I > > was asked this question and I got it wrong. I have already fidlled > > around with the answer but I don't know the correct reasoning behind > > it. > > The answer to that question is that the fastest way to divide > by 7 is to use the divide instruction. You'd have to go down > to a really old 8-bit microprocessor like the Intel 8051 to > find something where bit-twiddling like that pays off. Perhaps not that far back. Google "Granlund Montgomery". The technique got built into gcc. > And no way would this be a win in Python, which is > interpreted. Agreed. From aspineux at gmail.com Tue Feb 13 08:19:52 2007 From: aspineux at gmail.com (aspineux) Date: 13 Feb 2007 05:19:52 -0800 Subject: favourite editor In-Reply-To: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> Message-ID: <1171372792.589283.121990@m58g2000cwm.googlegroups.com> I'm very happy with eclipse and its python module called pydev. It's a little slow because it parse continuously the code (P4 >2.0Ghz required), but give nice realtime info by underlining syntax error or unknown variable (very very useful when miss spelling a variable or a function :-) On 11 f?v, 05:41, "azrael" wrote: > Since i'm new on this forum, and first time meeting a python comunity, > i wanted to ask you for your python editors. > > Im looking for some good python editor, with integrated run function, > without having to set it up manualy like komodo. > I found the pyscripter, and it has all i need, but it's unsatble. > bloated. it crashes when i close an yplication window run by python > from pyscripter. please. tell me a good one with buil in run (<-very > important) and nice gui. if possible to suport projects, code > highlighting, code completition, class browser, python comand line > (>>>), traceback. > > I didn't take a look on vista (and i dont want to), but i hope they > improved the notepad. From pydecker at gmail.com Thu Feb 1 07:07:47 2007 From: pydecker at gmail.com (Peter Decker) Date: Thu, 1 Feb 2007 07:07:47 -0500 Subject: "Correct" db adapter In-Reply-To: <1170324781.762209.115060@p10g2000cwp.googlegroups.com> References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> <1170262532.590048.247580@a75g2000cwd.googlegroups.com> <52c4fdF1o9fd9U1@mid.uni-berlin.de> <1170324781.762209.115060@p10g2000cwp.googlegroups.com> Message-ID: On 1 Feb 2007 02:13:01 -0800, king kikapu wrote: > But one of the reasons that i started learning Python, is to NOT to be > tied-up again with ANY company or specific product again (i had enough > MS addiction over these years...). So, based on this direction, i am > using pyodbc, which is DB-API2 compliant and i suppose that the code i > write this way, will have little changes to use another db in the > future. I don't know if this product will meet your needs, but I've read recently on the Dabo list that they've added support for Microsoft SQL Server. I don't work with databases, so I have no idea how this might compare to what you're looking at, but I do know that in general their code is solid and the authors are responsive. So you might want to check out Dabo: http://dabodev.com -- # p.d. From paul at boddie.org.uk Sun Feb 4 09:20:59 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Feb 2007 06:20:59 -0800 Subject: Python does not play well with others In-Reply-To: References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <1170546032.316062.133050@m58g2000cwm.googlegroups.com> Message-ID: <1170598859.290983.136300@j27g2000cwj.googlegroups.com> Kirk Sluder wrote: > In article <1170546032.316062.133050 at m58g2000cwm.googlegroups.com>, > "Paul Boddie" wrote: > > > Quite. I imagine that most GNU/Linux distributions (and various BSDs) > > provide at least some version of MySQLdb as a package. > > Bingo, I've rarely installed python from python.org, or other > libraries from sourceforge, etc., etc.. Usually I've installed > BSD-style ports, debian-style packages, or RedHat-style RPMs. And while Python eggs may be useful for people managing additional software as some unprivileged user, hosting providers (and virtual private server administrators) will want packages that fit in with the rest of the software being managed in the hosting environment. Paul From kgmuller at gmail.com Fri Feb 16 05:44:28 2007 From: kgmuller at gmail.com (KIaus Muller) Date: Fri, 16 Feb 2007 11:44:28 +0100 Subject: Pickling of generators Message-ID: Generators are becoming more and more important and powerful in Python. The inability of pickle to save/restore generators has become a major (and growing) limitation to the full exploitation of generators. The requirement for pickling generators has already been raised in 2003. My project (SimPy - Simulation in Python) has had this requirement since its inception in 2002. Generator pickling would make saving and reloading simulation state trivial. The workarounds one has to use without this capability are baroque and beyond the expertise of a typical simulation user. Is there any hope of action in this area in the foreseeable future? Klaus Muller (Lead designer of SimPy) -------------- next part -------------- An HTML attachment was scrubbed... URL: From hg at nospam.org Thu Feb 22 12:40:27 2007 From: hg at nospam.org (hg) Date: Thu, 22 Feb 2007 18:40:27 +0100 Subject: What is the best queue implemetation in Python? References: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> Message-ID: John Machin wrote: > On Feb 23, 11:12 am, "John" wrote: >> I want to write a code for Breadth First Traveral for Graph, which needs >> a queue to implement. >> >> I wonder that for such a powerful language as Python, whether there is a >> better and simpler implementation for a traditional FIFO queue? >> > > Better and simpler than *WHAT*? Sorry, but you do that all the time ... "ask the question as you know the answer, otherwise shut the f u ..." Can't you assume for a second that other people do not have your wonderful brain and still have to make it through 60+ years of life of learning ? hg From steve at holdenweb.com Sat Feb 10 03:38:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 08:38:42 +0000 Subject: interacting with shell - another newbie question In-Reply-To: <%hfzh.53050$QU1.17723@newssvr22.news.prodigy.net> References: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> <0e2dnUM6nIWq41DYRVnzvA@telenor.com> <%hfzh.53050$QU1.17723@newssvr22.news.prodigy.net> Message-ID: James Stroud wrote: > Tina I wrote: >> James wrote: >>> Hello, >>> >>> I work in this annoying company where I have to autheticate myself to >>> the company firewall every 30-50 minutes in order to access the >>> internet. (I think it's a checkpoint fw). >>> >>> I have to run "telnet what.ever.ip.address 259" then it prompts me >>> with userid, then password, then I have to select "1". Then the >>> program closes itself and the internet is enabled. >>> >>> I would like to automate this process with Python and run it every 30 >>> miniutes so I don't have to keep typing in these userid/password >>> everytime. How can this be done? Is there a module I can use to >>> interact with the shell? (I'm running linux) >>> >>> Thank you. >>> >>> James >>> >> Sounds like the perfect way to get fired. To be sure though, remember to >> store your password in clear text ;) >> However bizarre the security measures seem it's obviously in place to >> make sure it's *you* sitting at the computer. Scripting the >> authentication process is equal to simply removing it. > > Yes, and finding ways to have employees pointlessly waste time is equal > to simply removing them. The clue, of course, is right there at the start of the original post: "I work at this annoying company ...". What the OP really needs is a new employer if it's impossible to do anything about the "policy". The company and the employee are clearly incompatible. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From greg at cosc.canterbury.ac.nz Sat Feb 3 19:36:19 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 04 Feb 2007 13:36:19 +1300 Subject: PyGUI show_text() In-Reply-To: <1170545132.303861.325340@v33g2000cwv.googlegroups.com> References: <1170545132.303861.325340@v33g2000cwv.googlegroups.com> Message-ID: <45C52A83.1000503@cosc.canterbury.ac.nz> Arnd wrote: > I needed some finer text-positioning on a canvas (ie wanted to center > a string wrt a point, something show_text() doesn't provide) Fonts have ascent, descent, height and line_height attributes, and a width() method for measuring the width of a string. You should be able to find out what you need to know from those. > would it be possible to include some optional positioning > parameters, something like left,center,right,top,middle,bottom to > show_text()). Yes, I'm considering something like that. > All in all thanks a lot for PyGUI, Glad you like it! -- Greg From nagle at animats.com Fri Feb 2 13:20:48 2007 From: nagle at animats.com (John Nagle) Date: Fri, 02 Feb 2007 18:20:48 GMT Subject: Timeout for M2Crypto working - patch In-Reply-To: References: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> Message-ID: <4iLwh.67994$qO4.63966@newssvr13.news.prodigy.net> From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 19 13:04:20 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 19 Feb 2007 19:04:20 +0100 Subject: Declare a variable global References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> Message-ID: <53u754F1tibtgU1@mid.individual.net> yinglcs at gmail.com wrote: > I have the following code: > > colorIndex = 0; > > def test(): > print colorIndex; Don't use ";". It's redundant. > This won't work. But it works if i do this: > > colorIndex = 0; > > def test(): > global colorIndex; > print colorIndex; > > My question is why do I have to explicit declaring 'global' for > 'colorIndex'? Because you could want to have an identifier called colorIndex in test's scope. Globals are infrequently used in Python, thus the more common case is assumed by default. > Can't python automatically looks in the global scope when i > access 'colorIndex' in my function 'test()'? No, it can't looks. Regards, Bj?rn -- BOFH excuse #66: bit bucket overflow From ark at acm.org Wed Feb 14 14:46:14 2007 From: ark at acm.org (Andrew Koenig) Date: Wed, 14 Feb 2007 19:46:14 GMT Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> Message-ID: "redawgts" wrote in message news:1171482088.993720.69620 at l53g2000cwa.googlegroups.com... >I keep getting this error "local variable 'f' referenced before > assignment" in the finally block when I run the following code. > > try: > f = file(self.filename, 'rb') > f.seek(DATA_OFFSET) > self.__data = f.read(DATA_SIZE) > self.isDataLoaded = True > except: > self.isDataLoaded = False > finally: > f.close() > > Can someone tell me what's wrong with the code? Am I doing something > wrong? I'm somewhat new to python but this makes sense to me. If the call to file raises an exception, then variable f won't have been created. Here's a simple example: def f(): throw 42 try: x = f() except: print x Try it and see what happens. While you're at it, you might try to figure out what you would like it to print. From phd at phd.pp.ru Mon Feb 12 12:09:14 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 12 Feb 2007 20:09:14 +0300 Subject: SQLObject 0.8.0 Message-ID: <20070212170914.GB31186@phd.pp.ru> Hello! I'm pleased to announce the 0.8.0 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.7 -------------- Features & Interface -------------------- * It is now possible to create tables that reference each other. Constraints (in the DBMSes that support constraints) are added after the tables have been created. * Added ``createSQL`` as an option for sqlmeta. Here you can add related SQL you want executed by sqlobject-admin create after table creation. createSQL expects a string, list, or dictionary. If using a dictionary the key should be a dbName value (ex. 'postgres') and the value should be a string or list. Examples in sqlobject/tests/test_sqlobject_admin.py or at * Added method ``sqlhub.doInTransaction(callable, *args, **kwargs)``, to be used like:: sqlhub.doInTransaction(process_request, os.environ) This will run ``process_request(os.environ)``. The return value will be preserved. * Added method ``.getOne([default])`` to ``SelectResults`` (these are the objects returned by ``.select()`` and ``.selectBy()``). This returns a single object, when the query is expected to return only one object. The single argument is the value to return when zero results are found (more than one result is always an error). If no default is given, it is an error if no such object exists. * Added a WSGI middleware (in ``sqlobject.wsgi_middleware``) for configuring the database for the request. Also handles transactions. Available as ``egg:SQLObject`` in Paste Deploy configuration files. * New joins! ManyToMany and OneToMany; not fully documented yet, but still more sensible and smarter. * SELECT FOR UPDATE * New module dberrors.py - a hierarchy of exceptions. Translation of DB API module's exceptions to the new hierarchy is performed for SQLite and MySQL. * SQLiteConnection got a new keyword "factory" - a name or a reference to a factory function that returns a connection class; useful for implementing functions or aggregates. See test_select.py and test_sqlite_factory.py for examples. * SQLObject now disallows columns with names that collide with existing variables and methods, such as "_init", "expire", "set" and so on. Small Features -------------- * Configurable client character set (encoding) for MySQL. * Added a close option to .commit(), so you can close the transaction as you commit it. * DecimalValidator. * Added .expireAll() methods to sqlmeta and connection objects, to expire all instances in those cases. * String IDs. * FOREIGN KEY for MySQL. * Support for sqlite3 (a builtin module in Python 2.5). * SelectResults cannot be queried for truth value; in any case it was meaningless - the result was always True; now __nonzero__() raises NotImplementedError in case one tries bool(MyTable.select()) or "if MyTable.select():..." * With empty parameters AND() and OR() returns None. * Allows to use set/frozenset sets/Set/ImmutableSet sets as sequences passed to the IN operator. * ID columns are now INT UNSIGNED for MySQL. Bug Fixes --------- * Fixed problem with sqlite and threads; connections are no longer shared between threads for sqlite (except for :memory:). * The reference loop between SQLObject and SQLObjectState eliminated using weak references. * Another round of bugfixes for MySQL errors 2006 and 2013 (SERVER_GONE, SERVER_LOST). * Fixed a bug in MSSQLConnection caused by column names being unicode. * Fixed a bug in FirebirdConnection caused by column names having trailing spaces. * Order by several columns with inheritance. * Fixed aggregators and accumulators with inheritance. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From arkanes at gmail.com Fri Feb 23 17:40:59 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 23 Feb 2007 16:40:59 -0600 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: <4866bea60702231440g75fdf3ak4df657b138329c16@mail.gmail.com> On 2/23/07, James Stroud wrote: > Troy Melhase wrote: > >> Why do people sometimes use one leading underscore? > > > > > > Many folks like to use the single leading underscore to emphasize that > > the attribute isn't part of the normal way to use the class or > > instance. > > > > It's bad style in my opinion, but I'm probably in the minority. > > I've increasingly found that leading underscores are unnecessary as well > if not using a "magic" attribute with the bounding double underscores. > -- I use the single underscore a lot and should use it more. It indicates something that you shouldn't look at unless you understand and are willing to bind yourself to the class internals. For example, I have a network interface that buffers data as it's being parsed. The internal buffer is a list named _buffer, and messing with the buffer is a good way to break the parser. There's an exterior interface, which is a guaranteed consistent buffer called "message", but (even for me, the author) it's easy to get confused about which one is the safe, public attribute and which one is private. The underscore disambiguates. From naima.mans at gmail.com Fri Feb 23 10:46:40 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 23 Feb 2007 07:46:40 -0800 Subject: Apache Cgi (70007)The timeout specified has expired Message-ID: <1172245600.565599.225990@p10g2000cwp.googlegroups.com> Hello, When i run my python script, it works a moment and then stop with this message in the log: (70007)The timeout specified has expired: ap_content_length_filter: apr_bucket_read() failed refers to ...... I think my script is too long therefore the server stop it... how can i do to run all my python script? thanks for your help From aahz at pythoncraft.com Sun Feb 18 13:16:00 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Feb 2007 10:16:00 -0800 Subject: threading and multicores, pros and cons References: Message-ID: In article , Maric Michaud wrote: > >This is a recurrent problem I encounter when I try to sell python >solutions to my customers. I'm aware that this problem is sometimes >overlooked, but here is the market's law. Could you expand more on what exactly the problem is? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From google at orcon.net.nz Sat Feb 17 18:47:20 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 17 Feb 2007 15:47:20 -0800 Subject: How do I save the contents of a text buffer Message-ID: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> Hi, I'm using Python with pygtk and have this problem - I have read the contents of a file into the text buffer with this code, infile = open("mytextfile", "r") if infile: string = infile.read() infile.close() textbuffer.set_text(string) As a test, I tried to write the buffer back to a file with this code but did not work, outfile = open("newbannedsitelist", "w") outfile.write(textbuffer.get_text(0, 1000, include_hidden_chars=True)) outfile.close() What I want to know is how do I write the contents of the text buffer back to a file? Thanks From Bulkan at gmail.com Wed Feb 21 00:21:43 2007 From: Bulkan at gmail.com (placid) Date: 20 Feb 2007 21:21:43 -0800 Subject: getting a thread out of sleep In-Reply-To: References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> Message-ID: <1172035303.424370.20140@t69g2000cwt.googlegroups.com> On Feb 21, 4:12 pm, mark wrote: > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > On Feb 21, 3:08 pm, mark wrote: > > > Right now I have a thread that sleeps for sometime and check if an > > > event has happened and go back to sleep. Now instead I want the thread > > > to sleep until the event has occured process the event and go back to sleep > > > > class eventhndler(threading.Thread): > > > def __init__(self): > > > threading.Thread.__init__(self) > > > def run(self): > > > while True: > > > time.sleep(SLEEPTIME) > > > ''''do event stuff''' > > > The way i would do this is by using an threading.Event ( > >http://docs.python.org/lib/event-objects.html) > > > > > > class eventhandler(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > self.event = threading.Event() > > def run: > > while True: > > # block until some event happens > > self.event.wait() > > """ do stuff here """ > > self.event.clear() > > > > > the way to use this is to get the main/separate thread to set() the > > event object. > > Can you give an example of how to get the main threead to set teh event object? > this is exactly what i wanted to do! > thanks a lot! > mark To set the event object if __name__ == "__main__": evtHandlerThread = eventhandler() evtHandler.start() # do something here # evtHandler.event.set() # do more stuff here # evtHandler.event.set() Hope thats what your looking for. Cheers From dwmaillist at gmail.com Fri Feb 16 15:16:37 2007 From: dwmaillist at gmail.com (dwmaillist at gmail.com) Date: 16 Feb 2007 12:16:37 -0800 Subject: can't load a dll in python 2.5 Message-ID: <1171656997.423604.175410@v45g2000cwv.googlegroups.com> Hello, I am on WindowsXP. I have a dll that I can load in python 2.3 but when trying to load it into python 2.5 it complains that there is nothing by that name. Is there some aspect of the dll loading mechanism between python 2.3 and 2.5 that has changed preventing me from loading the dll in 2.5? Thanks in advance for your suggestions. Daniel From richard.charts at gmail.com Tue Feb 6 15:51:30 2007 From: richard.charts at gmail.com (Richard Charts) Date: 6 Feb 2007 12:51:30 -0800 Subject: electronics and python In-Reply-To: <1170787134.923982.197760@v33g2000cwv.googlegroups.com> References: <1170787134.923982.197760@v33g2000cwv.googlegroups.com> Message-ID: <1170795090.011941.153770@q2g2000cwa.googlegroups.com> On Feb 6, 1:38 pm, "lee" wrote: > Hi guys.....Is there any software written using python for > electronics.....i mean any simulation software or something?? There's MyHDL. http://myhdl.jandecaluwe.com/doku.php I found it originally in a Linux Journal article some years ago. http://www.linuxjournal.com/article/7542 Haven't tried it in a while so you'll have to test it yourself. From kirk at nospam.jobsluder.net Sat Feb 3 12:06:54 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Sat, 03 Feb 2007 12:06:54 -0500 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <7xbqkb2pmt.fsf@ruckus.brouhaha.com> Message-ID: In article <7xbqkb2pmt.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > skip at pobox.com writes: > > Where would you stop? At the boundaries of your particular application > > interests? > > If the Pythonistas are serious > about such a claim, competitive analysis says they should be willing > to look at what language L does to support application XYZ (example: > PHP includes database connectivity), make a checklist of L's features, > and see to it that Python achieves (at least) parity in those areas. Well, digging into this, php includes database connectivity if compiled against the database client libraries. So it's not as if you can just download php and have it work against the database you want. I also don't think that python as a general-purpose programming language is in direct competition to web frameworks like PHP and ColdFusion. Perhaps the right answer is to say that PHP is a better solution for people wanting a web templating framework with embedded scripting, while Python is a better solution for people who want a general scripting/application language with broad support for specific applications via add-on modules. But then again, I'm one of those heterodox people who argue that one should fit the tool to the problem. Common Lisp, bash, awk, sed and R are other great languages for different domains. From bwooster47 at gmail.com Wed Feb 21 21:17:59 2007 From: bwooster47 at gmail.com (bwooster47 at gmail.com) Date: 21 Feb 2007 18:17:59 -0800 Subject: Bug in time module - %z works in perl, not in python? Message-ID: <1172110679.681182.128350@j27g2000cwj.googlegroups.com> Following python code prints out incorrect UTC Offset - the python docs say that %z is not fully supported on all platforms - but on Linux Fedora FC5, perl code works and python does not - is this a bug or is this expected behavior? For a EST timezone setup, Perl prints correct -0500, while Python prints +0000 - this is Python 2.4. Perl: $now_string = strftime "%Y-%m-%d %H:%M:%S %Z%z", localtime; print $now_string, "(iso local)\n"; 2007-02-21 21:16:16 EST-0500 (iso localtime, perl) Python: now_string = time.strftime("%Y-%m-%d %H:%M:%S %Z%z", time.localtime()) print now_string, " (iso localtime, python)" 2007-02-21 21:15:58 EST+0000 (iso localtime, python) Is this expected behavior, or a bug? From parallelpython at gmail.com Sun Feb 4 22:57:17 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 4 Feb 2007 19:57:17 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: <1170647837.646739.259570@j27g2000cwj.googlegroups.com> On Jan 12, 11:52 am, Neal Becker wrote: > parallelpyt... at gmail.com wrote: > > Has anybody tried to runparallelpythonapplications? > > It appears that if your application is computation-bound using 'thread' > > or 'threading' modules will not get you any speedup. That is because > >pythoninterpreter uses GIL(Global Interpreter Lock) for internal > > bookkeeping. The later allows only onepythonbyte-code instruction to > > be executed at a time even if you have a multiprocessor computer. > > To overcome this limitation, I've created ppsmp module: > > http://www.parallelpython.com > > It provides an easy way to runparallelpythonapplications on smp > > computers. > > I would appreciate any comments/suggestions regarding it. > > Thank you! > > Looks interesting, but is there any way to use this for a cluster of > machines over a network (not smp)? There are 2 major updates regarding Parallel Python: http:// www.parallelpython.com 1) Now (since version 1.2) parallel python software could be used for cluster-wide parallelization (or even Internet-wide). It's also renamed accordingly: pp (module is backward compatible with ppsmp) 2) Parallel Python became open source (under BSD license): http:// www.parallelpython.com/content/view/18/32/ From metaperl at gmail.com Thu Feb 8 14:43:09 2007 From: metaperl at gmail.com (metaperl) Date: 8 Feb 2007 11:43:09 -0800 Subject: Parsing HTML In-Reply-To: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> References: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> Message-ID: <1170963788.882845.124810@k78g2000cwa.googlegroups.com> On Feb 8, 2:38 pm, "mtuller" wrote: > I am trying to parse a webpage and extract information. BeautifulSoup is a great Python module for this purpose: http://www.crummy.com/software/BeautifulSoup/ Here's an article on screen scraping using it: http://iwiwdsmi.blogspot.com/2007/01/how-to-use-python-and-beautiful-soup-to.html From mccredie at gmail.com Wed Feb 7 19:55:51 2007 From: mccredie at gmail.com (Matimus) Date: 7 Feb 2007 16:55:51 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: <1170896151.334753.113130@l53g2000cwa.googlegroups.com> > For some reason Python 2.2.4 cannot find the Numeric module. It's been Is this a typo, or are you really using 2.2.4? If so, you are going to have to get the versions of Numeric and PIL that work with Python 2.2. Or, alternatively, you can install python 2.4.4 with the .msi file you listed. You should also be able to run that just like an executable if you are using Windows XP. Based on the assumption that you have Python 2.2 installed, this will leave you with two version of Python, which will work, but could be tricky. It might be best to just uninstall and reinstall Python. -Matt From george.sakkis at gmail.com Sun Feb 18 10:26:13 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Feb 2007 07:26:13 -0800 Subject: Complex HTML forms In-Reply-To: References: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> Message-ID: <1171812373.552835.226290@s48g2000cws.googlegroups.com> On Feb 18, 4:44 am, Gregor Horvath wrote: > George Sakkis schrieb: > > > I'd like to gather advice and links to any existing solutions (e.g. > > libraries, frameworks, design patterns) on general ways of writing > > complex web forms, as opposed to the typical {name:value} flat model. > > A particular case of what I mean by complex is hierarchical forms. For > > http://toscawidgets.org/http://docs.turbogears.org/1.0/SimpleWidgetForm > > -- > Greg Thank you all for the helpful replies. ToscaWidgets seems particularly promising at a first glance, I'll look into it first. Best, George From eopadoan at altavix.com Tue Feb 6 06:15:11 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Tue, 6 Feb 2007 09:15:11 -0200 Subject: lambda functions ? In-Reply-To: References: <7xy7nc6y9e.fsf@ruckus.brouhaha.com> Message-ID: > This means that "f" is not a pointer to make_incrementor but rather to > the internal (copied?) function. "returned" function isthe right here. As any returned object from a function. > > > This style is very common in Scheme programming so you might read a > > Scheme book if you want to understand it. The classic: > > > > http://mitpress.mit.edu/sicp/ > > > > I might just well do that. A nice read indeed, but understand this concept first: http://en.wikipedia.org/wiki/First-class_function -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com From deets at nospam.web.de Fri Feb 16 08:53:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 Feb 2007 14:53:27 +0100 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <45d5a499$0$5995$b9f67a60@news.newsdemon.com> <1171631180.776312.258100@v33g2000cwv.googlegroups.com> <53lp57F1t2g4mU2@mid.uni-berlin.de> <1171633519.379342.306750@j27g2000cwj.googlegroups.com> Message-ID: <53lranF1th0pcU1@mid.uni-berlin.de> Paul Boddie wrote: > On 16 Feb, 14:16, "Diez B. Roggisch" wrote: >> >> You can't leave WSDL out of SOAP > > Yes you can, since they're two different things. What you probably > meant was that you can't leave WSDL out of "big architecture", W3C > standards-intensive Web services. Of course, RPC-style SOAP without > the contracts imposed by WSDL may remove some of the attractions for > some people (who really should consider CORBA, anyway), but then > there's always document-oriented SOAP, although if you don't want the > baggage associated with routing and other things, plain XML messaging > would be easier. And there's always XMPP if you want stuff like > routing and a standard that isn't undergoing apparently continuous > change. Didn't know that. Yet I presume it is pretty awful to manually decompose and compose the method invocations and parameter sets. I've got no idea what document-orientied SOAP means either. Is that just pushing XML-files over a protocol? Diez From gagsl-py at yahoo.com.ar Mon Feb 19 20:30:10 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 22:30:10 -0300 Subject: FPE: Add bindings to exception tracebacks. References: <13f991410702191447o41969227k72ffb9417993f55b@mail.gmail.com> Message-ID: En Mon, 19 Feb 2007 19:47:26 -0300, Nathan escribi?: > Throughout my python development career, I've occasionally made > various developer tools to show more information about assertions or > exceptions with less hassle to the programmer. Until now, these tools > didn't pass a utility vs pain-to-use threshold. > > Now I've created a tool I believe to have passed that threshold, which > I call "binding annotated exception tracebacks". In short, this tool > adds text showing relevant local bindings to each level in a stack > trace print out. Something very similar already exists in the standard library, but using a very misleading name, "cgitb". It works much better with a source file (so it can print source lines too) === begin tb.py === import cgitb cgitb.enable(format="text") def f(c): d = 2*c return g(c) def g(x): return (lambda z: z+'foo')(x) f(42) === end tb.py === C:\TEMP>python tb.py Python 2.5: c:\apps\python\python.exe Mon Feb 19 22:27:26 2007 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. C:\TEMP\tb.py in () 7 8 def g(x): 9 return (lambda z: z+'foo')(x) 10 11 f(42) f = C:\TEMP\tb.py in f(c=42) 4 def f(c): 5 d = 2*c 6 return g(c) 7 8 def g(x): global g = c = 42 C:\TEMP\tb.py in g(x=42) 7 8 def g(x): 9 return (lambda z: z+'foo')(x) 10 11 f(42) z undefined x = 42 C:\TEMP\tb.py in (z=42) 7 8 def g(x): 9 return (lambda z: z+'foo')(x) 10 11 f(42) z = 42 x undefined : unsupported operand type(s) for +: 'int' and 'str ' The above is a description of an error in a Python program. Here is the original traceback: Traceback (most recent call last): File "tb.py", line 11, in f(42) File "tb.py", line 6, in f return g(c) File "tb.py", line 9, in g return (lambda z: z+'foo')(x) File "tb.py", line 9, in return (lambda z: z+'foo')(x) TypeError: unsupported operand type(s) for +: 'int' and 'str' -- Gabriel Genellina From mfmdevine at gmail.com Fri Feb 23 03:46:58 2007 From: mfmdevine at gmail.com (amadain) Date: 23 Feb 2007 00:46:58 -0800 Subject: pexpect regex help In-Reply-To: <1172099731.535866.234380@s48g2000cws.googlegroups.com> References: <1172099628.074816.61980@q2g2000cwa.googlegroups.com> <1172099731.535866.234380@s48g2000cws.googlegroups.com> Message-ID: <1172220418.035252.65410@8g2000cwh.googlegroups.com> On Feb 21, 11:15 pm, jonathan.s... at gmail.com wrote: > On Feb 21, 6:13 pm, jonathan.s... at gmail.com wrote: > > > > > I have apexpectscript to walk through a cisco terminal server and I > > was hoping to get some help with this regex because I really suck at > > it. > > > This is the code: > > > index = s.expect(['login: ',pexpect.EOF,pexpect.TIMEOUT]) > > if index == 0: > > m = re.search('((#.+\r\n){20,25})(\s.*)', > > s.before) #<---------- MY PROBLEM > > print m.group(3), > > print ' %s %s' % (ip[0], port) > > s.send(chr(30)) > > s.sendline('x') > > s.sendline('disco') > > s.sendline('\n') > > elif index == 1: > > print s.before > > elif index == 2: > > print > > print '%s %s FAILED' % (ip[0], port) > > print 'This host may be down or locked on the TS' > > s.send(chr(30)) > > s.sendline('x') > > s.sendline('disco') > > s.sendline('\n') > > > This is attempting to match the hostname of the connected host using > > the output of a motd file which unfortunately is not the same > > everywhere... It looks like this: > > > ######################################################################### > > # This system is the property > > of: # > > # > > # > > # DefNet > > # > > # > > # > > # Use of this system is for authorized users > > only. # > > # Individuals using this computer system without authority, or > > in # > > # excess of their authority, are subject to having all of > > their # > > # activities on this system monitored and recorded by > > system # > > # > > personnel. # > > # > > # > > # In the course of monitoring individuals improperly using > > this # > > # system, or in the course of system maintenance, the > > activities # > > # of authorized users may also be > > monitored. # > > # > > # > > # Anyone using this system expressly consents to such > > monitoring # > > # and is advised that if such monitoring reveals > > possible # > > # evidence of criminal activity, system personnel may provide > > the # > > # evidence of such monitoring to law enforcement > > officials. # > > ######################################################################### > > > pa-chi1 console login: > > > And sometimes it looks like this: > > > ######################################################################### > > # This system is the property > > of: # > > # > > # > > # DefNet > > # > > # > > # > > # Use of this system is for authorized users > > only. # > > # Individuals using this computer system without authority, or > > in # > > # excess of their authority, are subject to having all of > > their # > > # activities on this system monitored and recorded by > > system # > > # > > personnel. # > > # > > # > > # In the course of monitoring individuals improperly using > > this # > > # system, or in the course of system maintenance, the > > activities # > > # of authorized users may also be > > monitored. # > > # > > # > > # Anyone using this system expressly consents to such > > monitoring # > > # and is advised that if such monitoring reveals > > possible # > > # evidence of criminal activity, system personnel may provide > > the # > > # evidence of such monitoring to law enforcement > > officials. # > > ######################################################################### > > pa11-chi1 login: > > > The second one works and it will print out pa11-chi1 but when there > > is a space or console is in the output it wont print anything or it > > wont match anything... I want to be able to match just the hostname > > and print it out. > > > Any ideas? > > > Thanks, > > > Jonathan > > It is also posted here more clearly and formatted as it would appear > on the terminal: http://www.pastebin.ca/366822 what about using s.before.split("\r\n")[-1]? A From gagsl-py at yahoo.com.ar Thu Feb 8 12:18:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 8 Feb 2007 09:18:26 -0800 Subject: postgres backup script and popen2 In-Reply-To: References: <1170951829.472924.65040@q2g2000cwa.googlegroups.com> Message-ID: <1170955106.724239.47920@k78g2000cwa.googlegroups.com> On 8 feb, 13:29, Jean-Paul Calderone wrote: > On 8 Feb 2007 08:23:49 -0800, Gabriel Genellina wrote: > >On 8 feb, 10:27, Ma?l Benjamin Mettler wrote: > >> flupke schrieb: > >> > i made a backup script to backup my postgres database. > >> > Problem is that it prompts for a password. It thought i > >> > could solve this by using popen2. > > >> Use pexpect:http://pexpect.sourceforge.net/ > > >pexpect could work. But a better way would be to supply the password > >on the command line. > > So that it shows up in `ps' output to anyone on the system? :) Any solution has pros and cons... having the password in the source code is not so good anyway... -- Gabriel Genellina From ziga.seilnacht at gmail.com Fri Feb 16 17:15:05 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 16 Feb 2007 14:15:05 -0800 Subject: cmath, __float__ and __complex__ In-Reply-To: <1171583533.455129.261490@k78g2000cwa.googlegroups.com> References: <1171583533.455129.261490@k78g2000cwa.googlegroups.com> Message-ID: <1171664105.661871.158970@m58g2000cwm.googlegroups.com> Mark Dickinson wrote: > Does anyone know of a good reason for the above behaviour? Would a > patch to complexobject.c that `fixes' this be of any interest to > anyone but me? Or would it likely break something else? I think this is a bug in the PyComplex_AsCComplex function. To get more feedback, submit your patch to the Python patch tracker: http://sourceforge.net/patch/?group_id=5470 Patch submission guidelines can be found here: http://www.python.org/dev/patches/ Ziga From horpner at yahoo.com Fri Feb 16 14:41:36 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Feb 2007 20:41:36 +0100 Subject: why I don't like range/xrange References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <1171645302.453369.166190@s48g2000cws.googlegroups.com> Message-ID: On 2007-02-16, Bart Ogryczak wrote: > On Feb 16, 4:30 pm, "stdazi" wrote: > >> for (i = 0; some_function() /* or other condition */ ; i++) > > C's "for(pre,cond,post) code" is nothing more, then shorthand form of > "pre; while(cond) {code; post;}" > Which translated to Python would be: > > pre > while cond: > code > post No, when you consider the continue statement, which which Python also supports. for (pre; cond; post) { continue; } That's not an infinite loop in C, but the Python while-loop version would be. -- Neil Cerutti From jimhill at swcp.com Sat Feb 10 01:57:05 2007 From: jimhill at swcp.com (Jim Hill) Date: Sat, 10 Feb 2007 06:57:05 +0000 (UTC) Subject: Embedding, "import site", PYTHONHOME, and an old, old issue Message-ID: Well, I've found about a hundred thousand web pages where people have had the same problem I have but nary a page with a solution that works for me. I want to do a simple embed, so I've followed the example in the Extending and Embedding documentation: In the .c file, #include int routine() { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } The code compiles just fine, but when I execute it the call to Py_Initialize() comes back with: 'import site' failed; use -v for traceback Traceback (most recent call last): File "", line 1, in ImportError: No module named time I found a lot of websites that say to set PYTHONHOME to the the path to the directory where site.py lives. I did that but I get the same error. Here are a few bits o' additional information: 'python -v' tells me it was built with gcc 3.4.4 (and has no trouble at all finding site.py whether PYTHONHOME is defined or not). The following code snippet: >>> import distutils.sysconfig >>> distutils.sysconfig.get_config_var('LINKFORSHARED') comes back with '-Xlinker -export-dynamic'. My own code needs to use Portland Group's pgi. I did some googling for various permutations of nouns from the preceding few paragraphs and found Pythonic mention of using "-Wl,-export-dynamic" as a flag for the PG linker. OK, try that, builds fine, same error. I cannot recompile Python on this machine and I don't really understand exactly what is happening with the Py_* function calls in the C snippet above, or whether I can get more detailed traceback info. This is the first time I've tried embedding and it's rather obvious that I've run into a problem that everyone but Messrs. van Rossum and Lundh has hit. Somebody, somewhere must have an honest-to-glub solution. If you are that somebody, please let me know what to do because I'm about to throw in the towel and embed That Other Language. Oh, one more thing: if I launch python from the shell and type in the strings from the C snippet it works fine. Thanks, Jim -- It's not "pretexting", it's "lying." From elrondrules at gmail.com Wed Feb 7 14:50:55 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 7 Feb 2007 11:50:55 -0800 Subject: need help to kill a process In-Reply-To: References: <1170813580.163486.219190@l53g2000cwa.googlegroups.com> Message-ID: <1170877855.791892.277590@q2g2000cwa.googlegroups.com> On Feb 6, 8:24 pm, "Gabriel Genellina" wrote: > En Tue, 06 Feb 2007 22:59:40 -0300, escribi?: > > > > > > > this is my code snip. > > within my python script I have the following commands.. > > > > > > import os > > ... > > os.system ("cd /home; ./TestTool &") > > os.system ("cd /usr/; sh run.sh load.xml &") > > > > > > I need to kill these 2 process after a particular job is done.. is > > there any way to get the pids of these process and if so how do i > > invoke the kill command through os.system.. > > > or else is there anyother way to do this... > > If you're using Python>=2.4 you could use the subprocess module. > > import subprocess > child1 = subprocess.Popen(["./TestTool"], cwd="/home") > child2 = subprocess.Popen(["sh","run.sh","load.xml"], cwd="/usr") > > Popen objects have a pid attribute. You don't have to use os.system to > kill them; use os.kill instead. > You'll notice that I leave out the final &, because I don't know how to > start a background process without using the shell. But I think you can > use: bg [pid], afterwards, to get the same result. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - thx for the reply os.kill worked fine for the first process.. for the second one the kill managed to kill the shell but the application is still running.. is there any other work around for this.. thanks From sickcodemonkey at gmail.com Tue Feb 6 18:31:17 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 6 Feb 2007 18:31:17 -0500 Subject: Dictionary/Hash question Message-ID: <2adc542f0702061531g7504de83ob01b56933794a37e@mail.gmail.com> Even though I am starting to get the hang of Python, I continue to find myself finding problems that I cannot solve. I have never used dictionaries before and I feel that they really help improve efficiency when trying to analyze huge amounts of data (rather than having nested loops). Basically what I have is 2 different files containing data. My program will take the first line in one file and see if it exists in another file. If it does find a match, then it will write the data to a file. --------------- Right now, the code will open file1 and store all contents in a list. Then it will do the same thing to file2. THEEEEN it will loop over list1 and insert into a Hash table. I am trying to find out a way to make this code more efficient. SO here is what i would rather have..... when i open file1 send directly to the hash table totally bypassing the insertion of the script...... Is this possible? def fcompare(f1name, f2name): import re mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') f1 = fopen(f1name) f2 = fopen(f2name) if not f1 or not f2: return 0 a = f1.readlines(); f1.close() b = f2.readlines(); f2.close() file1List= [] print "starting list 1" for c in a: file1List.extend(mailsrch.findall(c)) print "storing File1 in dictionary." d1 = {} for item in file1List : d1[item] = None print "finished storing information in lists." print "starting list 2" file2List = [] for d in b: file2List.extend(mailsrch.findall(d)) utp = open("match.txt","w") for item in file2List : if d1.has_key( item ) : utp.write(item + '\n') utp.close() #del file1List #del file2List print "finished comparing 2 lists." #return 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian at sweetapp.com Tue Feb 6 06:39:39 2007 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 06 Feb 2007 12:39:39 +0100 Subject: XMLRPC Server In-Reply-To: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> Message-ID: <45C868FB.909@sweetapp.com> viscanti at gmail.com wrote: > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > It's not too difficult to configure everything, but I would like to > tune it in order to receive up to 2000 calls per minute without any > problems. That doesn't seem like excessive volume. Why not just try it? You could replace your database logic with time.sleep(1) for now. > Do Pthon CGIs use threading? To do what? CGI requires that a new interpreter instance be launched to handle every request. The requests will be handled in parallel with the number of requests handled simultaneously depending on your apache configuration. > I need to make it very efficient, Actually, you might not have to. 2000 calls/minute isn't that big, assuming you have a decent server. Cheers, Brian From rshepard-at-appl-ecosys.com Fri Feb 9 20:01:42 2007 From: rshepard-at-appl-ecosys.com (rshepard-at-appl-ecosys.com) Date: 10 Feb 2007 01:01:42 GMT Subject: Matching Strings References: Message-ID: On 2007-02-10, James Stroud wrote: > Assuming item is "(u'ground water',)" > > import re > item = re.compile(r"\(u'([^']*)',\)").search(item).group(1) James, I solved the problem when some experimentation reminded me that 'item' is a list index and not a string variable. by changing the line to, if item[0] == selName: I get the matchs correctly. Now I need to extract the proper matching strings from the list of tuples, and I'm working on that. Many thanks, Rich From ishpeck at gmail.com Tue Feb 27 17:58:14 2007 From: ishpeck at gmail.com (Ishpeck) Date: 27 Feb 2007 14:58:14 -0800 Subject: Running Python scripts from BASH In-Reply-To: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> References: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> Message-ID: <1172617094.797736.60800@v33g2000cwv.googlegroups.com> It may be worth noting that I'm running Cygwin on WindowsXP professional. From nospamformeSVP at gmail.com Sat Feb 17 10:20:36 2007 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 17 Feb 2007 10:20:36 -0500 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: ifti_crazy at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language but i > am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net > By 'GUI based programming language' I think that you mean an integrated development environment that includes a visual designer that allows you to layout your GUI and that generates a skeleton application for you to complete. If this is so then the nearest thing that I have found is Boa Constructor, although you will need to know more about the underlying windowing system (wxPython) than you would when using VB.net in Visual Studio. Another system worth a close look is Pythoncard. Other folks have already mentioned Dabo, but this is probably too early in its development for your needs. As an alternative, you can make your own choice of editor/IDE and use a stand-alone visual designer for your GUI. I like Pydev/Eclipse for an IDE and wxGlade for the visual designer. Again, you will need to learn something about wxPython if you want avoid lots of frustration - Robin Dunn's book 'wxPython in Action' is good. There are probably similar toolkits available for combinations of Python and other windowing systems (Tkinter, Qt). Don. From jeff at taupro.com Fri Feb 2 08:37:54 2007 From: jeff at taupro.com (Jeff Rush) Date: Fri, 02 Feb 2007 07:37:54 -0600 Subject: About PyCamp - a Regional Python Unconference Message-ID: <45C33EB2.8000202@taupro.com> A week or so ago, the Dallas and Houston Python User Groups met online in a chat room, to discuss the possibility of a regional Python conference. There was interest on all sides. Some of the Dallas members had recently attended their second BarCamp (http://barcamp.org), defined as an ad-hoc gathering born from the desire for people to share and learn in an open environment. From this interaction as well as the realization, after the Dallas group hosted PyCon in 2006 and will again in 2007, that a conference is a *lot* of work, we decided to try the idea of running an "unconference". An unconference (http://en.wikipedia.org/wiki/Unconference) is a conference where the content of the sessions is driven and created by the participants, generally day-by-day during the course of the event, rather than by a single organizer, or small group of organizers, in advance. And tossing around some names, we decided upon "PyCamp". There is much to be discussed re dates, location and how it will operate, so I set up the website: http://pycamp.python.org/ and a Mailman instance for mailing lists at: http://pycamp.python.org/lists/ The rough idea is to hold a Texas-wide unconference, perhaps sometimes in August and near Austin. There was also the idea of holding a rotating unconference that moves between Dallas, Austin and Houston, say twice a year. To minimize the impact on participant (not attendee - this is an unconference after all where you are expected to get involved) schedules, it was suggested we hold it over a weekend. We'd meet for dinner/drinks on a Friday evening, hold our talks at some hotel on Saturday and early Sunday, and then travel home Sunday evening. You'll notice that I keep saying "maybe", "suggested" and other weasel words above. This is because I'm not the conference chair (thankfully) and we're not imposing the schedule/rules. Ralph Green of Dallas has volunteered to wrangle the project and website, and is one of those who has attended a BarCamp. We need the creative energy and participation by members of all Python User Groups in Texas and invite you to join the Texas PyCamp mailing list (see above URL). Oh, and we didn't want to be the only ones having fun, so the PyCamp URL, wiki and mailing lists are available to other states or regions than Texas. Hopefully we can start a movement toward regional PyCamp Unconferences everywhere. If you're unfortunate enough to not live in Texas, drop me an email and I'll set you up your own regional section of the PyCamp site. Jump in and let's talk. And with PyCon rapidly approaching, we'd like to meet face-to-face with kindred spirits there. I'll make sure it gets on the conference schedule. Jeff Rush Python Advocacy Coordinator Dallas-Ft. Worth Pythoneers Coordinator PyCon 2007 Co-Chair From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 16:54:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 22:54:40 +0100 Subject: Sorting a list In-Reply-To: References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> <45c254a2$0$674$426a34cc@news.free.fr> Message-ID: <45c25aa7$0$25086$426a34cc@news.free.fr> Steven Bethard a ?crit : > Bruno Desthuilliers wrote: > >> If you want to prevent this from happening and don't mind creating a >> copy of the list, you can use the sorted() function with the key and >> reverse arguments and operator.itemgetter: >> (snip) > > You don't need to use sorted() -- sort() also takes the key= and > reverse= arguments:: > Yeps - thanks for the reminder. From kyosohma at gmail.com Wed Feb 28 14:59:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 28 Feb 2007 11:59:56 -0800 Subject: Importing WMI in a child Thread throws an error In-Reply-To: References: <1172602368.563302.160060@t69g2000cwt.googlegroups.com> Message-ID: <1172692796.192098.300590@h3g2000cwc.googlegroups.com> On Feb 27, 3:32 pm, Tim Golden wrote: > kyoso... at gmail.com wrote: > > The problem I have is that since I import WMI, it takes a long time > > and we have users complaining about it. So I stuck the import > > statement into a separate thread and set it to a daemon so it could do > > its thing in the background and the rest of the script would finish > > and exit. > > Two things: > > 1) If you run WMI in a thread, you'll need to call > pythoncom.CoInitialize first: > > > import pythoncom > import wmi > > pythoncom.CoInitialize () > c = wmi.WMI () > # > # do things > # > pythoncom.CoUninitialize () > > > 2) If you need a bit of speed running WMI, see the post > I sent a few days ago to someone else: > > http://mail.python.org/pipermail/python-win32/2007-February/005550.html > > TJG Thanks! This works for my problem. It appears to cut the real time required for my script to run by 30-50%. I tried to figure out how to apply your answer to the other fellow, but I am actually querying WMI for the amount of RAM and the CPU type and I just don't see how to use your example in these cases. I am new to the WMI paradigm. Thanks again, Mike From http Thu Feb 22 03:52:03 2007 From: http (Paul Rubin) Date: 22 Feb 2007 00:52:03 -0800 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172103048.160783.309470@l53g2000cwa.googlegroups.com> <12tq4rvmb0ke0a4@corp.supernews.com> Message-ID: <7x1wkizia4.fsf@ruckus.brouhaha.com> Grant Edwards writes: > > print base64.decodestring(open('sambleb.conf', 'r').read()) > It'll only remain obfuscated for about 30 seconds after even a > mildly curious user looks at the file. You could use the mult127 function, self-inverting like its better known but more easily recognized rot13 relative: def mult127(text): return ''.join(map(chr, ((127*ord(c)) % 256 for c in text))) From troy.melhase at gmail.com Wed Feb 28 01:22:45 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Tue, 27 Feb 2007 21:22:45 -0900 Subject: Installing java2python (Newbie) In-Reply-To: <1172642834.634337.26040@p10g2000cwp.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172642834.634337.26040@p10g2000cwp.googlegroups.com> Message-ID: > properly now (error free!! yay) and the j2py script is located under : > C:\Documents and Settings\Ujjal Pathak\Desktop\java2python-0.2\build > \scripts-2.5 that doesn't look right -- it looks like you found what the setup script left behind. what you should look for is j2py in either (a) your python directories or (b) in your system directories. look in c:\python2.5 first. > Meaning under scripts-2.5 folder, there are two files j2py and > jast_print but without any file extension though! correct, they don't have extensions. once you find the real scripts, rename them to include the .py extension. these scripts are meant to run from a prompt, and double-clicking them in the windows file manager won't do any good. From sickcodemonkey at gmail.com Wed Feb 28 16:01:41 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 28 Feb 2007 16:01:41 -0500 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> Message-ID: <2adc542f0702281301w77cf4b84n7b5b4319b02b99a0@mail.gmail.com> Sorry, I forgot to make a change. You will need to change "COMPUTER_NAME" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >>> from win32com.client import GetObject >>> wmiObj = GetObject("winmgmts:\\\\COMPUTER_NAME\\root\\cimv2") >>> diskinfo = wmiObj.ExecQuery("Select * from Win32_LogicalDisk") >>> for disk in diskinfo: ... print disk.Name, disk.FreeSpace On 28 Feb 2007 12:26:31 -0800, kevinliu23 at gmail.com wrote: > > HI, > > I am new to Python and wanted to know how to check for the remaining > disk space on my Windows machine using Python? I was thinking of using > the command line "dir" and trying to extract the output from there. > But I'm not sure how to extract command line strings using Python > either. > > Anyway help would be appreciated. :) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVEME.cybersource.com.au Thu Feb 15 01:23:06 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 17:23:06 +1100 Subject: Method overloading? References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <1171519115.463977.220700@j27g2000cwj.googlegroups.com> Message-ID: On Wed, 14 Feb 2007 21:58:35 -0800, Paul McGuire wrote: > No, Python does not do overloading as part of the language, you have > to do the variable argument interpretation for yourself. > > For instance, if you want a method to accept a single argument of > various types, it would look something like this: > > def multiAccept( argOfVariousTypes ): > if isinstance(argOfVariousTypes,int): > # treat like an int > elif isinstance(argOfVariousTypes,float): > # treat like a float > elif isinstance(argOfVariousTypes,(list,tuple)): > # treat like a container Is that really called "overloading"? I've never (knowingly) come across the term being used in that context before. I've always known that as "multiple dispatch" or "polymorphism", depending on whether you or the compiler handles the dispatching. Actually, I tell a lie. I've always know it as "a function that can handle different types of arguments" :) -- Steven D'Aprano From jgrzebyta at NO.gazeta.pl.SPAM Sat Feb 3 16:07:12 2007 From: jgrzebyta at NO.gazeta.pl.SPAM (Jacol) Date: Sat, 03 Feb 2007 21:07:12 +0000 Subject: raise or not to raise [Newbie] References: Message-ID: I understand that author generated exception and than extracted the name of function from the exeption. But is any sens in using exeptions service if we have smthing simpler: just print for example? In my opinion no, it doesn't make sens. Jacek From steven.bethard at gmail.com Tue Feb 20 17:09:53 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 20 Feb 2007 15:09:53 -0700 Subject: Python 3.0 unfit for serious work? In-Reply-To: <1172008387.851412.181530@p10g2000cwp.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> Message-ID: Jay Tee wrote: > Let's see if I can scare up something I wrote about ten years ago on a > now-dead language that I really wanted to use (wound up sticking with > python instead because "it was supported" ;-) > > ======================= > to figure out how to work things. The fact that there are three (or > four depending if you count Linz V4) different Oberon System > implementations, and several different compilers, and even four or > five separate dialects of Oberon with none of them appearing to be > really "official", gives the impression of a fragmented, directionless > development effort, and a probability bordering on 1.0000 that > whatever you try to do will be incompatible with all but a small > subset of what's available (unless you stick to writing small programs > like in the books.) It does not matter if you tell people that this > is not so; something has to clearly stand out as being THE STANDARD > STUFF and all the other stuff as INTERESTING BUT NONTHREATENING SIDE > PROJECTS. The STANDARD STUFF must include a sufficient number of > ========================= Well, the problem of multiple standards shouldn't really apply in the same way to Python. Right now, Python 2.X is the standard. Python 2.6, 2.7 and any later 2.X versions are intended to be transitional versions while the standard is migrating to Python 3.X. At some point, the 2.X line will almost certainly be discontinued. So as a Python programmer, the path is clear. As soon as possible, you should make your code compatible with Python 3.0. That will likely mean taking advantage of some new features in Python 2.6, so "as soon as possible" may still mean many years for projects that need to support older versions of Python. Still, once Python 2.6 is installed everywhere by default, it shouldn't be difficult to start making code compatible with the new standard, Python 3.0. STeVe From aahz at pythoncraft.com Wed Feb 28 00:02:11 2007 From: aahz at pythoncraft.com (Aahz) Date: 27 Feb 2007 21:02:11 -0800 Subject: What is bad with "Relative imports" References: Message-ID: In article , Alexander Eisenhuth wrote: > >PyLint says that "Relative imports" ... are worth to be warned . > >And I ask myself why? http://www.python.org/dev/peps/pep-0328 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From steve at holdenweb.com Sat Feb 10 07:52:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 12:52:37 +0000 Subject: [off-topic] Maximum TCP Server Connections Message-ID: Sorry this question isn't strictly Python-related. Does any one know how many simultaneous TCP connections it's practical to expect a TCP-based server application to support (on the OS of your choice)? I'm looking for the restrictions imposed by the operating environment rather than the application itself. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gregturn at mindspring.com Sat Feb 3 11:20:48 2007 From: gregturn at mindspring.com (gregturn at mindspring.com) Date: 3 Feb 2007 08:20:48 -0800 Subject: Jython In-Reply-To: References: Message-ID: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> On Feb 3, 11:21 am, Boris Ozegovic wrote: > Hi > > Why this doesn't work: > > def go(): > for line in open("bobo.txt", "r"): > print line > > go() > > python FileReader.py: everything ok > jython FileReader.py: > > Traceback (innermost last): > File "FileReader.py", line 6 > File "FileReader.py", line 3 > AttributeError: __getitem__ > > -- > "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa > silovana" Files aren't lists and thus don't have the functions for iteration. Try: def go(): for line in open("bobo.txt", "r").readlines(): print line go() From mfmdevine at gmail.com Wed Feb 14 07:27:39 2007 From: mfmdevine at gmail.com (amadain) Date: 14 Feb 2007 04:27:39 -0800 Subject: replacing substrings within strings In-Reply-To: <53gcsbF1sbe8oU1@mid.uni-berlin.de> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> <53gcsbF1sbe8oU1@mid.uni-berlin.de> Message-ID: <1171456059.848396.42270@m58g2000cwm.googlegroups.com> On Feb 14, 12:16 pm, "Diez B. Roggisch" wrote: > amadain wrote: > > Hi > > I was wondering if there was a nicer way to swap the first 2 > > characters in a string with the 4th and 5th characters other than: > > > darr=list("010203040506") > > aarr=darr[:2] > > barr=darr[4:6] > > darr[:2]=barr > > darr[4:6]=aarr > > result="".join(darr) > > > The above code works fine but I was wondering if anybody had another > > way of doing this? > > You can do it like this: > > darr=list("010203040506") > darr[:2], darr[4:5] = darr[4:6], darr[:2] > result="".join(darr) > print result > > Diez Thats the same code. I was wondering if the string manipulation can be done without an excursion into the list world. A From paul at boddie.org.uk Fri Feb 2 07:25:49 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Feb 2007 04:25:49 -0800 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <1170419149.496098.44180@q2g2000cwa.googlegroups.com> On 2 Feb, 04:56, Ben Finney wrote: > > A bug report should be sent to the bug tracker for the software > against which you're reporting a bug. Only at that point does it > become something on which you can comment about attitude toward bug > reports, because before that point the bug report doesn't exist in a > useful form. I think it's also worth considering various social factors when filing bug reports. Whilst a report sent directly to the developers of a particular module might ultimately be the way to get bugs fixed "permanently", it is also worth investigating whether there are any other parties affected by those bugs, whether bugs have been filed in other places (eg. in a Linux distribution's bug tracker), and whether there are communities who have an interest in fixing the bugs in a more timely fashion. I see this kind of thing every now and again with projects like KDE. Often, in a distribution, the version of KDE won't be the absolute latest from kde.org, and the level of interest amongst the original developers to fix bugs in older releases is somewhat restrained. Consequently, I would look to distributions to fix problems with their KDE packages, especially since many of them appear to perform surgery on KDE, often making the resulting software almost unmaintainable by the original developers. Of course, if the bugs are genuine things which are present "upstream" (ie. in the original software) then I'd expect that any fixes ultimately make their way back to the original developers, although various projects (including KDE) seem uninterested even in merging ready-made fixes to older releases unless it involves a major security flaw. Paul From arkanes at gmail.com Mon Feb 26 09:00:12 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 26 Feb 2007 08:00:12 -0600 Subject: a=b change b a==b true?? In-Reply-To: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> References: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> Message-ID: <4866bea60702260600s337bc409s4f30258fcb067733@mail.gmail.com> On 26 Feb 2007 05:50:24 -0800, rstupplebeen at gmail.com wrote: > I do not have a clue what is happening in the code below. > > >>> a=[[2,4],[9,3]] > >>> b=a > >>> [map(list.sort,b)] > [[None, None]] > >>> b > [[2, 4], [3, 9]] > >>> a > [[2, 4], [3, 9]] > > I want to make a copy of matrix a and then make changes to the > matrices separately. I assume that I am missing a fundamental > concept. Any help would be appreciated. > this: >>> b=a does not make a copy. It binds the name b to the same object that is bound to the name a. If you want a copy, ask for a copy. >>> a = [1,2] >>> import copy >>> b = copy.copy(a) #shallow copy >>> a.append(3) >>> a,b ([1, 2, 3], [1, 2]) >>> You may need to do something else depending on exactly what copy semantics you want, read the docs on the copy module. From jonc at icicled.net Mon Feb 5 11:57:52 2007 From: jonc at icicled.net (Jonathan Curran) Date: Mon, 5 Feb 2007 10:57:52 -0600 Subject: No subject In-Reply-To: References: Message-ID: <200702051057.52496.jonc@icicled.net> On Monday 05 February 2007 10:07, Zahid Ahmadzai wrote: > HI THERE > > I NEED HELP WITH THE FOLLOWING EXERSISE CAN YOU PLEASE HELP IF YOU CAN. > > PLEASE SEND ME THE CODE ON E-MAIL > > MANY THANKS > > Quick, everyone, send him the solution to his homework problem! =P From ruka_at_ at fastmail.fm Fri Feb 16 04:47:43 2007 From: ruka_at_ at fastmail.fm (ruka_at_ at fastmail.fm) Date: 16 Feb 2007 01:47:43 -0800 Subject: KeyboardInterrupt not caught Message-ID: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> Hi, why is KeyboardInterrupt not caught (xp)? import sys try: inp = sys.stdin.read() except (KeyboardInterrupt, SystemExit): print "kbd-interr,SystemExit" except EOFError: print "eof encountered" except: print "caught all" self.showtraceback() print "normal end" result after script startet and ^C hit: >ctrl_test.py normal end Traceback (most recent call last): File "C:\work\py_src\ctrl_test.py", line 11, in ? print "normal end" KeyboardInterrupt br Rudi From pwuertz at students.uni-mainz.de Thu Feb 22 12:57:04 2007 From: pwuertz at students.uni-mainz.de (Peter Wuertz) Date: Thu, 22 Feb 2007 18:57:04 +0100 Subject: export an array of floats to python In-Reply-To: References: Message-ID: Travis Oliphant wrote: > Peter Wuertz wrote: >> Hi, >> >> I'm writing a C module for python, that accesses a special usb camera. >> This module is supposed to provide python with data (alot of data). >> Then SciPy is used to fit the data. >> > > Which version of scipy are you using? I'm using ubuntu edgy eft, which ships scipy 0.5.2 > How about creating an array directly from your float array using > PyArray_SimpleNewFromData (the NumPy C-API) or PyArray_FromDimsAndData > (the Numeric C-API). Cool thanks, thats exactly what I needed! From __peter__ at web.de Mon Feb 12 11:56:15 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 12 Feb 2007 17:56:15 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Message-ID: devicerandom at gmail.com wrote: > I am currently using the Cmd module for a mixed cli+gui application. I > am starting to refactor my code and it would be highly desirable if > many commands could be built as simple plugins. > > My idea was: > - Load a list of plugin names (i.e. from the config file, or from the > plugins directory) > - Import all plugins found dynamically: > and this is easy, since I can do, for example: > > PLUGIN_NAMES=['foo', 'bar'] > PLUGIN_MODULES = map(__import__, PLUGIN_NAMES) > PLUGINS = [item.Commands for item in PLUGIN_MODULES] > > Now, what I have to do is to define my command line class. This is > usually done by subclassing cmd.Cmd: > > class MyCli(cmd.Cmd): > .... > > Now I want to add the commands defined in foo.Commands and > bar.Commands. foo.Commands contains the functions corresponding to the > new commands this way: > #foo.py > class Commands > > def do_this(self,args): > ... > def do_that(self,args): > ... > > I've seen I can do it by explicitely import them and using multiple > inheritance: > > class MyCli(cmd.Cmd , foo.Commands, bar.Commands) > .... > > so that do_this and do_that are now methods of a Cmd command line. > > Now: > - how can I instead have MyCli inherit from a dynamic list of modules? > - is there a better way than using multiple inheritance to plug-in > dynamically commands in a Cmd command line? >>> import cmd >>> class Foo: ... def do_this(self, arg): ... print "THIS", arg ... >>> class Bar: ... def do_that(self, arg): ... print "THAT", arg ... >>> plugins = [Foo, Bar] >>> def make_command_class(*bases): ... return type(cmd.Cmd)("MyCli", bases + (cmd.Cmd,), {}) ... >>> cmd = make_command_class(*plugins)() >>> cmd.cmdloop() (Cmd) help Undocumented commands: ====================== help that this (Cmd) that one THAT one (Cmd) Most of the above should be straight-forward. I used type(cmd.Cmd)(name, bases, classdict) instead of just type(name, bases, classdict) because cmd.Cmd is a classic class. The thread "Partial 1.0 - Partial classes for Python" might also be of interest. Peter From garrickp at gmail.com Wed Feb 14 10:32:26 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 14 Feb 2007 07:32:26 -0800 Subject: multi processes In-Reply-To: <1171464784.419065.149140@v45g2000cwv.googlegroups.com> References: <1171464784.419065.149140@v45g2000cwv.googlegroups.com> Message-ID: <1171467145.957828.188780@j27g2000cwj.googlegroups.com> On Feb 14, 7:53 am, "amadain" wrote: > Hi > Heres a poser. I want to start a program 4 times at exactly the same > time (emulating 4 separate users starting up the same program). I am > using pexpect to run the program from 4 separate locations accross the > network. How do I start the programs running at exactly the same time? > I want to time how long it takes each program to complete and to show > if any of the program initiations failed. I also want to check for > race conditions. The program that I am running is immaterial for this > question - it could be mysql running queries on the same database for > example. Using threading, you call start() to start each thread but if > I call start on each instance in turn I am not starting > simultaneously. > A Standard answers about starting anything at *exactly* the same time aside, I would expect that the easiest answer would be to have a fifth controlling program in communication with all four, which can then send a start message over sockets to each of the agents at the same time. There are several programs out there which can already do this. One example, Grinder, is designed for this very use (creating concurrent users for a test). It's free, uses Jython as it's scripting language, and even is capable of keeping track of your times for you. IMO, it's worth checking out. http://grinder.sourceforge.net From skpeterson at nospam.please.ucdavis.edu Sun Feb 11 23:13:20 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 20:13:20 -0800 Subject: How to find all the same words in a text? References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> <1171210571.609726.254260@v33g2000cwv.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com on 11 Feb 2007 08:16:11 -0800 didst step forth and proclaim thus: > More concisely: > > import re > > pattern = re.compile(r'\b324\b') > indices = [ match.start() for match in > pattern.finditer(target_string) ] > print "Indices", indices > print "Count: ", len(indices) > Thank you, this is educational. I didn't realize that finditer returned match objects instead of tuples. > Cheers, > Steven > -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From eric_brunel at despammed.com Wed Feb 7 08:38:13 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 07 Feb 2007 14:38:13 +0100 Subject: ps tkinter References: <1170852030.522393.267140@v33g2000cwv.googlegroups.com> Message-ID: On Wed, 07 Feb 2007 13:40:33 +0100, yvesd wrote: > For a bit more help about my previous message (outlook bar) > does anybody know how to reparent or change a widget(button)'s owner > in tkinter ? > here's my code that doesn't work : > def inverse(self): > if (self.texte=="top"): > self.texte="bottom" > btn = self > btn.pack_forget() > btn.configure(parent = self.top, text=self.texte) > btn.pack(side=TOP,fill=X,expand=1) > else: > self.texte="top" > btn = self > btn.pack_forget() > btn.configure(parent=self.bottom, text=self.texte) > btn.parent = None > btn.pack(side=BOTTOM,fill=X,expand=1) Short answer: you can't. At tcl level, the name for the button contains the name of its parent, and you basically can't rename a button. But, having no idea about what you call an "outlook bar" since I never used outlook in my whole life, another solution may exist, not requiring to "reparent" an existing widget. If you only describe exactly what you're trying to do, someone may be able to provide far better help. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From gibo at gentlemail.com Wed Feb 21 21:46:51 2007 From: gibo at gentlemail.com (GiBo) Date: Thu, 22 Feb 2007 15:46:51 +1300 Subject: guess file type in python In-Reply-To: References: Message-ID: <45DD041B.9030005@gentlemail.com> mark wrote: > Is there any way to guess the file type using python? > thanks > mark > > For example in unix: > > file code.py > code.py: a python script text executable > > file Eccentric.gif > Eccentric.gif: GIF image data, version 89a, 237 x 277 "file" tool uses libmagic.so library which in turn uses /etc/magic file with file format descriptions. To get some reliable results you'll have to call libmagic. The "file-4.xx.tar.gz" source tarball has python bindings included and there's a python-magic package (at least in Debian) that provides libmagic bindings for python. HTH, GiBo From markbpan at mailinator.com Mon Feb 19 17:51:29 2007 From: markbpan at mailinator.com (Mark) Date: 19 Feb 2007 22:51:29 GMT Subject: PyDev on Mac References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> Message-ID: <45da29f1$0$13737$5a62ac22@per-qv1-newsreader-01.iinet.net.au> On Sun, 18 Feb 2007 10:50:37 +0100, Diez B. Roggisch wrote: > Just wait until my crystal ball comes back from the cleaners, and I > will start looking at your problem. > > As you can lay back and do nothing while that happens, I suggest you > take this highly entertaining read: Now that is an entertaining twist to the standard "RTFM" response! Hadn't seen that one before. From bg_ie at yahoo.com Thu Feb 22 03:59:29 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 22 Feb 2007 00:59:29 -0800 Subject: Finding a tuple in a tuple Message-ID: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> Hi, Lists say I have the following tuple - t1 = ("ONE","THREE","SIX") and then the following tuples - t2 = ("ONE","TWO","THREE") t3 = ("TWO","FOUR","FIVE","SIX") t4 = ("TWO",) t5 = ("TWO","FIVE") What I want to do is return true if any member of tuple t1 is found in the remaining tuples. Therefore - 2) ("ONE","TWO","THREE") : TRUE 3) ("TWO","FOUR","FIVE","SIX") : TRUE 4) ("TWO",) FALSE 5) ("TWO","FIVE") How do I do this? Cheers, Barry. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 5 11:47:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 05 Feb 2007 17:47:01 +0100 Subject: Count nb call of a function, without global var or decorator References: <45c75b0f$0$5090$ba4acef3@news.orange.fr> Message-ID: <52p5c5F1p0r0cU1@mid.individual.net> M?ta-MCI wrote: > Example, with meta-data (attributs of function) : Apart from asking what counting "nb call" of a function means, I wonder why you didn't use an iterator? > @-salutations @-less Regards, Bj?rn -- BOFH excuse #65: system needs to be rebooted From fredrik at pythonware.com Wed Feb 28 09:49:23 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Feb 2007 15:49:23 +0100 Subject: msvcr71.dll References: <8c7f10c60702280223s7a2059b6gdaa69169c5209573@mail.gmail.com> Message-ID: Simon Brunning wrote: >> Are there news about the impossibility of redistributing msvcr71.ddl >> with own stand-alone application written in python for who doesn't have >> MSVC7 license? > > Last I heard the consensus was that it's OK to distribute msvcr71.ddl. > But IANAL, and neither is anyone else that I've heard discussing the > matter. it is perfectly okay to include the Microsoft DLL if you're redistributing a Python build downloaded from python.org (since it's built with a properly licensed com- piler). From bdesth.quelquechose at free.quelquepart.fr Tue Feb 6 16:28:09 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 22:28:09 +0100 Subject: Missing member In-Reply-To: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> References: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> Message-ID: <45c8ebcb$0$1026$426a74cc@news.free.fr> Mizipzor a ?crit : > I have some troubles with a member variable that seems to be missing > in a class. In short, heres what I do; class A is the parent class, B > inherits from A and C inherits from B (hope I used the right words > there). Now, I create an instance of C, which calls A's __init__ which > in turn creates all the member variables. Then I call C.move() (a > function defined in A), but then, one of the variables seems to have > become 'NoneType'. > > The code can be found here (Ive taken away unnecessery stuff): > http://pastebin.com/875394 > > The exact error is (which occur on line 15 in the pasted code): > TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' Alas, there's a dependency on an unknown class or function vector (which I presume lives in the eponym module), so we just can guess that the call to vector() at line 8 returned None. IOW, the problem is elsewhere... > Any comments are welcome. :) You ask for it, you get it: import pygame, math from pygame.locals import * => bad style import tilemap, dataManager from vector import * => idem class _BaseEntity: => class _BaseEntity(object): def __init__(self, type, x, y): self._direction = vector() self.pos = vector(x,y) self.stats = dataManager.getEntityStats(type) self.hp = self.stats.maxHp # todo: make all atttributes local def move(self): """ moves the entity in its direction according to its speed """ self.pos += (self._direction * self.stats.speed) def setDirection(self, point, y = None): """ sets the direction to point, and normalises it if y is specifed, "point" is expected to be x, otherwise, "point" is expected to be a vector class """ # make a vector if not y == None: => if y is not None: point = vector(point, y) self._direction = point.normalise() #def lookAt(self, point, y = None): # """ changes the angle so the entity "looks" at the specified coords # if y is specifed, "point" is expected to be x, # otherwise, "point" is expected to be a vector class """ # # make a vector # if not y == None: # point = vector(point, y) => code duplication, should be factored out # vec = vector(point.x - self.posx, point.y - self.posy) # vec.normalise() # # angle = math.degrees(math.asin(vec.y)) # print angle def draw(self, targetSurface): """ blits the entire stats.image onto the targetSurface at the ent's coords """ targetSurface.blit(self.stats.image, (self.pos.x,self.pos.y)) class Entity(_BaseEntity): def __init__(self, type, x = 0, y = 0): _BaseEntity.__init__(self, type, x, y) => You don't need to override the __init__ method if it's just to call the superclass's __init__ with the same args... (snip) From sickcodemonkey at gmail.com Wed Feb 28 20:10:11 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 28 Feb 2007 20:10:11 -0500 Subject: text wrapping help In-Reply-To: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> References: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> Message-ID: <2adc542f0702281710u15557305n13924021b1f4580c@mail.gmail.com> I am not certain if I understand your problem, but I think you are just trying to read in a string and create a visable matrix. If that is true, then may some of the code below will work. This is in no way elegant. ++++++++++++++++++++++++++++++++++++++++++ count = 1 width = 2 #the width of your matrix string="aaaaaaaaaa" #input string to piece up final="" #output string for character in string: if count == width : final = "%s%s\n" % (final,character) count = 1 else: final = "%s%s" % (final,character) count += 1 print final On 28 Feb 2007 16:06:08 -0800, Ryan K wrote: > > I'm trying to text wrap a string but not using the textwrap module. I > have 24x9 "matrix" and the string needs to be text wrapped according > to those dimensions. Is there a known algorithm for this? Maybe some > kind of regular expression? I'm having difficulty programming the > algorithm. Thanks, > Ryan > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From m.yanowitz at kearfott.com Thu Feb 1 15:51:19 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 1 Feb 2007 15:51:19 -0500 Subject: division by 7 efficiently ??? In-Reply-To: <1170361512.204099.191740@a75g2000cwd.googlegroups.com> Message-ID: <000001c74642$b95a57c0$0d7d12ac@kearfott.com> I think it is off by 1 in small numbers, off by a little more with large numbers: >>> def div7 (N): ... return (N>>3) + ((N-7*(N>>3))>>3) ... >>> div7 (70) 9 >>> div7 (77) 10 >>> div7 (700) 98 >>> div7 (7) 0 >>> div7 (10) 1 >>> div7 (14) 1 >>> div7 (21) 2 >>> div7 (700) 98 >>> div7 (7000) 984 Michael Yanowitz -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Krypto Sent: Thursday, February 01, 2007 3:25 PM To: python-list at python.org Subject: Re: division by 7 efficiently ??? The correct answer as told to me by a person is (N>>3) + ((N-7*(N>>3))>>3) The above term always gives division by 7 -- http://mail.python.org/mailman/listinfo/python-list From gagsl-py at yahoo.com.ar Fri Feb 16 23:56:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 01:56:49 -0300 Subject: how to use Dispatch to open an application in win32com.client References: <1171679786.355275.191860@h3g2000cwc.googlegroups.com> Message-ID: En Fri, 16 Feb 2007 23:36:26 -0300, vithi escribi?: > I am trying to launch an application. When I try like that > When I try like that Excel is opening > import win32com.client > object = win32com.client.Dispatch("Excel.Application") > object.Visible = 1 > > But when I try my application which is QeepIt.exe > which is in the c:\ drive it is not running > Any body tell me how to give path to open an exectable application in > Dispatch modules > I try like that > object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") > It give an error. The above code is used to launch a COM server registered under the name "Excel.Application" and then control it. If you don't know what a COM server is, surely your application can't be used this way. For launching another program, perhaps sending it some text, and capturing its output, look at the subprocess module. If you are only interested in executing it, with no additional communication, os.system() may be enough. -- Gabriel Genellina From domingo.aguilera at gmail.com Thu Feb 22 13:22:24 2007 From: domingo.aguilera at gmail.com (batok) Date: 22 Feb 2007 10:22:24 -0800 Subject: JasperServer Message-ID: <1172168543.975485.238770@a75g2000cwd.googlegroups.com> JasperServer is a report engine ( java based ). It has a soap interface. Does anybody has used Jasperserver via Soap ? An example would be appreciated. From casevh at comcast.net Fri Feb 23 15:00:10 2007 From: casevh at comcast.net (casevh at comcast.net) Date: 23 Feb 2007 12:00:10 -0800 Subject: Rational numbers In-Reply-To: <1172255683.114085.217310@m58g2000cwm.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> Message-ID: <1172260810.779025.135670@j27g2000cwj.googlegroups.com> On Feb 23, 10:34 am, "mensana... at aol.com" wrote: > On Feb 23, 10:39 am, Martin Manns wrote: > > > On Fri, 23 Feb 2007 09:52:06 -0600 > > > Larry Bates wrote: > > > I quick search of Google turned up: > > > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p... > > >http://calcrpnpy.sourceforge.net/clnum.html > > >http://gmpy.sourceforge.net/ > > > Sorry that I did not point these out initially. > > > + clnum seems to be slower and for speed may be compiled to wrap gmp so > > that it is just an additional layer between python and gmp . > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of > > cvs 10 months ago). I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex has not updated cvs with the fix. gmpy 1.04a compiles cleanly with the latest releases of Python and GMP, so I consider it stable. > > Actually, gmpy is being maitained even if SourceForge isn't up to > date. > > I got my gmpy 1.04a for Python 2.5 Windows binary from > > > > I haven't used the rationals all that much, but been very > happy with them when I have. > casevh From ziga.seilnacht at gmail.com Mon Feb 26 18:51:59 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 26 Feb 2007 15:51:59 -0800 Subject: pickle problem - frexp() out of range In-Reply-To: <1172529903.332360.124400@z35g2000cwz.googlegroups.com> References: <1172529903.332360.124400@z35g2000cwz.googlegroups.com> Message-ID: <1172533918.957031.256290@a75g2000cwd.googlegroups.com> ahaldar wrote: > Hi: > > I have some large data structure objects in memory, and when I attempt > to pickle them, I get the following error: > > SystemError: frexp() out of range > > Are there some objects that are just too large to serialize, and if > so, is there an easy workaround without breaking up the object and > reconstructing it during deserialization? > > Here's the code I use to pickle the object: > > f = open(dir+file, "w+b") > pickle.dump(structure, f, protocol=2) # throws error > f.close() > > - abhra You are probably trying to pickle Inf or NaN. This was fixed in Python 2.5, see this revision: http://svn.python.org/view?rev=38893&view=rev and this patch: http://www.python.org/sf/1181301 Ziga From vishal at veriwave.com Sat Feb 3 06:13:04 2007 From: vishal at veriwave.com (vishal at veriwave.com) Date: Sat, 3 Feb 2007 03:13:04 -0800 (PST) Subject: HELP NEEDED ... Regd. Regular expressions PyQt Message-ID: <50725.71.109.230.173.1170501184.squirrel@mail.veriwave.com> Hello All: I am trying to work out a regular expression in a PyQt environment for time in hh:mm:ss format. Any suggestions? Thanks, Vishal From rschroev_nospam_ml at fastmail.fm Sat Feb 17 04:21:51 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 17 Feb 2007 09:21:51 GMT Subject: HTTP_REFERER value In-Reply-To: <1171701486.540940.151990@h3g2000cwc.googlegroups.com> References: <1171701486.540940.151990@h3g2000cwc.googlegroups.com> Message-ID: Johny schreef: > Is HTTP_REFERER value transfered between different domains? > For example if I come to a website , say, www.python.org, from > website www.microsoft.com > will www.python.org finds that I came there from www.microsoft.com? If you get from www.microsoft.com to www.python.org by clicking a link on Microsoft's website, yes. If you get to www.python.org by manually typing in the URL or by using a bookmark, no. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mituller at gmail.com Sat Feb 10 18:07:43 2007 From: mituller at gmail.com (mtuller) Date: 10 Feb 2007 15:07:43 -0800 Subject: HTML Parsing Message-ID: <1171148863.807386.310960@h3g2000cwc.googlegroups.com> Alright. I have tried everything I can find, but am not getting anywhere. I have a web page that has data like this: LETTER 33,699 1.0 What is show is only a small section. I want to extract the 33,699 (which is dynamic) and set the value to a variable so that I can insert it into a database. I have tried parsing the html with pyparsing, and the examples will get it to print all instances with span, of which there are a hundred or so when I use: for srvrtokens in printCount.searchString(printerListHTML): print srvrtokens If I set the last line to srvtokens[3] I get the values, but I don't know grab a single line and then set that as a variable. I have also tried Beautiful Soup, but had trouble understanding the documentation, and HTMLParser doesn't seem to do what I want. Can someone point me to a tutorial or give me some pointers on how to parse html where there are multiple lines with the same tags and then be able to go to a certain line and grab a value and set a variable's value to that? Thanks, Mike From gagsl-py at yahoo.com.ar Sat Feb 3 04:54:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Feb 2007 06:54:36 -0300 Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" References: Message-ID: En Sat, 03 Feb 2007 06:12:33 -0300, Peter Otten <__peter__ at web.de> escribi?: > John Nagle wrote: > >> How do I suppress "DeprecationWarning: Old style callback, use >> cb_func(ok, >> store) instead". A library is triggering this message, the library is >> being fixed, but I need to make the message disappear from the output >> of a >> CGI program. > > import warnings > warnings.filterwarnings("ignore", message="Old style callback, use > cb_func(ok, store) instead") Or you can be more aggressive and filter out all DeprecationWarnings: warnings.simplefilter("ignore",DeprecationWarning) (same as using option -Wignore::DeprecationWarning on the python command line) -- Gabriel Genellina From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 11:50:15 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 17:50:15 +0100 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: Thinker wrote: > zefciu wrote: >>> I am trying to embed a c function in my python script for a first >>> time. When I try to call it I get an error >>> >>> SystemError: new style getargs format but argument is not a tuple >>> >>> Guido said on some mailing list, that it is probably an effect of >>> the lack of METH_VARARGS in the functions' array, but it's ok in my >>> source code. Here is the full code: > Is coord always tuple? Yes it is. The script launches it with tuple and two numeric arguments. On the other hand when I try it in interactive mode with mandelpixel((1,1), 1, 1) it segfaults, which I completely don't understand. zefciu From lbates at websafe.com Mon Feb 26 17:23:30 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 26 Feb 2007 16:23:30 -0600 Subject: design question: no new attributes In-Reply-To: <8BIEh.1349$QI4.489@trnddc01> References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: <6ZadneKLjYxJwH7YnZ2dnUVZ_ubinZ2d@comcast.com> Alan Isaac wrote: > I have a class whose instances should only receive attribute > assignments for attributes that were created at inititialization. > If slots are not appropriate, what is the Pythonic design for this? > > Thanks, > Alan Isaac > > My understanding of "Pythonic design" is not to worry about it. If users want to set attributes that won't accomplish anything productive (within your class) let them. -Larry From jakub.stolarski at gmail.com Thu Feb 22 05:56:34 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 22 Feb 2007 02:56:34 -0800 Subject: PLY for standard library In-Reply-To: <1172089673.964842.7810@v45g2000cwv.googlegroups.com> References: <1172062961.384337.295280@j27g2000cwj.googlegroups.com> <1172089673.964842.7810@v45g2000cwv.googlegroups.com> Message-ID: <1172141793.931517.271150@s48g2000cws.googlegroups.com> On 21 Lut, 21:27, "Paul McGuire" wrote: > Other candidates besides PLY:http://www.nedbatchelder.com/text/python-parsers.htmlhttp://wiki.python.org/moin/LanguageParsing > > I'm not sure this is a "one size fits all" problem space. > > Personally I find PLY's use of docstrings for grammar definition a bit > too clever (as I'm sure others have their own personal likes and > dislikes on any of these packages, even (gasp) pyparsing). > I tried some other packages too. PLY was the most suitable for me, but there are many much more powerful tools. If there will be any other parsing tool in standard library that's OK. But I think that python needs some standard parsing tool. -- Jakub Stolarski From deets at nospam.web.de Mon Feb 26 08:58:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Feb 2007 14:58:34 +0100 Subject: a=b change b a==b true?? References: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> Message-ID: <54g7caF20tq1uU1@mid.uni-berlin.de> rstupplebeen at gmail.com wrote: > I do not have a clue what is happening in the code below. > >>>> a=[[2,4],[9,3]] >>>> b=a >>>> [map(list.sort,b)] > [[None, None]] >>>> b > [[2, 4], [3, 9]] >>>> a > [[2, 4], [3, 9]] > > I want to make a copy of matrix a and then make changes to the > matrices separately. I assume that I am missing a fundamental > concept. Any help would be appreciated. You are missing that the operation b=a is not a copying, but a mere name-binding. The object that a points to now is also pointed at by b. If you need copies, use the copy-module, with it's method deepcopy. Diez From mitko at qlogic.com Thu Feb 15 19:18:51 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Thu, 15 Feb 2007 16:18:51 -0800 Subject: Python's freeze.py utility Message-ID: <20070215161851.3d6bf2fc@opal.pathscale.com> OK, this might be a stupid question: for the life of me, I can't find Python's freeze.py utility in the Python distribution that comes with FC6. Has it been removed from the distribution? Has it been removed from Python? I have FC6's python-2.4.4 rpms installed (python, python-devel, python-tools, etc) and the script is neither in /usr/lib/python-2.4/Tools or /usr/lib/python-2.4/Demos Thanks for your help! -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== Help me, I'm a prisoner in a Fortune cookie file! From robin at reportlab.com Wed Feb 21 06:49:06 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 21 Feb 2007 11:49:06 +0000 Subject: BDFL in wikipedia In-Reply-To: <1172053544.515756.28200@v45g2000cwv.googlegroups.com> References: <1172053544.515756.28200@v45g2000cwv.googlegroups.com> Message-ID: <45DC31B2.6050809@chamonix.reportlab.co.uk> Carl Banks wrote: ...... > > Since when is Larry Wall benevolent? He should be called the SDFL. > ..... even the great leader has been referred to as the MDFL :) most language designers get to do it once and then recognize the result as either beneficial or otherwise. The alternative is a constantly changing language without any clear goal or endpoint. That's fine for some not for others. -- Robin Becker From gandalf at designaproduct.biz Tue Feb 13 12:40:20 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 13 Feb 2007 18:40:20 +0100 Subject: _ssl.pyd is buggy? In-Reply-To: References: Message-ID: <45D1F804.8050609@designaproduct.biz> > I was using _ssl.pyd to upload files to DAV server over ssl and > found it to be a problem. I upgraded to Python 2.5 and the problem > was fixed. I don't know if it is the same problem that is affecting > you, but I couldn't get it to work on 2.4. > > FYI, Larry > I just installed Python 2.5 and now I do not get the error message in the event log. But the service still cannot be stopped and does not log anything. I'm using the logging module and RotatingFileHandler, so the service should start logging into a new file immediately after startup. According to the event log, the service is started, but it does nothing. If I start the same program as an application, it works fine. The program only uses the standard lib. Any ideas, what can be the problem? Thanks, Laszlo From free.condiments at gmail.com Tue Feb 13 18:26:46 2007 From: free.condiments at gmail.com (Sam) Date: Tue, 13 Feb 2007 23:26:46 +0000 Subject: c++ for python programmers In-Reply-To: References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: On 13 Feb 2007 17:51:00 GMT, Jorgen Grahn wrote: > Well, C++ is a better language than C in many ways. So, if he needs to learn > one of them, why does it have to be C? > > Another reason some people choose C++ over Python for some tasks is that > they feel that larger programs benefit from strong, static type checking. > I like both ways, but depending on the task, one or the other is better. C++ is -not- strongly typed. You can cast anything to void *, and manipulate it in ways unimaginable. Plus there's the whole mess that is pointer arithmetic and a weak typesystem... Disclaimer: I am unashamedly in the "C++ Is Evil" camp, and wholly believe that if you want proper strong, static type checking, use Haskell, or if you want proper, complete object-orientation (C++'s primitive types compromise its object system's integrity, and I believe I've already discussed casting and pointers), use Python, and if you want under-the-hood pointer-fu, use C. --Sam From boris.smirnov at gmail.com Tue Feb 27 04:47:00 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 27 Feb 2007 01:47:00 -0800 Subject: Interactive os.environ vs. os.environ in script In-Reply-To: References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> <1172562212.691747.150310@m58g2000cwm.googlegroups.com> <1172566324.278334.284760@s48g2000cws.googlegroups.com> Message-ID: <1172569620.033838.315920@p10g2000cwp.googlegroups.com> On Feb 27, 10:33 am, Peter Otten <__pete... at web.de> wrote: > boris.smir... at gmail.com wrote: > > On Feb 27, 9:31 am, Peter Otten <__pete... at web.de> wrote: > >> boris.smir... at gmail.com wrote: > >> > Is there another possibility of how to solve it just by adding some > >> > lines in script? > > >> I think you have to wrap your script in a shell script > > >> #!/bin/sh > >> export LD_LIBRARY_PATH=/path/Linux/rh_linux > >> python shrink_bs_070226.py > > >> To avoid that you can have the python script invoke itself, e. g.: > > >> #!/usr/bin/env python > >> import os > >> if os.environ.get("YADDA") != "whatever": > >> print "fix environment" > >> os.environ["YADDA"] = "whatever" > >> os.system("yadda.py") > >> raise SystemExit > > >> print "YADDA is now %r" % os.environ["YADDA"] > >> print "do your real stuff" > > >> Peter > > > Thanks for the reply. > > > If I that good understood I did this: > > ********************************** > > import sys, re, glob, shutil > > import os > > > if os.environ["LD_LIBRARY_PATH"].count('/path/Linux/rh_linux') !=1: > > os.environ["LD_LIBRARY_PATH"]=os.environ["LD_LIBRARY_PATH"]+':'+'/ > > path/Linux/rh_linux' > > os.system("shrink_bs_070226.py") > > raise SystemExit > > > from qt import * > > *********************** > > > Is that correct. If yes then it not works. If not then, what's wrong? > > I don't know. You are not quoting the actual code you are using (from qt > import * is definitely not in line 29, and the #!/path/to/your/python is > missing). Do you have more than one python version installed? then you may > have to put > > #!/usr/bin/python2.2 > > or similar in the first line of your script. > > Peter- Hide quoted text - > > - Show quoted text - Probably I understood it not correctly. What did you mean was to put that code into my python script "shrink_bs_070226.py" and then calls script itself? So I took my script "shrink_bs_070226.py" and it starts with: ********************************** #!/usr/bin/env python import sys, re, glob, shutil import os then I put your code in that script if os.environ["LD_LIBRARY_PATH"].count('/path/Linux/rh_linux') !=1: os.environ["LD_LIBRARY_PATH"]=os.environ["LD_LIBRARY_PATH"]+':'+'/ path/Linux/rh_linux' os.system("shrink_bs_070226.py") raise SystemExit and here continues my script: from qt import * ..... *********************** Is it correct? BTW: On lines 3:18 I have comments, script description and modifications, therefore is "from qt import *" on the line 29 From sturlamolden at yahoo.no Thu Feb 8 12:13:34 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 8 Feb 2007 09:13:34 -0800 Subject: Does the world need another v0.1 python compiler? In-Reply-To: <1170918215.074099.262930@p10g2000cwp.googlegroups.com> References: <1170918215.074099.262930@p10g2000cwp.googlegroups.com> Message-ID: <1170954814.417840.64810@l53g2000cwa.googlegroups.com> On Feb 8, 8:03 am, "Kay Schluehr" wrote: > This code generation for an arbitrary backend sounds more like an > appropriate task for PyPy. I think Grant's or anyone elses compiler > could be a viable tool for augmenting the CPython interpreter in > particular in the presence of optional type annotations in Py3K. IMHO, with the presence of static types in Py3K, we should have a static compiler that can be invoked dynamically, just like Common Lisp. Something like def foo(...): bar = static_compile(foo, optimize=2) bar(...) JIT compilers are hyped, static compilers perform much better. This way the programmer can decide what needs to be compiled. This is the reason why CMUCL can compete with most C compilers. From simon at brunningonline.net Fri Feb 23 12:18:39 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 23 Feb 2007 17:18:39 +0000 Subject: c_string missing from ctypes? In-Reply-To: <1172250201.092615.52940@s48g2000cws.googlegroups.com> References: <1172250201.092615.52940@s48g2000cws.googlegroups.com> Message-ID: <8c7f10c60702230918v2f89a824t60a10b8b5803239d@mail.gmail.com> On 23 Feb 2007 09:03:21 -0800, Jacob Rael wrote: > I was following along with this site: > > http://www.brunningonline.net/simon/blog/archives/000659.html You don't want to be messing around with that old rubbish. I should know - I wrote it. Instead, take a look at . > In [9]: import ctypes > In [10]: dir(ctypes.c_string) > --------------------------------------------------------------------------- > Traceback (most recent call > last) > : 'module' object has no attribute > 'c_string' I think that c_string has been replaced by c_buffer in recent versions of ctypes. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Thu Feb 15 20:19:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 20:19:15 -0500 Subject: filecmp.cmp() cache In-Reply-To: References: <1171554885.517477.316470@s48g2000cws.googlegroups.com> <1171577045.892167.46580@p10g2000cwp.googlegroups.com> Message-ID: Peter Otten wrote: > Mattias Br?ndstr?m wrote: > >> On Feb 15, 5:56 pm, Peter Otten <__pete... at web.de> wrote: >>> You can clear the cache with >>> >>> filecmp._cache = {} >>> >>> as a glance into the filecmp module would have shown. >> You are right, a quick glance would have enlighten me. Next time I >> will RTFS first. :-) >> >>> If you don't want to use the cache at all (untested): >>> >>> class NoCache: >>> def __setitem__(self, key, value): >>> pass >>> def get(self, key): >>> return None >>> filecmp._cache = NoCache() >>> >> Just one small tought/question. How likely am I to run into trouble >> because of this? I mean, by setting _cache to another value I'm >> mucking about in filecmp's implementation details. Is this generally >> considered OK when dealing with Python's standard library? > > I think it's a feature that Python lends itself to monkey-patching, but > still there are a few things to consider: > > - Every hack increases the likelihood that your app will break in the next > version of Python. > - You take some responsibility for the "patched" code. It's no longer the > tried and tested module as provided by the core developers. > - The module may be used elsewhere in the standard library or third-party > packages, and failures (or in the above example: performance degradation) > may ensue. > > For a script and a relatively obscure module like 'filecmp' monkey-patching > is probably OK, but for a larger app or a module like 'os' that is heavily > used throughout the standard lib I would play it safe and reimplement. > It would probably be a good idea to add a clear_cache() function to the module API for 2.6 to avoid such issues. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From Alessandro.Fachin at gmail.com Sun Feb 4 15:22:11 2007 From: Alessandro.Fachin at gmail.com (Alessandro Fachin) Date: Sun, 04 Feb 2007 21:22:11 +0100 Subject: Create a cookie with cookielib References: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> <45c59494$0$36013$4fafbaef@reader4.news.tin.it> <87zm7travc.fsf@pobox.com> Message-ID: <45c64070$0$21786$4fafbaef@reader2.news.tin.it> John J. Lee wrote: > Fine, but see my other post -- I think you misunderstand how cookies > work. Maybe you misunderstand me... While i wrote "cookie are simply http header :)" i want to said that i've look at wrong thing, cookielib are not needed... Anyway thank you for help, regards. From gagsl-py at yahoo.com.ar Sat Feb 10 18:36:38 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 20:36:38 -0300 Subject: Question about strftime References: <1171139392.261505.9350@l53g2000cwa.googlegroups.com> Message-ID: En Sat, 10 Feb 2007 17:29:52 -0300, escribi?: > I have question about strftime. I am trying to print the current time > in this format: > > date = strftime("%Y%m%d_%H%M%S", gmtime()) > print date > > I run the script at 2:18 pm, but I get this: 20070210_201837 > > Can you please tell me why I get '20'? instead of '14' (which is 2:00 > pm)? gmtime() returns the time in UTC, not local time, and your computer thinks you're in Mexico, central USA or Canada. -- Gabriel Genellina From http Sun Feb 4 15:35:09 2007 From: http (Paul Rubin) Date: 04 Feb 2007 12:35:09 -0800 Subject: Learning to program in Python References: <1168028517.005902.172880@11g2000cwr.googlegroups.com> Message-ID: <7x1wl5oe4i.fsf@ruckus.brouhaha.com> "jbchua" writes: > I am an Electrical Engineering major and have dabbled in several > languages such as Python, C, and Java in my spare time because of my > interest in programming. However, I have not done any practical > programming because I have no idea where to get started. I taught > myself these languages basically by e-tutorials and books. This makes > me feel as if I don't really know how to implement these languages. > Does anybody have any advice on where to start applying my limited > knowledge practically in order to advance my learning? Try http://www.diveintopython.org . If you want something more academic about programming in general, try http://mitpress.mit.edu/sicp/ From sjmachin at lexicon.net Tue Feb 20 18:15:18 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 15:15:18 -0800 Subject: Regex Speed In-Reply-To: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> Message-ID: <1172013317.943062.303110@t69g2000cwt.googlegroups.com> On Feb 21, 8:29 am, garri... at gmail.com wrote: > While creating a log parser for fairly large logs, we have run into an > issue where the time to process was relatively unacceptable (upwards > of 5 minutes for 1-2 million lines of logs). In contrast, using the > Linux tool grep would complete the same search in a matter of seconds. > > The search we used was a regex of 6 elements "or"ed together, with an > exclusionary set of ~3 elements. What is an "exclusionary set"? It would help enormously if you were to tell us what the regex actually is. Feel free to obfuscate any proprietary constant strings, of course. > Due to the size of the files, we > decided to run these line by line, I presume you mean you didn't read the whole file into memory; correct? 2 million lines doesn't sound like much to me; what is the average line length and what is the spec for the machine you are running it on? > and due to the need of regex > expressions, we could not use more traditional string find methods. > > We did pre-compile the regular expressions, and attempted tricks such > as map to remove as much overhead as possible. map is a built-in function, not a trick. What "tricks"? > > With the known limitations of not being able to slurp the entire log > file into memory, and the need to use regular expressions, do you have > an ideas on how we might speed this up without resorting to system > calls (our current "solution")? What system calls? Do you mean running grep as a subprocess? To help you, we need either (a) basic information or (b) crystal balls. Is it possible for you to copy & paste your code into a web browser or e-mail/news client? Telling us which version of Python you are running might be a good idea too. Cheers, John From nogradi at gmail.com Mon Feb 26 09:04:32 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 26 Feb 2007 15:04:32 +0100 Subject: [OT] python notation in new NVIDIA architecture In-Reply-To: References: Message-ID: <5f56302b0702260604m63d45a48m1c6d83cf29639ba8@mail.gmail.com> > > Something funny: > > > > The new programming model of NVIDIA GPU's is called CUDA and I've > > noticed that they use the same __special__ notation for certain things > > as does python. For instance their modified C language has identifiers > > such as __device__, __global__, __shared__, etc. Is it a coincidence? > > Probably it is. :) > > Cuda is usually taken as short for "barracuda", a fish. Fish have been > known to slither under the right circumstances. Perhaps this is the link? Wow! How is it that I didn't think about this before?! Thanks a million! From turhan.aydin at gmail.com Tue Feb 27 04:35:32 2007 From: turhan.aydin at gmail.com (copermine) Date: 27 Feb 2007 01:35:32 -0800 Subject: JasperServer In-Reply-To: <1172168543.975485.238770@a75g2000cwd.googlegroups.com> References: <1172168543.975485.238770@a75g2000cwd.googlegroups.com> Message-ID: <1172568932.016387.270820@q2g2000cwa.googlegroups.com> On Feb 22, 8:22 pm, "batok" wrote: > JasperServeris a report engine ( java based ). It has asoap > interface. Does anybody has usedJasperserverviaSoap? > > An example would be appreciated. What do you need exactly? From bearophileHUGS at lycos.com Thu Feb 15 14:09:43 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Feb 2007 11:09:43 -0800 Subject: RE engines and related matters Message-ID: <1171566583.163694.201090@s48g2000cws.googlegroups.com> >From Lambda the Ultimate blog, a link to an interesting article about such topics: http://swtch.com/~rsc/regexp/regexp1.html http://swtch.com/~rsc/regexp/ http://lambda-the-ultimate.org/node/2064 Bye, bearophile From nszabolcs at gmail.com Sun Feb 11 07:36:36 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 11 Feb 2007 04:36:36 -0800 Subject: favourite editor In-Reply-To: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> Message-ID: <1171197396.381401.100460@v33g2000cwv.googlegroups.com> azrael wrote: > Since i'm new on this forum, and first time meeting a python comunity, > i wanted to ask you for your python editors. > > Im looking for some good python editor, with integrated run function, > without having to set it up manualy like komodo. > I found the pyscripter, and it has all i need, but it's unsatble. > bloated. it crashes when i close an yplication window run by python > from pyscripter. please. tell me a good one with buil in run (<-very > important) and nice gui. if possible to suport projects, code > highlighting, code completition, class browser, python comand line > (>>>), traceback. > > I didn't take a look on vista (and i dont want to), but i hope they > improved the notepad. *sigh* this question arises at least three times a week on this group you can use the googlegroups search function: http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=python+editor+ide&qt_g=Search+this+group also use the python wiki: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments http://wiki.python.org/moin/PythonEditors From greg at cosc.canterbury.ac.nz Thu Feb 8 18:52:36 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 09 Feb 2007 12:52:36 +1300 Subject: Referencing vars, methods and classes by name In-Reply-To: <1170952302.866455.52220@a34g2000cwb.googlegroups.com> References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> <7xbqk52gt8.fsf@ruckus.brouhaha.com> <7xveid6ni0.fsf@ruckus.brouhaha.com> <1170952302.866455.52220@a34g2000cwb.googlegroups.com> Message-ID: <531ri5F1qcm6sU1@mid.individual.net> Gabriel Genellina wrote: > On 8 feb, 05:51, Paul Rubin wrote: > > > "Gabriel Genellina" writes: > > > > > Surely you meant to say getattr(obj, a)() > > > > Yeah, darn. Counterintuitive. > > A generic function helps on using it on objects of any kind - like > len() > Perhaps it was more important with old style classes. It also avoids intruding on the method namespace of the object. That's important -- I like the way that the namespace of a brand-new class is a blank slate, apart from the double-underscore names. -- Greg From horpner at yahoo.com Mon Feb 12 10:39:42 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 12 Feb 2007 16:39:42 +0100 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> <7xbqjzud45.fsf@ruckus.brouhaha.com> Message-ID: On 2007-02-12, James Stroud wrote: > Paul Rubin wrote: >> "agent-s" writes: >>>Basically I'm programming a board game and I have to use a >>>list of lists to represent the board (a list of 8 lists with 8 >>>elements each). I have to search the adjacent cells for >>>existing pieces and I was wondering how I would go about doing >>>this efficiently. Thanks >> >> You're getting a bunch of Pythonic suggestions which are easy >> to understand though not so efficient. If you're after >> efficiency you might look at a book like Welsh and Baczynskyj >> "Computer Chess II" for some techniques (warning, this is a >> rather old book though) and program in a closer-to-the-metal >> language. One common approach these days is "bit boards". >> Basically you represent the board state as a bunch of 64-bit >> words, one bit per square. So for checking occupancy, you'd >> have a word having the bits set for occupied squares. If you >> only want to check adjacent squares (king moves), you could >> have a bunch of bit masks (one for each square) with bits set >> only for the adjacent squares (similarly for bishop moves, >> rook moves, etc.) Then to check adjacency you'd mask off the >> appropriate bits for that square, then AND it against the >> occupancy word. Normally you'd have separate occupancy words >> for your own pieces and your opponent's. > > In defense of the less efficient suggestions, he did say he had > to use a list of lists. But what you describe is pretty cool. Precomputing and storing the adjecent indexes for each square would be a possible hybrid solution. In effect every square would contain pointers to all its neighbors. -- Neil Cerutti From rschroev_nospam_ml at fastmail.fm Fri Feb 16 09:20:57 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 16 Feb 2007 14:20:57 GMT Subject: Pep 3105: the end of print? In-Reply-To: References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: Edward K Ream schreef: >> I'm pretty sure you're mistaken. Python 3 will be the release that breaks >> code. Hopefully very little, but there almost certainly will be some. > > Pep 3105 breaks a *lot* of code, despite the bland assertion that most > production programs don't use print. > > Presumably, Guido wanted to improve print in such a way that *more* people > would use it. But the effect of the pep is that *less* people will be able > to use print, *regardless* of how backward compatible Python 3.x is > 'allowed' to be. AFAIK the intention is not primarily to get more people to use print. Instead Guido has felt for some time that the print statement is a wart in the language (see the references in PEP 3105 for his arguments), and Python 3000 seems like a good opportunity to fix it once and for all. Precisely because AFAIK the point of Python 3000 is to fix a number of long-standing shortcomings, even if that means giving up a degree of backward compatibility. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From baur79 at gmail.com Thu Feb 1 13:17:31 2007 From: baur79 at gmail.com (baur79) Date: 1 Feb 2007 10:17:31 -0800 Subject: mysqldb duplicate entry error handling Message-ID: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> Hi guys i try to run this code in loop and to pass even the entry is duplicated def email_insert_in_db(email): sql="INSERT INTO emails (email) values ('%s') "%(email) db=_mysql.connect(host = "localhost", user = db_user, passwd = db_pass, db = db_name) try: db.query(sql) except IndentationError: print "duplicate" pass also try to (raise, continue) but can't continue in loop error output is: File "inser_in_db.py", line 85, in email_insert_in_db db.query(sql) IntegrityError: (1062, "Duplicate entry 'email at domain.com' for key 1") thanks for your help Baurzhan Zhakashev Kazakhstan / Shymkent city From mensanator at aol.com Sun Feb 11 04:08:21 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 11 Feb 2007 01:08:21 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> Message-ID: <1171184901.012350.40140@q2g2000cwa.googlegroups.com> On Feb 11, 1:35???am, Steve Holden wrote: > mensana... at aol.com wrote: > > On Feb 10, 4:07?pm, "Ben Sizer" wrote: > >> On Feb 10, 6:31 am, "mensana... at aol.com" wrote: > > >>> On Feb 9, 11:39?am, "Ben Sizer" wrote: > >>>> Hopefully in the future, some of those convoluted steps will be fixed, > >>>> but that requires someone putting in the effort to do so. As is often > >>>> the case with Python, and indeed many open source projects, the people > >>>> who are knowledgeable enough to do such things usually don't need to > >>>> do them, as their setup already works just fine. > >>> So you're saying the knowledgeable people's attitude > >>> is "fuck everyone else as lomg as it's not MY problem"? > >>> And you people complain about Microsoft. > >> Am I one of "those people"? You don't exactly make it clear. > > > I'm talking about the people who complain about Microsoft > > making the VC6 compiler no longer legally available and > > yet are so irresponsible that they use it for the latest > > release. > > I think you'll find those two sets are disjoint. > > > > > > >> But yes, there is a lot of "well, it works for me" going around. If > >> you do that long enough, people stop complaining, so people wrongly > >> assume there's no longer a problem. This is partly why Python has > >> various warts on Windows and why the standard libraries are oddly > >> biased, why configuring Linux almost always ends up involving hand- > >> editing a .conf file, why the leading cross-platform multimedia > >> library SDL still doesn't do hardware graphics acceleration a decade > >> after such hardware became mainstream, and so on. > > >> However, the difference between the open-source people and Microsoft > >> is the the open-source people aren't being paid by you for the use of > >> their product, so they're not obligated in any way to help you. > > > This argument has become tiresome. The Python community > > wants Python to be a big fish in the big pond. That's why > > they make Windows binaries available. > > ? I would suggest rather that "the Python community" (by which you > apparently mean the developers) hope that the fruits of their labours > will be used by as wide a cross-section of computer users as possible. > > The goals of open source projects are not those of commercial product > developers: I and others wouldn't collectively put in thousands of > unpaid hours a year to make a commercial product better and protect its > intellectual property, for example. > > >> After all, they have already given freely and generously, and if they choose > >> not to give more on top of that, it's really up to them. > > > Right. Get people to commit and then abandon them. Nice. > > Anyone who committed to Python did so without being battered by a > multi-million dollar advertising campaign. Multi-million dollar ad campaigns mean nothing to me. I committed to Python because it's a great language. I've dabbled in perl, Visual BASIC, UBASIC, REXX, Java, Scheme, C and C++ but Python is the one I use. > The Python Software > Foundation has only recently dipped its toes in the advocacy waters, > with results that are still under evaluation. And the use of the > Microsoft "free" VC6 SDK was never a part of the "official" means of > producing Python or its extensions, it was a community-developed > solution to the lack of availability of a free VS-compatible compilation > system for extension modules. > > I agree that there are frustrations involved with maintaining extension > modules on the Windows platform without having a copy of Visual Studio > (of the correct version) available. One of the reasons Python still uses > an outdated version of VS is to avoid forcing people to upgrade. Any > such decision will have fallout. Such as anyone who tries to get in the game late. > An update is in the works for those > using more recent releases, That's good news, although the responsible thing to do was not relaease version 2.5 until such issues are resolved. > but that won't help users who don't have > access to Visual Studio. That can be solved by throwing money at the problem. But money doesn't help when the solution is on the far side of the moon. > > >> Yes, it's > >> occasionally very frustrating to the rest of us, but that's life. > > > As the Kurds are well aware. > > I really don't think you help your argument by trying to draw parallels > between the problems of compiler non-availability and those of a > population subject to random genocide. You missed the point of the analogy. The US government suggested to the oppressed tribes in Iraq that they should rise up and overthrow Saddam Hussein at the end of the first Gulf War. And what did the US government do when they rose up? Nothing. They were left to twist in the wind. > Try to keep things in perspective, please. See if you can see the similarity. I buy into Python. I spend a lot of effort developing a math library based on GMPY to use in my research. I discover a bug in GMPY and actually go to a lot of effort and solve it. But _I_ can't even use it because I've been left to twist in the wind by the fact that Python 2.5 for Windows was built with an obsolete compiler that's not even available. Luckily, unlike the Kurds, my situation had a happy ending, someone else compiled the fixed GMPY source and made a 2.5 Windows version available. But can anyone say what will happen the next time? > > >> The best I feel I can do is raise these things on occasion, > >> on the off-chance that I manage to catch the attention of > >> someone who is > >> altruistic, knowledgeable, and who has some spare time on > >> their hands! > > > Someone who, say, solved the memory leak in the GMPY > > divm() function even though he had no way of compiling > > the source code? > > > Just think of what such an altruistic, knowedgeable > > person could do if he could use the current VC compiler > > or some other legally available compiler. > > Your efforts would probably be far better spent trying to build a > back-end for mingw or some similar system into Python's development > system, to allow Python for Windows to be built on a regular rather than > a one-off basis using a completely open source tool chain. No, as I said elsewhere, I'm not a software developer, I'm an amateur math researcher. My efforts are best spent as an actual end user to find and report bugs that the developers never see. Remember, a programmer, because he wrote it, only _thinks_ he knows how the program works. Whereas I, the user, _know_ how it works. > > The fact that the current maintainers of the Windows side of Python > choose to use a commercial tool to help them isn't something I am going > to try and second-guess. To do so would be to belittle efforts I would > have no way of duplicating myself, and I have far too much respect for > those efforts to do so. And I respect those efforts too. What I don't respect is irresponsible behaviour. > > There are published ways to build extension modules for Windows using > mingw, by the way - have you tried any of them? Yeah, and got nowhere. > It's much harder than sniping on a newsgroup, That figures. You try and contribute and you get accused of being a troll. > but you earn rather more kudos. Guess what kudos I got for solving the GMPY divm() problem? None. How much effort would it have been to mention my contribution in the source code comments (as was the case for other contributers)? Not that I'm bitter, after all, I'm altruistic. By the way, on the sci.math newsgroup I promote Python every chance I get. One fellow thanked me profusely for recommending Python & GMPY and asked for some help with a program he was having problems with. We worked it out fine but his problem made me suspect there may be more bugs in GMPY. What's my motivation for tracking them down? > > regards > ? Steve > -- > Steve Holden ? ? ? +44 150 684 7255 ?+1 800 494 3119 > Holden Web LLC/Ltd ? ? ? ? ?http://www.holdenweb.com > Skype: holdenweb ? ?http://del.icio.us/steve.holden > Blog of Note: ? ? ? ? ?http://holdenweb.blogspot.com > See you at PyCon? ? ? ? ?http://us.pycon.org/TX2007 From thomas.pollet at gmail.com Wed Feb 7 10:22:40 2007 From: thomas.pollet at gmail.com (Thomas Pollet) Date: Wed, 7 Feb 2007 16:22:40 +0100 Subject: python sub interpreter Message-ID: Hello, I want to have a python interpreter shell spawn from a python class member function. atm I use exec but I want something more flexible (i.e. syntax checking while typing) E.g.: class blah: def start_shell(self): import sys dbg=self str="" while str != 'exit': exec str print 'pydbg>>', str=sys.stdin.readline() etc. Somebody knows if something like this has been done before or an easy way to go about this? Regards, Thomas -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Sun Feb 18 01:22:52 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 18 Feb 2007 17:22:52 +1100 Subject: How do I save the contents of a text buffer References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> <1171761546.906729.95680@j27g2000cwj.googlegroups.com> Message-ID: On Sat, 17 Feb 2007 17:19:06 -0800, google wrote: >> Did you get an exception? Maybe something about not being able to open >> the file for reading? Or perhaps disk full? > > File read ok for input, its the file write thats the problem Well, duh. I know that -- that's what your first email said. Don't tell us there's a problem. Tell us what the problem is. Duh. >> Did you get something unexpected in the file? Maybe an empty file? > > Yes, a rabbit popped out of the floppy slot - amazing! You know how your teachers said "there are no stupid questions, only stupid answers?" They lied. Perhaps you should go away and read this before asking any further questions. http://catb.org/esr/faqs/smart-questions.html >> I'm guessing... it erased your hard disk. Do I win? > > Sorry, you lose....are you a Windows user? Sorry, you lose. I really don't know why you're casting aspersions on the intelligence of Windows users, when you're the one posting a stupid question. Do I really need to spell it out? We can't tell you what the solution to the problem is if you won't tell us what the problem is. If you get an exception, post the exception. If something unexpected happens, tell us what it was. We're not mind-readers. -- Steven. From jasonmccandless at gmail.com Tue Feb 6 08:36:54 2007 From: jasonmccandless at gmail.com (jasonmc) Date: 6 Feb 2007 05:36:54 -0800 Subject: Running long script in the background In-Reply-To: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> Message-ID: <1170769014.352466.135280@h3g2000cwc.googlegroups.com> > Does anybody know a way to make output show in real time? You can put: #!/usr/bin/python -u at the top of the script to have unbuffered binary stdout and stderr. From skpeterson at nospam.please.ucdavis.edu Sun Feb 11 23:22:25 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 20:22:25 -0800 Subject: No module named pyExcelerator Error References: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> Message-ID: "susan" on 11 Feb 2007 16:55:35 -0800 didst step forth and proclaim thus: > Hi, > I'm new of Python, and this problem stucked me whole day but can't be > solved. [snip] > anybody can tell me where's wrong please? Thanks in advance! What are the contents of sys.path from an interactive prompt? Have you tried the official windows Python? Is there a reason you need to use the cygwin Python? -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From gagsl-py at yahoo.com.ar Sat Feb 24 23:56:08 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 01:56:08 -0300 Subject: convert python scripts to exe file References: Message-ID: En Sun, 25 Feb 2007 00:29:53 -0300, Eric CHAO escribi?: > I know py2exe can make an exe file. But python runtime dll is still > there. How can I combine the dll file into the exe, just make one > file? May I ask why? If you want to distribute your app on a single file, there are many installers available that will package that for you (try InnoSetup). -- Gabriel Genellina From gagsl-py at yahoo.com.ar Mon Feb 12 00:33:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 02:33:13 -0300 Subject: No module named pyExcelerator Error References: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> <1171242994.102776.69730@s48g2000cws.googlegroups.com> <1171255611.853011.118970@s48g2000cws.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 01:46:51 -0300, susan escribi?: >> > $ python ./pyExcelerator/setup.py install >> >> Try this instead: >> $ cdpyExcelerator >> $ python ./setup.py install > I still wonder why my way didn't work. I think maybe there's some hard > code of installation directory, hence, installation won't be succesful > if the directory is not exactly the same as the one in README. It doesn't matter the directory name, what matters is that you run the script from the install dir (where setup.py resides) and not from other place. -- Gabriel Genellina From steve at REMOVEME.cybersource.com.au Tue Feb 27 21:39:14 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Feb 2007 13:39:14 +1100 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: On Tue, 27 Feb 2007 20:59:03 +0000, Alan Isaac wrote: > "Steven D'Aprano" wrote in message > news:pan.2007.02.27.07.24.57.769316 at REMOVEME.cybersource.com.au... > class Difficult(object): > def __setattr__(self, name, value): > if self.__dict__.has_key(name): > print "'%s' exists as an instance attribute" % name > self.__dict__[name] = value > elif self.__class__.__dict__.has_key(name): > print "'%s' exists as a class attribute" % name > self.__class__.__dict__[name] = value > else: > print "Can't create new attributes, 'cos I said so!" > > > > But this prevents setting attributes during initialization, > so it does not meet the spec. What, you expect us to do everything for you? *wink* If you want the class to change behaviour after initialisation, you have to code it to do so. The easy, but inelegant, way is to set a flag. Finding an elegant way to do so is a little like asking for an elegant way to scrub a septic tank clean. But one way might be to change the class after initialisation: class Parrot(object): def __init__(self, data): self.data = data self.__class__ = Annoying class Annoying(Parrot): def __setattr__(self, name, value): print "Annoy the user." >>> x = Parrot(5) >>> x.data 5 >>> x.data = 7 Annoy the user. >>> x.data 5 -- Steven D'Aprano From http Sat Feb 3 21:05:52 2007 From: http (Paul Rubin) Date: 03 Feb 2007 18:05:52 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> Message-ID: <7xfy9mekxr.fsf@ruckus.brouhaha.com> "Paul Boddie" writes: > Python should only incorporate functionality in order to offer a > coherent experience (where the omission of functionality would > otherwise lead to a flawed experience). For example, having support > for SSL in the socket module offers a coherent experience because it > means that urllib and related modules can offer to support SSL-related > URLs out of the box. But they can't, because the built-in socket module SSL interface doesn't check certificates, causing total security failure if someone spoofs the remote site. The built-in SSL functionality is broken and users have to resort to external packages. Then you have to ask why the stdlib includes anything like urllib in the first place, under this "coherent experience" concept (I interpret that as some kind of minimalist philosophy). Can't users have a coherent experience if the stdlib doesn't include urllib? My own answer is the one that I thought that the developers had settled on years ago, namely "batteries included", i.e. ship a rich set of libraries that provide a wide variety of useful functions, i.e. the doctrine of minimalism has been explicitly rejected. We then get the question of whether to include any specific function and that's where comparisons with other languages come in. > > No. That would be colo or something similar , > Or a virtual private server. Sure, that would count as "something similar". > If a hosting provider claims Python and MySQL support, then I'd hope > that they have worked out that the MySQLdb package glues the two > together. I'd expect so too. The issue is there aren't very many of those companies and that appears partly because of the hassle involved. So minimizing the hassle suggests itself as a road to wider acceptance. Your point that shared hosting with Python isn't so easy because of insufficient isolation between apps is valid. Maybe Python 3.0 can do something about that and it seems like a valid thing to consider while fleshing out the 3.0 design. > Perhaps better information is necessary for those hosting > companies who haven't worked such things out: you'd have a metapackage > for stuff like this in certain distributions. That could help. > So, for the less forward-thinking providers a metapackage would be the > solution, then? I'm not sure what you mean by metapackage but in general the goal is to minimize the number of places that the hosting provider (or OS distro maintainer, or whatever) From nospamformeSVP at gmail.com Wed Feb 14 11:48:08 2007 From: nospamformeSVP at gmail.com (Don Taylor) Date: Wed, 14 Feb 2007 11:48:08 -0500 Subject: Testers please In-Reply-To: References: Message-ID: <45D33D48.4000005@gmail.com> martien friedeman wrote: > I have written this tool that allows you to look at runtime data and > code at the same time. > And now I need people to test it. > > The easiest way to see what I mean is to look at some videos: > http://codeinvestigator.googlepages.com/codeinvestigator_videos > > It requires Apache and Sqlite. > > It works for me with a Firefox browser on Linux. > ODB, the Omniscient Debugger, for Java does the same sort of thing and more. http://www.lambdacs.com/debugger/ODBDescription.html I would love to have one of these for Python. Don. From kent at kentsjohnson.com Mon Feb 12 13:58:57 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 12 Feb 2007 18:58:57 GMT Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Message-ID: devicerandom at gmail.com wrote: > Hi, > > I am currently using the Cmd module for a mixed cli+gui application. I > am starting to refactor my code and it would be highly desirable if > many commands could be built as simple plugins. > > My idea was: > - Load a list of plugin names (i.e. from the config file, or from the > plugins directory) > - Import all plugins found dynamically: > and this is easy, since I can do, for example: > > PLUGIN_NAMES=['foo', 'bar'] > PLUGIN_MODULES = map(__import__, PLUGIN_NAMES) > PLUGINS = [item.Commands for item in PLUGIN_MODULES] > > Now, what I have to do is to define my command line class. This is > usually done by subclassing cmd.Cmd: > > class MyCli(cmd.Cmd): > .... > > Now I want to add the commands defined in foo.Commands and > bar.Commands. foo.Commands contains the functions corresponding to the > new commands this way: > #foo.py > class Commands > > def do_this(self,args): > ... > def do_that(self,args): > ... > > I've seen I can do it by explicitely import them and using multiple > inheritance: > > class MyCli(cmd.Cmd , foo.Commands, bar.Commands) > .... > > so that do_this and do_that are now methods of a Cmd command line. > > Now: > - how can I instead have MyCli inherit from a dynamic list of modules? > - is there a better way than using multiple inheritance to plug-in > dynamically commands in a Cmd command line? Your plugins could define plain functions with names starting with do_. Then you can create an empty subclass of cmd.Cmd and just plug in the imported commands: In [1]: import cmd In [3]: def do_this(self, arg): print 'This', arg ...: In [4]: def do_that(self, arg): print 'That', arg ...: In [8]: class MyCmd(cmd.Cmd): pass ...: In [9]: MyCmd.do_this = do_this In [10]: MyCmd.do_that = do_that In [11]: c=MyCmd() In [12]: c.cmdloop() (Cmd) help Undocumented commands: ====================== help that this (Cmd) that That In your code you could use introspection to locate the plugin commands, something like PLUGIN_MODULES = map(__import__, PLUGIN_NAMES) for module in PLUGIN_MODULES: for name in dir(module): if name.startswith('do_'): setattr(MyCmd, name, getattr(module, name)) If the plugin module defines a list of commands then use that instead of dir(module). Kent From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 16:19:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 28 Feb 2007 22:19:32 +0100 Subject: Extract String From Enclosing Tuple In-Reply-To: References: Message-ID: <45e5ea13$0$30011$426a74cc@news.free.fr> rshepard at nospam.appl-ecosys.com a ?crit : > I'm a bit embarrassed to have to ask for help on this, but I'm not finding > the solution in the docs I have here. > > Data are assembled for writing to a database table. A representative tuple > looks like this: > > ('eco', "(u'Roads',)", 0.073969887301348305) > > Pysqlite doesn't like the format of the middle term: > pysqlite2.dbapi2.InterfaceError: Error binding parameter 1 - probably > unsupported type. > > I want to extract the 'Roads', part from the double-quoted enclosing > tuple. The unicode part should be automatically removed when the string is > printed, but I suspect it's the double quotes and extra parentheses that are > the problem. I know that tuples are immutable, but I thought that I could > slice it. If so, I'm not doing it correctly, because each attempt results in > TypeError: unsubscriptable object Where do you get your data from ? MHO is that you'd better handle the problem at the source (ie : dont put a string representation of a tuple in your data) instead of trying to fix it afterward. From johnjsal at NOSPAMgmail.com Thu Feb 1 14:55:47 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Feb 2007 14:55:47 -0500 Subject: Sorting a list In-Reply-To: <45c245e1$0$31965$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> Message-ID: <45c24643$0$31965$c3e8da3@news.astraweb.com> John Salerno wrote: > Bruno Desthuilliers wrote: >> John Salerno a ?crit : >>> Hi everyone. If I have a list of tuples, and each tuple is in the form: >>> >>> (year, text) as in ('1995', 'This is a citation.') >>> >>> How can I sort the list so that they are in chronological order based >>> on the year? >> >> Calling sort() on the list should just work. > > Amazing, it was that easy. :) Here's what I did: import re file = open('newrefs.txt') text = file.readlines() file.close() newfile = open('sortedrefs.txt', 'w') refs = [] pattern = re.compile('\(\d{4}\)') for line in text: year = pattern.search(line).group() refs.append((year, line)) refs.sort() for ref in refs: newfile.write(ref[1]) newfile.close() From nagle at animats.com Sun Feb 25 20:30:13 2007 From: nagle at animats.com (John Nagle) Date: Mon, 26 Feb 2007 01:30:13 GMT Subject: convert strings to utf-8 In-Reply-To: <54efruF20lajvU1@mid.uni-berlin.de> References: <54doljF20aq9hU1@mid.uni-berlin.de> <54efruF20lajvU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Niclas schrieb: > >> Thank you! >> >> solved it with this: >> unicode( data.decode('latin_1') ) > > > The unicode around this is superfluous. Worse, it's an error. utf-8 needs to go into a stream of 8-bit bytes, not a Unicode string. John Nagle From gagsl-py at yahoo.com.ar Sat Feb 10 07:48:10 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 09:48:10 -0300 Subject: Distributing Python Applications References: <1171110089.040455.154690@v33g2000cwv.googlegroups.com> Message-ID: En Sat, 10 Feb 2007 09:21:29 -0300, escribi?: > It has been such a painful thing for me. Ouch... why was that? Programming in Python, or using py2exe? > As I made a program to > encrypt files, now I want to distribute that program over other > computers. I created .EXE file with py2exe but the "dist" folder makes > around 2 mb and it restricts for the python DLL to be within the same > folder. Is there any easy way to get this thing done in just one exe > file? Perhaps... but what would you gain? Most programs include, apart from the main executable: manual, license, readme file, release notes, installation guide, other resources, etc. You can use an installer like Inno Setup to package nicely all required pieces into a single distributable file. For simple programs, even a self-extracting .zip would suffice. > I mean if I do interfacing with C/C++ will it work for me and if > I do interfacing with C/C++ will it be necessary on the other computer > to have python installed on it? I don't understand what are you asking... You can extend and/or embed Python using C. And you already know py2exe, obviously: the idea is to *not* require a previous Python install in order to run your application. -- Gabriel Genellina From broek at cc.umanitoba.ca Thu Feb 8 18:02:43 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 08 Feb 2007 17:02:43 -0600 Subject: Python Newbie In-Reply-To: <1170973096.113660.264600@l53g2000cwa.googlegroups.com> References: <1170973096.113660.264600@l53g2000cwa.googlegroups.com> Message-ID: <45CBAC13.1090102@cc.umanitoba.ca> spazziam said unto the world upon 02/08/2007 04:18 PM: > SyntaxError: invalid syntax > File "C:\Python23\vdrop2\final py\vdrop2.py", line 123 > def INIT_HIGHS(): > ^ > SyntaxError: invalid syntax > > Why would this come up? > Hi, Most likely, a previous line contains an unfinished statement. For instance: not_yet_a_list = [1,2,3 def foo(): pass when saved and run as foo.py produces: brian at gottlob:~/scratch$ python foo.py File "foo.py", line 3 def foo(): ^ SyntaxError: invalid syntax HTH, Brian vdB From steve at holdenweb.com Fri Feb 9 09:15:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Feb 2007 14:15:51 +0000 Subject: Glob returning an empty list when passed a variable In-Reply-To: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: Neil Webster wrote: > Hi, > > I was wondering whether anybody could help me out. > > I have a program, for part of it I am trying to pass a variable to a > glob function, this returns an empty list. The strange thing is when > I hard code in the variable the glob section works. > > Does anybody have any ideas as why it is not working? > > The section of code that is not working is: > > # The variable to be passed to the glob function > area_name_string = '"*% s*"' % (Area_name) > > os.chdir(Input) > > filename = glob.glob(area_name_string) > > Thanks in advance Because you are trying to match filenames that have a double-quote character at the start and end? Try area_name_string = '*% s*' % (Area_name) Interesting, I never realised until now that you can have spaces between the percent sign and th format effector. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From arkanes at gmail.com Mon Feb 12 09:02:33 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Feb 2007 08:02:33 -0600 Subject: Putting wxFrame on the second monitor In-Reply-To: <45d06dae$0$30310$9b4e6d93@newsspool1.arcor-online.net> References: <45d06dae$0$30310$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4866bea60702120602t1dd8b4cy7081fde5470818e1@mail.gmail.com> On 2/12/07, Michael Butscher wrote: > Hi, > > My software is written with wxPython. At some point it pops up a child- > frame of the main frame. The child-frame gets a fixed position in > constructor (maybe this is the problem). > > Now I got reports from users with dual monitor systems that this child- > frame is always shown on the primary monitor even if the main frame is > on the second. Any hints what I can do here? > > > TIA > > Michael > -- Don't give it a fixed position in the constructor, position it relative to the parent frame. From ruan at jcmills.com Sat Feb 3 18:49:25 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Sat, 3 Feb 2007 18:49:25 -0500 Subject: confused about resizing array in Python References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: You mentioned "it doubles in size". Are you saying that a new double sized array is allocated and the contents of the old list is copied there? Then the old list is freed from memory? It seems to be what is called amortized constant. Say the list size is 100, before it is fully used, the append takes O(1) time. But for the 101th element, the time will be O(100+1), and then from then on, it is O(1) again. Like John Machin said in the previous post? But on average, it is O(1). I guess this is the amortized constant. Isn't it? "Roel Schroeven" wrote in message news:vc8xh.325172$Au6.6345787 at phobos.telenet-ops.be... > Ruan schreef: >> "Roel Schroeven" wrote: >>> Ruan schreef: >>>> My confusion comes from the following piece of code: >>>> >>>> memo = {1:1, 2:1} >>>> def fib_memo(n): >>>> global memo >>>> if not n in memo: >>>> memo[n] = fib_memo(n-1) + fib_memo(n-2) >>>> return memo[n] >>>> >>>> I used to think that the time complexity for this code is O(n) due to >>>> its use of memoization. >>>> >>>> However, I was told recently that in Python, dictionary is a special >>>> kind of array and to append new element to it or to resize it, it is in >>>> fact >>>> internally inplemented by creating another array and copying the old >>>> one to >>>> it and append a new one. > >>> That's not correct. Python dictionaries are highly optimized and I >>> believe the time complexity is amortized constant (i.e. O(1)) for both >>> insertions and lookups. > >> Then how about Python's list? >> >> What is done exactly when list.append is executed? >> >> For list, is there another larger list initialized and the contents from >> the >> old list is copied to it together with the new appended list? > > I'm not sure, but I think each time the list needs to grow, it doubles in > size. That leaves room to add a number of elements before the allocated > space needs to grow again. It's a frequently used approach, since it is > quite efficient and the memory needed is never double the amount of memory > strictly needed for the elements of the list. > > You can always study the source code for all gory details of course. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven From adamgarstang at googlemail.com Mon Feb 26 17:45:26 2007 From: adamgarstang at googlemail.com (Adam) Date: 26 Feb 2007 14:45:26 -0800 Subject: Walk thru each subdirectory from a top directory In-Reply-To: <1172529799.827628.321760@p10g2000cwp.googlegroups.com> References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <1172529799.827628.321760@p10g2000cwp.googlegroups.com> Message-ID: <1172529926.247804.4050@p10g2000cwp.googlegroups.com> Whoops, the first bit of my reply ended up in the quoted text. See above. Adam From skip at pobox.com Thu Feb 8 10:05:12 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 8 Feb 2007 09:05:12 -0600 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <1170939556.975052.128930@a34g2000cwb.googlegroups.com> References: <45C9A137.8090009@v.loewis.de> <52vtc4F1pngrdU1@mid.individual.net> <1170939556.975052.128930@a34g2000cwb.googlegroups.com> Message-ID: <17867.15400.120742.482866@montanaro.dyndns.org> Michele> That is a common design, but I don't like it, since it becomes Michele> very easy to get classes with dozens of methods inherited from Michele> everywhere, a modern incarnation of the spaghetti-code Michele> concept. I find it much better to use composition, i.e. to Michele> encapsulate the various behaviors in different objects and to Michele> add them as attributes. Composition is great when you know how largish classes are going to be composed ahead of time and/or already have the pieces available in the form of other classes you want to reuse. I use this fragment-by-multiple- inheritance (I hesitate to call it a) pattern when I realize after a long period of organic growth that a single-inheritance class has gotten too big. It's often relatively easy to carve the class up into multiple related base classes. The next step after that might be to morph those independent base classes back into delegated attributes. Skip From steve at holdenweb.com Fri Feb 16 11:32:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 11:32:16 -0500 Subject: Reg Google Web Toolkit and Python In-Reply-To: <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> References: <53lranF1th0pcU1@mid.uni-berlin.de> <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> Message-ID: <45D5DC90.8090907@holdenweb.com> Shadab Sayani wrote: > Hi , > We have a project where I need to read files store > them in database in the backend.We have done this in > python.Now we decided to use Ajax technique for user > interface.For that we found that GWT is one of the > best toolkits.Now I got a doubt can I interface GWT > with python. > Thanks , > Shadab. > > Send instant messages to your online friends http://uk.messenger.yahoo.com Please note that you should not create a new conversation on a newsgroup by editing a reply to an unrelated post - your comments are now threaded along wiht "Approaches of Interprocess Communication", making them unnecessarily hard to find and somewhat confusingly positioned. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From loveline17 at gmail.com Wed Feb 28 01:07:14 2007 From: loveline17 at gmail.com (loveline17 at gmail.com) Date: 27 Feb 2007 22:07:14 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172640476.259853.245530@8g2000cwh.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> Message-ID: <1172642834.634337.26040@p10g2000cwp.googlegroups.com> Hi Troy, once again thanks for the quickie. I installed everything properly now (error free!! yay) and the j2py script is located under : C:\Documents and Settings\Ujjal Pathak\Desktop\java2python-0.2\build \scripts-2.5 Meaning under scripts-2.5 folder, there are two files j2py and jast_print but without any file extension though! Here's the screenie : http://img241.imageshack.us/img241/675/95456528nk3.png Once I fixed the path for both Python and j2py, only Python seems to be working but not j2py. Here is the screenie : http://img81.imageshack.us/img81/1796/51776836tf4.png So, I wonder what might be the problem now? ^^ :) On Feb 27, 11:27 pm, "troy.melh... at gmail.com" wrote: > > Hi Jeremy, that's the problem I'm having. Where should I type that " > > python setup.py install" ? Once again I'm using Windows system and not > > Unix. Should I move the file to a specific folder under Python 2.5 and > > then type " python setup.py install" in IDLE or Command Line window? > > I get the error "SyntaxError: invalid syntax" with the word "setup" > > hi andy, > > you want to run the windows command prompt, which is called "cmd.exe" > in windows xp. press the "start menu", then select "run", then type > "cmd.exe" without the quotes. > > a window will pop up that looks black, and it will have a prompt like > "C:\" or "D:\something". with this window, you need to type several > commands. the first command is "cd", which changes the working > directory. you'll want to type the name of the drive and folder where > you extracted the j2py package. this can be anywhere, and it doesn't > have to be in your python folders. example: > > C:\> cd D:\temp\java2python-0.2 > > next, you'll need to run the setup script with python. you can test > for python at the prompt like this: > > D:\temp\java2python-0.2\> python -V > > if you get "Python 2.5", you're ready to run the script. if you don't > get that, or if you get something along the lines of "command not > found", then you'll have to qualify the command with the full path to > the 2.5 interpreter. for example: > > D:\temp\java2python-0.2\> C:\Python2.5\python.exe -V > > i don't know where you installed python, nor do i remember much about > how the windows installation layout, so you'll have to figure out > these paths on your own. > > once you get the "Python 2.5" response, you can install the package. > this is the easy part. use whatever command you got to reply "Python > 2.5", enter it again, along with a space followed by "setup.py > install" (again, no quotes). continuing the example above: > > D:\temp\java2python-0.2\> C:\Python2.5\python.exe setup.py install > > you should read all of the output closely -- look for errors. you > might have problems installing the software if you're not an > administrator. > > if you don't have problems, the setup process will have copied a > script named "j2py" somewhere in your system path. try "j2py -- > version", and if everything works, you'll get the reply "j2py 0.2". > once the script is installed, change to the directory of your java > files (using "cd"), then do something like this, substituting your > file names where appropriate: > > D:\myjavafiles\> j2py -i someclass.java -o someclass.py > > best of luck to you, and please do let me (or the group) know how > everything works out. From grahamd at dscpl.com.au Mon Feb 5 16:42:30 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 5 Feb 2007 13:42:30 -0800 Subject: Python does not play well with others In-Reply-To: <7xodo85tzi.fsf@ruckus.brouhaha.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <7xodo85tzi.fsf@ruckus.brouhaha.com> Message-ID: <1170711750.776012.126850@h3g2000cwc.googlegroups.com> On Feb 6, 5:39 am, Paul Rubin wrote: > John Nagle writes: > > > The GIL doesn't affect seperate processes, and any large server that > > > cares about stability is going to be running a pre-forking MPM no > > > matter what language they're supporting. > > > Pre-forking doesn't reduce load; it just improves responsiveness. > > You still pay for loading all the modules on every request. For > > many AJAX apps, the loading cost tends to dominate the transaction. > > I think the idea is that each pre-forked subprocess has its own > mod_python that services multiple requests serially. And where 'worker' MPM is used, each child process can be handling multiple concurrent requests at the same time. Similarly on Windows although there is only one process. > New to me is the idea that you can have multiple separate Python > interpreters in a SINGLE process (mentioned in another post). I'd > thought that being limited to one interpreter per process was a > significant and hard-to-fix limitation of the current CPython > implementation that's unlikely to be fixed earlier than 3.0. No such limitation exists with mod_python as it does all the interpreter creation and management at the Python C API level. The one interpreter per process limitation is only when using the standard 'python' runtime executable and you are doing everything in Python code. Graham From horpner at yahoo.com Fri Feb 2 14:14:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 20:14:28 +0100 Subject: Checking default arguments References: Message-ID: On 2007-02-02, Igor V. Rafienko wrote: > Hi, > > I was wondering whether it was possible to find out which > parameter value is being used: the default argument or the > user-supplied one. That is: > > def foo(x, y="bar"): > # how to figure out whether the value of y is > # the default argument, or user-supplied? > > foo(1, "bar") => user-supplied > foo(1) => default > > {}.pop seems to be able to make this dictinction. You can fake it (this may be how dict.pop work) by not providing defaults, but using positional arguments. Here's a silly example, which returns a tuple if the user supplies the second argument, and a list otherwise. def foo(x, *args): if len(args) == 0: y_provided = True y = "bar" else: y_provided = False y = args[0] if y_provided: return (x, y) else: return [x, y] -- Neil Cerutti Wonderful bargains for men with 16 and 17 necks --sign at clothing store From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 16:41:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 22:41:58 +0100 Subject: alias for data member of class instance? In-Reply-To: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> References: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> Message-ID: <45c79d8f$0$23936$426a74cc@news.free.fr> Sean McIlroy a ?crit : > hi all > > is there a way to do this ... > > class clown: > def __init__(self): > self.x = 0 > self.y = ALIAS(self.x) ## FEASIBLE ? > class Clown(object): def __init__(self): self.x = 0 @apply def x(): def fget(self): return self._x def fset(self, value): self._x = value return property(**locals()) y = x From dimitri.pater at gmail.com Fri Feb 9 18:42:04 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Sat, 10 Feb 2007 00:42:04 +0100 Subject: Best Free and Open Source Python IDE In-Reply-To: <6fd78$45ccd1c1$d443bb3a$15713@news.speedlinq.nl> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> <1171047698.558376.160500@v33g2000cwv.googlegroups.com> <6fd78$45ccd1c1$d443bb3a$15713@news.speedlinq.nl> Message-ID: Hi, the hunt for free Python IDE's is a never ending journey... just make up your mind and invest some money in WingIDE. It is not *that* expensive and in the end it will save you lots of time (=money) hunting for the perfect "free" Python Ide. Just download the time limited free version of WingIDE and see for yourself. I don't think you'll be disappointed, I use it every day and it's a real time saver for my projects. And there is another priceless feature, the WingIDE guys will answer every question in the mailing list. Now, how's that? regards, Dimitri On 2/9/07, Stef Mientki wrote: > > Szabolcs Nagy wrote: > > Srikanth wrote: > >> Yes, > >> > >> All I need is a good IDE, I can't find something like Eclipse (JDT). > >> Eclipse has a Python IDE plug-in but it's not that great. Please > >> recommend. > >> > >> Thanks, > >> Srikanth > > > > try pida > > http://pida.co.uk/index.php/Main_Page > > > nice idea to re-use components you already have. > > Which brings me to some other questions on waste: > - isn't it a pitty so many people are involved in writing another editor / > IDE ? > - isn't it a waste for newbies to evaluate a dozen editors / IDE's ? > > What anser do we really give here ? > Aren't we just telling the guy, > what we've chozen (with our limited overview of our newbie time) ;-) > (sorry, I also gave an answer ;-) > > Can't we persuade the next newbie, asking this question, > to start some kind of wiki page, > where the differences between editors / IDE's are listed ? > > Unfortunately he number of IDE's / editors is so large, > a simple 2 dimensional array of features would become too large ;-) > Maybe a first split would be the required OS ? > Next split could be editor-features and IDE features ? > > just some thoughts, > of a some months old newbie, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Sat Feb 24 23:31:21 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 01:31:21 -0300 Subject: Endianness conversion References: <45e05c49$0$20809$5fc30a8@news.tiscali.it> <45e07570$0$20809$5fc30a8@news.tiscali.it> Message-ID: En Sat, 24 Feb 2007 14:27:12 -0300, Toby escribi?: > I ended up writing my own byteswapper in Pyrex: You can use the byteswap method of arrays: >>> import array >>> a = array.array('H', 'ABcd56') >>> a.tostring() 'ABcd56' >>> a.byteswap() >>> a.tostring() 'BAdc65' -- Gabriel Genellina From george.sakkis at gmail.com Tue Feb 20 09:13:14 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 20 Feb 2007 06:13:14 -0800 Subject: Bypassing __setattr__ for changing special attributes In-Reply-To: References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> <1171955882.929647.86700@v33g2000cwv.googlegroups.com> Message-ID: <1171980794.444365.223830@l53g2000cwa.googlegroups.com> On Feb 20, 7:57 am, Steven D'Aprano wrote: > On Mon, 19 Feb 2007 23:18:02 -0800, Ziga Seilnacht wrote: > > George Sakkis wrote: > >> I was kinda surprised that setting __class__ or __dict__ goes through > >> the __setattr__ mechanism, like a normal attribute: > > >> class Foo(object): > >> def __setattr__(self, attr, value): > >> pass > > >> class Bar(object): > >> pass > > >> >>> f = Foo() > >> >>> f.__class__ = Bar > >> >>> print f.__class__ is Foo > >> True > > >> Is there a way (even hackish) to bypass this, or at least achieve > >> somehow the same goal (change f's class) ? > > >> George > > >>>> object.__setattr__(f, '__class__', Bar) > >>>> f.__class__ is Bar > > True > > This version is arguably more "correct", although a tad longer to write, > and doesn't need you to hard-code the class superclass: > > super(f.__class__, f).__setattr__('__class__', Bar) > > But what surprised me was that this *didn't* work: > > >>> f = Foo() > >>> f.__dict__['__class__'] = Bar > >>> f.__class__ > > > > Unless I'm confused, it looks like instance.__class__ bypasses the usual > lookup mechanism (instance.__dict__, then instance.__class__.__dict__) for > some reason. > > >>> Foo.x = 1 # stored in class __dict__ > >>> f.x > 1 > >>> f.__dict__['x'] = 2 # stored in instance __dict__ > >>> f.x > 2 > >>> Foo.x > > 1 > > But __class__ doesn't behave like this. Why? > > -- > Steven. Perhaps because __class__ is a special descriptor: >>> type(object.__dict__['__class__']) George From boris.smirnov at gmail.com Tue Feb 27 03:52:04 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 27 Feb 2007 00:52:04 -0800 Subject: Interactive os.environ vs. os.environ in script In-Reply-To: References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> <1172562212.691747.150310@m58g2000cwm.googlegroups.com> Message-ID: <1172566324.278334.284760@s48g2000cws.googlegroups.com> On Feb 27, 9:31 am, Peter Otten <__pete... at web.de> wrote: > boris.smir... at gmail.com wrote: > > Is there another possibility of how to solve it just by adding some > > lines in script? > > I think you have to wrap your script in a shell script > > #!/bin/sh > export LD_LIBRARY_PATH=/path/Linux/rh_linux > python shrink_bs_070226.py > > To avoid that you can have the python script invoke itself, e. g.: > > #!/usr/bin/env python > import os > if os.environ.get("YADDA") != "whatever": > print "fix environment" > os.environ["YADDA"] = "whatever" > os.system("yadda.py") > raise SystemExit > > print "YADDA is now %r" % os.environ["YADDA"] > print "do your real stuff" > > Peter Thanks for the reply. If I that good understood I did this: ********************************** import sys, re, glob, shutil import os if os.environ["LD_LIBRARY_PATH"].count('/path/Linux/rh_linux') !=1: os.environ["LD_LIBRARY_PATH"]=os.environ["LD_LIBRARY_PATH"]+':'+'/ path/Linux/rh_linux' os.system("shrink_bs_070226.py") raise SystemExit from qt import * *********************** Is that correct. If yes then it not works. If not then, what's wrong? > python shrink_bs_070226.py Traceback (most recent call last): File "./shrink_bs_070226.py", line 29, in ? from qt import * ImportError: No module named qt Thanks Boris From exarkun at divmod.com Sun Feb 25 21:02:01 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 25 Feb 2007 21:02:01 -0500 Subject: getting terminal display size? In-Reply-To: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> Message-ID: <20070226020201.25807.1291999397.divmod.quotient.32067@ohm> On 25 Feb 2007 16:53:17 -0800, jeff wrote: >I looked around a lot on the internet and couldn't find out how to do >this, how do I get the sizer (in rows and columns) of the view? > Assuming you're talking about something vaguely *NIXy, you want something like what's being done here: http://twistedmatrix.com/trac/browser/trunk/twisted/conch/scripts/conch.py#L361 Jean-Paul From jura.grozni at gmail.com Thu Feb 8 16:07:20 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 13:07:20 -0800 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: <45ca6033$0$328$e4fe514c@news.xs4all.nl> References: <1170883933.480967.53500@v33g2000cwv.googlegroups.com> <45ca6033$0$328$e4fe514c@news.xs4all.nl> Message-ID: <1170968839.909709.54340@p10g2000cwp.googlegroups.com> no, not renting. i need such one at home. when you say rent it sounds like buy a hosting package. i need one to work all the time on max power. cracking md5 needs power. :-D From rshepard at nospam.appl-ecosys.com Sat Feb 24 21:01:18 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 25 Feb 2007 02:01:18 GMT Subject: Referencing Items in a List of Tuples Message-ID: While working with lists of tuples is probably very common, none of my five Python books or a Google search tell me how to refer to specific items in each tuple. I find references to sorting a list of tuples, but not extracting tuples based on their content. In my case, I have a list of 9 tuples. Each tuple has 30 items. The first two items are 3-character strings, the remaining 28 itmes are floats. I want to create a new list from each tuple. But, I want the selection of tuples, and their assignment to the new list, to be based on the values of the first two items in each tuple. If I try, for example, writing: for item in mainlist: if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': ec.Append(mainlist[item][2:]) python doesn't like a non-numeric index. I would really appreciate a pointer so I can learn how to manipulate lists of tuples by referencing specific items in each tuple (string or float). Rich From h.b.furuseth at usit.uio.no Fri Feb 2 07:48:47 2007 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Fri, 02 Feb 2007 13:48:47 +0100 Subject: LDAP/LDIF Parsing References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> <45c26772$0$4272$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > class LdapObject(object): > (...) > def __getattr__(self, name): > try: > data = self._record[name] > except KeyError: > raise AttributeError( > "object %s has no attribute %s" % (self, name) > ) Note that LDAP attribute descriptions may be invalid Python attribute names. E.g. {... 'title;lang-en': ['The Boss'] 'title;lang-no': ['Sjefen']} So you'd have to call getattr() explicitly to get at all the attributes this way. > else: > # all LDAP attribs are multivalued by default, > # even when the schema says they are monovalued > if len(data) == 1: > return data[0] > else: > return data[:] IMHO, this just complicates the client code since the client needs to inserts checks of isinstance(return value, list) all over the place. Better to have a separate method which extracts just the first value of an attribute, if you want that. -- Regards, Hallvard From uval at rz.uni-karlsruhe.de Thu Feb 15 11:12:33 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 15 Feb 2007 17:12:33 +0100 Subject: builtin set literal In-Reply-To: References: Message-ID: [...] >>> In Python 3.0, this looks like:: >>> >>> s = {1,2,3} >> >> jepp, that looks not bad .. as in a mathe book. >> the only disadvantage I see, that one may confuse it with a dict. > > Perhaps with a very cursory inspection. But the lack of any ':' > characters is a pretty quick clue-in. there is one a bigger disadvantage though {} empty set clashes with empty dict {} set() still must be used to generate the empty set or a hack like s = {None}.clear() I think something like {-} as the substitution for empty set will seem bit to perlish for most of us? :) Regards, Daniel From thauta at gmail.com Mon Feb 12 06:29:47 2007 From: thauta at gmail.com (Tomi Hautakoski) Date: Mon, 12 Feb 2007 13:29:47 +0200 Subject: How to use SocketServer with IPv6 Message-ID: Hello, I'm a Python newbie trying to figure out how to use SocketServer with IPv6. I would like to set up a TCPServer working like below but how to tell SocketServer I need to use AF_INET6? import SocketServer import logging as l l.basicConfig(level=l.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') PORT = 5001 class CollectorHandler(SocketServer.BaseRequestHandler): def setup(self): l.info('%s connected!', self.client_address) #self.request.send('hi ' + str(self.client_address) + '\n') def handle(self): data = self.request.recv(1024) l.debug('Client sent this: %s\n', data) def finish(self): l.info('%s disconnected!', self.client_address) #self.request.send('bye ' + str(self.client_address) + '\n') if __name__=='__main__': #server host is a tuple ('host', port) #myserver = SocketServer.ThreadingTCPServer(('', 5001), CollectorHandler) l.info('Collector software starting up, creating TCPServer.') try: myserver = SocketServer.TCPServer(('', PORT), CollectorHandler) l.info('Listening to connections in port %d.', PORT) myserver.serve_forever() except KeyboardInterrupt: pass Thanks for any advice! -- Tomi Hautakoski From skip at pobox.com Mon Feb 5 08:58:00 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 5 Feb 2007 07:58:00 -0600 Subject: in place-ness of list.append In-Reply-To: <740c3aec0702050544v5fc7563cpa334a93745bfcb87@mail.gmail.com> References: <17863.3720.339689.188664@montanaro.dyndns.org> <740c3aec0702050544v5fc7563cpa334a93745bfcb87@mail.gmail.com> Message-ID: <17863.14312.261372.353988@montanaro.dyndns.org> >>>>> "BJ?rn" == BJ?rn Lindqvist writes: BJ?rn> On 2/5/07, skip at pobox.com wrote: >> Bart> #-------------------------------------------------- Bart> def addnumber(alist, num): Bart> """ work around the inplace-ness of .append """ Bart> mylist = alist[:] Bart> mylist.append(num) Bart> return mylist Bart> #-------------------------------------------------- >> >> Such an operation will be O(N**2), and thus expensive if performed >> frequently on lists of moderate length. I've never been tempted to >> do this. BJ?rn> How can that be? Making a copy of a list is O(N), isn't it? Yes, not enough sleep under my belt or caffeine in my system (*) when I wrote those replies. addnumber is O(N). If you are building a binary tree of M elements you're going to wind up with an O(N*M) or O(N**2) cost to build the tree though. Actually, I think in the case of building the binary tree you wind up with an O(N*log N) algorithm since you don't have to traverse the entire set of nodes you've already built to find where to insert the next one. Skip (*) It really sucks when someone's car alarm goes off at 4AM with no visual indication when it's about -5F outside and you have to actually go outside to check and make sure it's not your car (only to find out it's the car directly behind yours)... S From gagsl-py at yahoo.com.ar Mon Feb 19 00:02:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 02:02:55 -0300 Subject: Need an identity operator because lambda is too slow References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> <1171852313.254660.44190@s48g2000cws.googlegroups.com> Message-ID: En Sun, 18 Feb 2007 23:31:53 -0300, Sean McIlroy escribi?: > On Feb 17, 9:59 pm, "Deron Meranda" wrote: > [snip] > > this may be really dense, but i'm curious what's wrong with the > "multiplexer" idiom: > > for item in some_sequence: > item2 = (not some_rare_condition and item) or \ > (some_rare_condition and > some_transform_function(item)) > ..... # more stuff The main concern of the OP was that lambda x:x is slow, so it's better to move the condition out of the loop. Also, this and/or trick does not work when the Boolean value of item is false (like 0, (), []...) -- Gabriel Genellina From gregpinero at gmail.com Tue Feb 20 15:20:03 2007 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 20 Feb 2007 15:20:03 -0500 Subject: How to do a Decorator Here? Message-ID: <312cfe2b0702201220n7d4d3e2o85faf8f6590564b5@mail.gmail.com> Need some decorator help. I have a class. And I want to add behavior to one of this class's methods to be run before the class runs the actual method. Is this what decorators are for? So the class I want to work with is string.Template Let's say I have this: from string import Template a=Template("$var1 is a test") def preprocess(var1): #Real code here will be more complicated, just an example var1=var1.upper() a.substitute(var1="greg") So how can I have preprocess run before substitute is run? I want the user to be able to call a.substitute and have preprocess run automatically. Or is this not what decorators do? I'm trying to avoid subclassing if I can. Thanks in advance for the help. -Greg From bearophileHUGS at lycos.com Tue Feb 20 11:29:19 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 20 Feb 2007 08:29:19 -0800 Subject: builtin set literal In-Reply-To: References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> Message-ID: <1171988959.628359.260710@l53g2000cwa.googlegroups.com> Steven Bethard: > While Python 3.0 is not afraid to break backwards > compatibility, it tries to do so only when there's a very substantial > advantage. I understand, but this means starting already to put (tiny) inconsistencies into Python 3.0... Unrelated: Ruby and Lisp use ? and ! at the end of the function/method names to denote a predicate or a function that mutates in place (With them the list.sort() may be called list.sort!() ). Using Python I usually put an Q at the end of the name for this purpose. Can Py 3.0 support names ending with "?" too? Bye, bearophile From hans_schwaebli at yahoo.com Wed Feb 14 08:47:31 2007 From: hans_schwaebli at yahoo.com (Hans Schwaebli) Date: Wed, 14 Feb 2007 05:47:31 -0800 (PST) Subject: How to print the variable? Message-ID: <345345.69488.qm@web39715.mail.mud.yahoo.com> Hi, am am a Python beginner with Java knowledge background. Infact I need to use Jython. My first beginner question is how to determine of what type a variable is? In program which supports Jython there is a variable called "rc" available. I can use the methods on that variable like rc.logMessage("hello"). But if I try to execute "print "${rc}" it tells me "Invalid variable syntax for attribute 'code' with value 'print "${rc}".' In Java I can print any variable. What I want is to do something like variable.getClass().getName(). Can this be done with that rc variable in Python/Jython scripts? Then I would know how to instantiate the rc variable. I apologize for my beginner questions. I should read more or get a teaching, but the last I won't get and for the first I have not so much time. Thanks in advance. --------------------------------- Now that's room service! Choose from over 150,000 hotels in 45,000 destinations on Yahoo! Travel to find your fit. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sriram.sundararajan at gmail.com Tue Feb 27 09:36:41 2007 From: sriram.sundararajan at gmail.com (Sriram) Date: 27 Feb 2007 06:36:41 -0800 Subject: os.system and quoted strings In-Reply-To: <1172586281.606903.79990@s48g2000cws.googlegroups.com> References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> Message-ID: <1172587001.704618.230120@j27g2000cwj.googlegroups.com> Hello svata, It is always better to compose your string before you send it as a command. try printing your command string out like this : print 'gvim dir+fileName+".txt". You'll see what the problem is. One possible solution is to compose your command string in the following manner: cmd = "gvim %s%s.txt" %(dir, fileName) and simply call os.system with cmd. os.system(cmd) Here is a little more detail on string format specifiers http://docs.python.org/lib/typesseq-strings.html HTH Sriram On Feb 27, 7:24 am, "svata" wrote: > Hello, > > as I'm new to python I've stumbled accros os.system and its not very > well documented usage. > > I use Win XP Pro and Python 2.5. > > Here is the code snippet: > > -------------------------------------------------------------------------------------------------- > > import time > import os > > dir = "C:\\Documents and Settings\\somepath\\" > fileName = time.strftime("%d%m%Y") > os.system('gvim dir+fileName+".txt"') > > --------------------------------------------------------------------------------------------------- > > The problem is that concatenated variable dir+fileName doesn't get > expanded as expected. > > Is there anything I omitted? > > svata From rshepard at nospam.appl-ecosys.com Tue Feb 27 19:48:03 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 28 Feb 2007 00:48:03 GMT Subject: Tuples from List Message-ID: While it should be easy for me to get what I need from a list, it's proving to be more difficult than I expected. I start with this list: [ 6.24249034e-01+0.j 5.11335982e-01+0.j 3.67333773e-01+0.j 3.01189122e-01+0.j 2.43449050e-01+0.j 1.82948476e-01+0.j 1.43655139e-01+0.j 9.91225725e-02+0.j] and I want a list of floats of only the first 6 digits for each value. If I write: for i in listname: print i I get this: (0.624249034424+0j) (0.511335982206+0j) (0.367333773283+0j) (0.301189121704+0j) (0.243449050439+0j) (0.182948475822+0j) (0.14365513894+0j) (0.0991225725344+0j) I know it's embarrassingly simple, but the correct syntax eludes my inexperienced mind. What I want is a list [0.62424, 0.51133, ...] so that I can normalize those values. What is the correct syntax, please? Rich From bdesth.quelquechose at free.quelquepart.fr Sat Feb 3 12:23:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Feb 2007 18:23:52 +0100 Subject: LDAP/LDIF Parsing In-Reply-To: References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> <45c26772$0$4272$426a74cc@news.free.fr> <45c339f3$0$432$426a74cc@news.free.fr> Message-ID: <45c4be21$0$453$426a74cc@news.free.fr> Hallvard B Furuseth a ?crit : > Bruno Desthuilliers writes: > >>Hallvard B Furuseth a ?crit : >> >>>> else: >>>> # all LDAP attribs are multivalued by default, >>>> # even when the schema says they are monovalued >>>> if len(data) == 1: >>>> return data[0] >>>> else: >>>> return data[:] >>> >>>IMHO, this just complicates the client code since the client needs to >>>inserts checks of isinstance(return value, list) all over the place. >>>Better to have a separate method which extracts just the first value of >>>an attribute, if you want that. >> >>Most of the times, in a situation such as the one described by the OP, >>one knows by advance if a given LDAP attribute will be used as >>monovalued or multivalued. Well, this is at least my own experience... > > But if the attribute is multivalued, you don't know if it will contain > just one value or not. If you know which attributes are supposed to be multivalued in your specific application, then it's time to write a more serious, application-specific wrapper. From sjmachin at lexicon.net Thu Feb 15 09:34:53 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 Feb 2007 06:34:53 -0800 Subject: AUX File Writing Error In-Reply-To: References: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> <1171521299.082449.67940@s48g2000cws.googlegroups.com> Message-ID: <1171550093.691486.150530@a75g2000cwd.googlegroups.com> On Feb 16, 12:13 am, "Gabriel Genellina" wrote: > En Thu, 15 Feb 2007 03:34:59 -0300, John Machin > escribi?: > > > On Feb 15, 4:03 pm, thewritersc... at gmail.com wrote: > >> Is there any way I can create an "AUX.csv" file without the error? > > > Probably not. AUX, CON, NUL, PRN, LPT, COM1, COM2 etc (with or without > > an extension) are reserved in Windows for specific devices for > > compatibility with MS-DOS 1.00 programs, which did that for > > compatibility with CP/M. > > (This is OT now) Do you know why "AUX.csv" is invalid too? I can accept > that AUX (without extension) is an invalid filename, but it is quite > different from "AUX.csv" > It is actually a valid file name, but the file is not on disk. I presume that the OP got an error because it was in 'a' (append) mode which requires an existing disk file. See below. C:\junk>copy con aux.csv fubar ^Z 1 file(s) copied. C:\junk>copy con sux.csv fubar ^Z 1 file(s) copied. C:\junk>dir *ux.csv [snip] Directory of C:\junk 16/02/2007 01:19 AM 7 sux.csv 1 File(s) 7 bytes Why? Who knows? We're talking CP/M, MS-DOS and Windows and you want to know why? Probably too lazy to distinguish between 'AUX\0', 'AUX.\0' and 'AUX.XYZ\0' ... probably stopped scanning on reaching the first invalid character. If you're desperate to find out, dial up your nearest RCPM and ask the sysop :-) Cheers, John From kyosohma at gmail.com Mon Feb 5 14:23:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Feb 2007 11:23:47 -0800 Subject: Finding cpu time spent on my program In-Reply-To: <1170664629.719220.249570@k78g2000cwa.googlegroups.com> References: <1170664629.719220.249570@k78g2000cwa.googlegroups.com> Message-ID: <1170703427.559432.155740@k78g2000cwa.googlegroups.com> On Feb 5, 2:37 am, "jm.sur... at no.spam.gmail.com" wrote: > I am trying to measure the time the processor spends on some > operation, and I want this measure to not depend on the current load > of the machine. But doing the following prints different values each > time a run. > > import time > c1 = time.clock() > for x in xrange(0xFFFFF): pass > > c2 = time.clock() > print "Time spent is %f" % (c2-c1) > > Is there a way to measure the number of cpu cycles spent on my program > alone irrespective of the current load etc of the machine. > > - > Suresh One of the best ways to time small snippets of code is python's timeit module. See the docs at http://docs.python.org/lib/module-timeit.html - Mike From uymqlp502 at sneakemail.com Tue Feb 20 18:56:13 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 20 Feb 2007 15:56:13 -0800 Subject: setup.py installation and module search path In-Reply-To: <4OGdnbwDvckpGkbYnZ2dnUVZ_qninZ2d@comcast.com> References: <1172010954.151670.274470@p10g2000cwp.googlegroups.com> <4OGdnbwDvckpGkbYnZ2dnUVZ_qninZ2d@comcast.com> Message-ID: <1172015773.217480.302840@v33g2000cwv.googlegroups.com> Larry Bates wrote: > I'm no expert, but I think what normally happens is the module gets > installed into ../pythonxx/lib/site-packages/ and if it > installs __init__.py file there they get automatically searched. > At least that the way things work for me. But if I don't have root priviledge, that doesn't happen. Is there a setup.py option to get a package installed just in my own account in such a way that my module search path gets updated? From google at mrabarnett.plus.com Tue Feb 6 15:47:06 2007 From: google at mrabarnett.plus.com (MRAB) Date: 6 Feb 2007 12:47:06 -0800 Subject: Recursive zipping of Directories in Windows In-Reply-To: <1170726509.797022.28930@j27g2000cwj.googlegroups.com> References: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> <1170618143.449135.37580@v33g2000cwv.googlegroups.com> <1170726509.797022.28930@j27g2000cwj.googlegroups.com> Message-ID: <1170794826.829468.276830@a34g2000cwb.googlegroups.com> On Feb 6, 1:48 am, "joshbl... at gmail.com" wrote: > On Feb 4, 12:42 pm, "Jandre" wrote: > > > > > On Feb 1, 9:39 pm, Larry Bates wrote: > > > > Jandre wrote: > > > > Hi > > > > > I am a python novice and I am trying to write a python script (most of > > > > the code is borrowed) to Zip a directory containing some other > > > > directories and files. The script zips all the files fine but when it > > > > tries to zip one of the directories it fails with the following > > > > error: > > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > > > > The script I am using is: > > > > > import zipfile, os > > > > > def toZip( directory, zipFile ): > > > > """Sample for storing directory to a ZipFile""" > > > > z = zipfile.ZipFile( > > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > > > ) > > > > def walker( zip, directory, files, root=directory ): > > > > for file in files: > > > > file = os.path.join( directory, file ) > > > > # yes, the +1 is hacky... > > > > archiveName = file[len(os.path.commonprefix( (root, > > > > file) ))+1:] > > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > > > > print file > > > > os.path.walk( directory, walker, z ) > > > > z.close() > > > > return zipFile > > > > > if __name__ == "__main__": > > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > > > > I have tried to set the permissions on the folder, but when I check > > > > the directory permissions it is set back to "Read Only" > > > > > Any suggestions? > > > > > Thanks > > > > Johan Balt > > > > Couple of quick suggestions that may help: > > > > 1) don't use 'file' as a variable name. It will mask > > > the builtin file function. If it hasn't bitten you before > > > it will if you keep doing that. > > > > 2) If you put the target .zip file in the directory you are > > > backing what do you expect the program to do when it comes > > > to the file you are creating as you walk the directory? You > > > haven't done anything to 'skip' it. > > > > 3) Your commonprefix and +1 appears to result in same > > > information that the easier to use os.path.basename() > > > would give you. Double check me on that. > > > > I don't see anything that references C:\\aaa\temp in your > > > code. Does it exist on your hard drive? If so does it > > > maybe contain temp files that are open? zipfile module > > > can't handle open files. You must use try/except to > > > catch these errors. > > > > Hope info helps. > > > > -Larry > > > Thank you Larry. > > I've changed the code as epr your advice. The code is now: > > > import zipfile, os > > > def toZip( directory, zipFile ): > > """Sample for storing directory to a ZipFile""" > > z = zipfile.ZipFile( > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > ) > > def walker( zip, directory, files, root=directory ): > > for f in files: > > f = os.path.join( directory, f ) > > archiveName = os.path.basename(f) > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > > print f > > os.path.walk( directory, walker, z ) > > z.close() > > return zipFile > > > if __name__ == "__main__": > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > > I still get the same error: > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 310, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\Python24\Scripts\dirZip.py", line 20, in ? > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > File "C:\Python24\Scripts\dirZip.py", line 14, in toZip > > os.path.walk( directory, walker, z ) > > File "C:\Python24\lib\ntpath.py", line 329, in walk > > func(arg, top, names) > > File "C:\Python24\Scripts\dirZip.py", line 12, in walker > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > > File "C:\Python24\lib\zipfile.py", line 405, in write > > fp = open(filename, "rb") > > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp' > > > c:\\aaa\\temp is a directory in the directory I an trying to zip. I > > want to use this script to back up my work once a day and would like > > to > > keep the directory structure as is. I can zip the files in c:\aaa\tem > > fine so I guess that there aren't any open files in the directory. > > Any more ideas? > > Hi Jandre, > > Your code is treating the directory as a file and trying to open it > and read its bytes to zip them. You'll need to differentiate between > files and directories. > > You'll need to check out the Zip module to see how it expects files > that should be nested within folders. I believe you'll need to set the > archive name for the nested files to something like \\temp\\file.ext > etc. > In my experience, zip files don't contain nested folders, instead they contain a 'flat' list of files. Files in subfolders are represented by relative path names containing slashes and empty subfolders are represented by relative paths ending in a slash,.for example "File1.txt", "Folder1/File2.dat", "Folder2/Folder3/". This seems to work for me! :-) From steven.bethard at gmail.com Thu Feb 15 10:25:43 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 15 Feb 2007 08:25:43 -0700 Subject: builtin set literal In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > Hello, > > lst = list((1,2,3)) > lst = [1,2,3] > > t = tupel((1,2,3)) > t = (1,2,3) > > s = set((1,2,3)) > s = ... > > it would be nice feature to have builtin literal for set type > maybe in P3 .. what about? > s = <1,2,3> In Python 3.0, this looks like:: s = {1,2,3} More info here: http://www.python.org/dev/peps/pep-3100/ STeVe From bbbart at inGen.be Fri Feb 2 07:57:40 2007 From: bbbart at inGen.be (Bart Van Loon) Date: Fri, 2 Feb 2007 17:57:40 +0500 Subject: Why does this not work? References: <1170420108.701432.77090@q2g2000cwa.googlegroups.com> Message-ID: It was 2 Feb 2007 04:41:48 -0800, when alain wrote: > I tried the following: > > myobj=object() > myobj.newattr=5 > > results in: > > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'newattr' > > Any idea? I think it's because... object has no attribute 'newattr' what else is there left to say? try: myobj=object() print dir(myobj) does that contain 'myattr'? -- groetjes, BBBart "To make a bad day worse, spend it wishing for the impossible." -Calvin From gherron at digipen.edu Fri Feb 9 03:00:06 2007 From: gherron at digipen.edu (Gary Herron) Date: Fri, 09 Feb 2007 00:00:06 -0800 Subject: UNIX shell in Python? In-Reply-To: References: Message-ID: <45CC2A06.3070106@digipen.edu> Deniz Dogan wrote: > Hello. > > I was thinking about writing a UNIX shell program using Python. Has > anyone got any experience on this? Is it even possible? I have > programmed a simple shell in C before and I came to think about how > perfect Python would be for parsing user input. > > Regards, > Deniz Dogan > Not only *can* it be done, but it *has* been done and well: See IPython at: http://ipython.scipy.org/moin/ Gary Herron From mathiasDOTfranzius at webDELETEME.de Tue Feb 13 09:25:42 2007 From: mathiasDOTfranzius at webDELETEME.de (Mathias) Date: Tue, 13 Feb 2007 15:25:42 +0100 Subject: Segmentation faults using threads Message-ID: Dear ng, I use the thread module (not threading) for a client/server app where I distribute large amounts of pickled data over ssh tunnels. Now I get regular Segmentation Faults during high load episodes. I use a semaphore to have pickle/unpickle run nonthreaded, but I still get frequent nondeterministic segmentation faults. Since there is no traceback after a sf, I have no clue what exactly happened, and debugging a multithreaded app is no fun anyway :( Can someone recommend me how to get extra info during such a crash? Or any other opinion on where the problem might lie? Thanks a lot, Mathias From researchbase at gmail.com Mon Feb 12 13:06:30 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Mon, 12 Feb 2007 23:36:30 +0530 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: Message-ID: os.start does not work.. attribute error. regards. Krishnakant. From steve at holdenweb.com Thu Feb 15 07:02:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 12:02:40 +0000 Subject: Newbie Question In-Reply-To: <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > bruno.desthuilliers at gmail.com wrote: >> On 9 f?v, 14:06, Stef Mientki wrote: >>>>> will explain the rest >>>> Delphi is a (dying) proprietary, MS-Windows-only[1] software relying >>>> on a low-level language. >>> Well it may be dying, >>> but for the moment it beats Python with a factor of 10, >>> when it comes to user (the majority of PC users) friendly GUI ;-) >> Would you mind explaining yourself and backing your above assertion ? >> Like, ie, on which points does Delphi "beats" Python wrt/ GUIs, what >> special magic would make so that GUIs designed with Delphi would be >> more "user-friendly", and where does this "factor 10" comes from ? >> > Maybe I should have written it in quotes "factor of 10" ;-) > But here are a few points > - in Delphi the GUI design itself is done in a graphical environment, making it much easier and faster Of course. You are comparing a Pascal-based IDE to a programming language. You might as well say "Visual Studio is better than C". [...] > but to be honest ... > ... I never even tried to write a GUI in Python, ... > ... just looked at others examples, > ... and still not seen what I can perform in Delphi ;-) Ignorance is bliss. This would apparently make you a troll. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From python at hope.cz Sat Feb 10 08:29:23 2007 From: python at hope.cz (Johny) Date: 10 Feb 2007 05:29:23 -0800 Subject: How to find all the same words in a text? Message-ID: <1171114163.781621.263210@s48g2000cws.googlegroups.com> I need to find all the same words in a text . What would be the best idea to do that? I used string.find but it does not work properly for the words. Let suppose I want to find a number 324 in the text '45 324 45324' there is only one occurrence of 324 word but string.find() finds 2 occurrences ( in 45324 too) Must I use regex? Thanks for help L. From lbates at websafe.com Fri Feb 23 10:52:06 2007 From: lbates at websafe.com (Larry Bates) Date: Fri, 23 Feb 2007 09:52:06 -0600 Subject: Rational numbers In-Reply-To: <20070223103519.08f25af9@localhost> References: <20070223103519.08f25af9@localhost> Message-ID: <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> Martin Manns wrote: > Hi, > > I am starting to use rationals and since I found no batteries included, > I tried out the mxNumber package. > > However, I get strange warnings on comparison operations > (which however seem to yield correct results): > > --- > $ python > Python 2.4.3 (#1, Jan 15 2007, 15:46:19) > [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from mx.Number import * >>>> a=Rational(0,1) >>>> a > 0/1 >>>> str(a) > '0.0' >>>> b=-5000000000000000000000000000000000000000000000000000000000 >>>> b > -5000000000000000000000000000000000000000000000000000000000L >>>> a==b > __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1 > False > --- > > How do I get rid of these warnings? > > Is there any rational number library around that > 1) is comparably fast for large denominators > 2) allows deriving types from Rationals without wrapping? > > Regards > > Martin > > P.S. The respective mailing list does not like me, so that I try my > luck here. I quick search of Google turned up: http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg http://calcrpnpy.sourceforge.net/clnum.html http://gmpy.sourceforge.net/ -Larry From wilson.max at gmail.com Sat Feb 17 11:46:24 2007 From: wilson.max at gmail.com (Max Wilson) Date: 17 Feb 2007 08:46:24 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <53nt2aF1sn581U1@mid.uni-berlin.de> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: <1171730784.720419.297310@m58g2000cwm.googlegroups.com> On Feb 17, 1:35 am, "Diez B. Roggisch" wrote: > But I've done extensive, cross-platform development with Qt. And can > assert that it is unmatched in productivity and feature richness, > especially when combined with python. And certainly beat VB, and most > probably even delphi (albeit I haven't done too much in that to really > put all my weight behind these words). [snip] Thanks for the pointer--my hobby right now is a GURPS-based wargame and I'm still looking for a good front-end generator. pygsear seems nice in a lot of ways, but it's possible Qt will require less development on my part. (I need to have one window, but split into separate panels in the style of old RPGs like Wizardry and Bard's Tale.) I'll have a look. -Maximilian From casevh at comcast.net Fri Feb 23 17:52:30 2007 From: casevh at comcast.net (casevh at comcast.net) Date: 23 Feb 2007 14:52:30 -0800 Subject: Rational numbers In-Reply-To: <1172268954.974348.93540@q2g2000cwa.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172268954.974348.93540@q2g2000cwa.googlegroups.com> Message-ID: <1172271150.718838.10170@s48g2000cws.googlegroups.com> > Am I hallucinating? Didn't I see at least some version > of gmpy for Python 2.5 on SourceForge awhile back? > I distinctly remember thinking that I don't have to > direct people to your site, but SourceForge is not > showing anything beyond vesion 1.01 for Python 2.4. Alex released versions 1.02 and 1.03 as CVS updates only. I think he may have made an announcement that 1.02 included alpha support for Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there has been an official release, though. casevh From wolf_tracks at invalid.com Wed Feb 7 18:50:48 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 07 Feb 2007 23:50:48 GMT Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: Robert Kern wrote: > W. Watson wrote: >> For some reason Python 2.2.4 cannot find the Numeric module. It's been >> suggested that I should re-install the Numeric file. How do that? Also the >> PIL. The three install files are: >> python-2.4.4.msi >> PIL-1.1.5.win32-py2.4.exe >> Numeric-24.2.win32-py2.4.exe > > The latter two are executable installers. Run them. > I have re-run Numeric. The python program still cannot detect the Numeric module. In IDLE, Run Modules shows: > Traceback (most recent call last): > File > "C:\Sandia_Meteors\NewSentinel\Test_Install_YG\Python_Install\sentuser.py", > line 8, in > from Numeric import * > ImportError: No module named Numeric sentuser.py looks like: #!/usr/bin/python # Sentinel User Program # J C Chavez # jochave at sandia.gov from Tkinter import * from Numeric import * import Image import ImageChops import ImageTk ... Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet 'I think it not improbable that man, like the grub that prepares a chamber for the winged thing it has never seen but is to be, may have... destinies that he does not understand." -- Oliver Wendell Holmes -- Web Page: From Kiran.Karra at gmail.com Thu Feb 1 22:56:26 2007 From: Kiran.Karra at gmail.com (Kiran) Date: 1 Feb 2007 19:56:26 -0800 Subject: python executing windows exe In-Reply-To: <1170372305.523749.295580@m58g2000cwm.googlegroups.com> References: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> <1170372305.523749.295580@m58g2000cwm.googlegroups.com> Message-ID: <1170388586.167723.293830@l53g2000cwa.googlegroups.com> On Feb 1, 6:25 pm, "aspineux" wrote: > First look if your .exe will accept to work that way ! > try in a DOS prompt > > > echo yourfilename | nec2d.exe > > or if the program expect more input, write them all in a file > ( myinputs.txt ) and try : > > > nec2d.exe < myinputs.txt > > If it works looks for module subprocess and more precisely object > subprocess.popen and method comunicate > > On 1 f?v, 23:57, "Kiran" wrote: > > > Hi everybody, > > I am making python run an executable using the os module. Here is > > my question. The executable, once it is running, asks the user to > > input a filename that it will process. Now, my question is how do i > > automate this. let me make this clear, it is not an argument you pass > > in when you type in the exe. An example below illustrates: > > > THIS IS NOT WHAT YOU DO: Hi everybody, What you guys said helped out a lot and I got it to do what I wanted. thanks!, Kiran > > nec2d.exe couple1.nec # couple1.nec is the > > file you want to prcess > > > rather, what you do is in windows cmd: > > > nec2d.exe > > **** PROGRAM PRINTS OUT STUFF***** > > **** PROGRAM PRINTS OUT STUFF***** > > **** PROGRAM PRINTS OUT STUFF***** > > **** PROGRAM PRINTS OUT STUFF***** > > Please enter input file: <--------- THIS IS WHERE THE USER IS ASKED > > TO TYPE IN THE FILENAME > > > everybody thanks for your help > > -- Kiran From free.condiments at gmail.com Fri Feb 16 17:31:04 2007 From: free.condiments at gmail.com (Sam) Date: Fri, 16 Feb 2007 22:31:04 +0000 Subject: Pep 3105: the end of print? In-Reply-To: <1171662509.736715.54400@t69g2000cwt.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> <1171662509.736715.54400@t69g2000cwt.googlegroups.com> Message-ID: On 16 Feb 2007 13:48:29 -0800, Klaas wrote: > 3. in your code: > try: > from compat26 import print2 > except (ImportError, SyntaxError): > # python 3.0 > print2 = print Python 2.5c1 (r25c1:51305, Aug 17 2006, 10:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> try: from compat26 import print2 except (ImportError, SyntaxError): # python 3.0 print2 = print SyntaxError: invalid syntax >>> try: pass except (ImportError, SyntaxError): # python 3.0 print2 = print SyntaxError: invalid syntax Any and all aliasing must happen in compat26.py. My suggested solution is this: #_compat30.py print2 = print #compat.py try: from _compat30 import print2 except SyntaxErorr, ImportError): def print2(): .... --Sam From bdesth.quelquechose at free.quelquepart.fr Thu Feb 15 15:07:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 15 Feb 2007 21:07:33 +0100 Subject: Which Object Database would you recommend for cross platform application? In-Reply-To: References: Message-ID: <45d4b621$0$23987$426a74cc@news.free.fr> Thomas Ploch a ?crit : > Hello folks, > > I am currently developing an open source Event Managment software > (events in real-life, like concerts, exhibitions etc. :-) ) using wx for > the GUI, and I need an Object database. "need" ? Why ? (I don't mean you shouldn't use one, just questionning the "need")... > Since this is the first time I > actually need doing this, I wondered if anybody here could recommend > one. It can be fairly simple. It doesn't need threading support and will > only host one client (the application, but I am thinking about making > this database accessible via the web, but this is still far in the > future), If you plan on making it accessible TTW, then you do need support for concurrent access. > although the database might get big (around 1GiB). It should be > available for linux, mac os and windows. > > I looked into ZODB, but thats totally overloaded for my purpose. I > looked into Durus (a re-implementation of ZODB, but without this > overloaded stuff, but the documentation is very thin). Both of them > don't really appeal. The ZODB is quite easy to use, and it's probably the most used Python OODB actually. I have no experience with Durus, but it looked quite close when I last browsed the project page. Else you may want to look at Metakit, KirbyBase etc http://wiki.python.org/moin/DatabaseInterfaces > So I wondered if any of you could recommend one that (more or less) best > fits the described conditions. sqlite +SQLAlchemy. Yes, I know, that's not an object DB. From nick at craig-wood.com Sat Feb 10 05:30:11 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 10 Feb 2007 04:30:11 -0600 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> <1171016992.962017.10540@m58g2000cwm.googlegroups.com> <87mz3mlxsf.fsf@tnoo.net> <1171074036.082831.283300@k78g2000cwa.googlegroups.com> <1171081888.750035.294170@h3g2000cwc.googlegroups.com> Message-ID: George Sakkis wrote: > On Feb 9, 9:20 pm, bearophileH... at lycos.com wrote: > > This is a bit simpler, but probably there are simpler solutions using > > modular arithmetic: > > > > l = [1] > > for _ in range(15): > > print ''.join(" *"[x] for x in l) > > l = [1] + [l[i+1]^l[i] for i in range(len(l)-1)] + [1] > > > > Bye, > > bearophile > > Here's another one, adapted from the example (in Java) in Wikipedia's > entry (http://en.wikipedia.org/wiki/Sierpinski_triangle): > > N=15 > for x in xrange(N,0,-1): > print ''.join('* '[x&y!=0] for y in xrange(N+1-x)) > This is my solution after a few minutes thought. It uses a different algorithm for generating the triangle. If python could output binary numbers it would be more elegant... >>> n = 1 >>> for i in range(16): ... print ("%X" % n).replace('0', ' ').replace('1', '*') ... n = n ^ (n << 4) ... * ** * * **** * * ** ** * * * * ******** * * ** ** * * * * **** **** * * * * ** ** ** ** * * * * * * * * **************** -- Nick Craig-Wood -- http://www.craig-wood.com/nick From naima.mans at gmail.com Tue Feb 27 05:20:57 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 27 Feb 2007 02:20:57 -0800 Subject: spawnl and waitpid In-Reply-To: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> Message-ID: <1172571657.574357.212360@h3g2000cwc.googlegroups.com> i forgot ... thanks for any help :) From sjmachin at lexicon.net Sat Feb 10 23:57:52 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 Feb 2007 20:57:52 -0800 Subject: os.tmpfile() -> permission denied (Win XP) Message-ID: <1171169872.507298.196990@j27g2000cwj.googlegroups.com> Hi, Here's what's happening: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. | >>> import os | >>> os.tmpfile() Traceback (most recent call last): File "", line 1, in OSError: [Errno 13] Permission denied but tempfile.mkstemp() works: >>> import tempfile >>> tempfile.mkstemp() (3, 'c:\\docume~1\\sjm\\locals~1\\temp\\tmpnfuk9i') This is Windows XP Pro SP2. The user with the problem is _not_ an administrator. It works OK when logged on as an administrator. I am using the mode which enables having multiple users logged on and switching between them. The problem happens with Pythons back to 2.2. Python 2.1 on Windows doesn't seem to have a tmpfile() function in the os module. On a Windows 2000 SP4 box, with a "Power User" [part way between administrator and vanilla user] Python 2.3.5 os.tmpfile() works OK. AFAICT Win XP doesn't have this intermediate level of user. Questions: 1. Before I start checking what permissions who has to do what to which, what directory is it likely to be trying to open the temp file in? C:\WINDOWS\TEMP....? 2. What is the general advice about whether to use os.tmpfile() or the functions in the tempfile module? I'm presuming that as os.tmpfile() is ultimately calling tmpfile() in the C stdio library, nobody would have gone to the effort of making the tempfile module just to reproduce stdio functionality, but AFAICT there's no guidance in the docs. Maybe I should be talking to the authors of the package that is using os.tmpfile() :-) TIA for any clues, John From laurent.pointal at limsi.fr Fri Feb 2 08:42:56 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Feb 2007 14:42:56 +0100 Subject: Why does this not work? In-Reply-To: <1170421703.561821.326840@k78g2000cwa.googlegroups.com> References: <1170420108.701432.77090@q2g2000cwa.googlegroups.com> <1170421703.561821.326840@k78g2000cwa.googlegroups.com> Message-ID: alain a ?crit : > On Feb 2, 1:57 pm, Bart Van Loon wrote: >> It was 2 Feb 2007 04:41:48 -0800, when alain wrote: >> >>> I tried the following: >>> myobj=object() >>> myobj.newattr=5 >>> results in: >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> AttributeError: 'object' object has no attribute 'newattr' >>> Any idea? >> I think it's because... object has no attribute 'newattr' >> >> what else is there left to say? >> >> try: >> >> myobj=object() >> print dir(myobj) >> >> does that contain 'myattr'? >> >> -- >> groetjes, >> BBBart >> >> "To make a bad day worse, spend it wishing for the impossible." -Calvin > > > What about this: > class Object(object):pass > myobj=Object() > myobj.newattr=5 > > and it works !!! > Python allows the dynamic creation of attributes for an instance of an > object. See previous discussion in this group "Re: Why don't have an object() instance a __dict__ attribute by default?" (2007-01-30) http://groups.google.fr/group/comp.lang.python/browse_thread/thread/a7e952d01b2eea68/961dec95bc20877e?lnk=st&q=&rnum=1#961dec95bc20877e A+ Laurent. From redawgts at gmail.com Wed Feb 14 17:05:04 2007 From: redawgts at gmail.com (redawgts) Date: 14 Feb 2007 14:05:04 -0800 Subject: try...except...finally problem in Python 2.5 In-Reply-To: <7x3b58jybl.fsf@ruckus.brouhaha.com> References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> Message-ID: <1171490704.557716.306650@a34g2000cwb.googlegroups.com> Thanks everybody, that helped alot. From gagsl-py at yahoo.com.ar Tue Feb 6 22:08:48 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Feb 2007 00:08:48 -0300 Subject: IOError: [Errno 4] Interrupted system call References: <5c62a320702061709s41dd7af2kd99be68e3afe3d58@mail.gmail.com> Message-ID: En Tue, 06 Feb 2007 22:09:00 -0300, Marco escribi?: > in my old script, I usually use os.popen2() to get info from standard > unix(LinuX) program like ps,ifconfig... > > Now, I write a OO-based programme, I still use os.popen2( check > whether mplayer still working via ps command ), but some things I got > the following message: > > Traceback (most recent call last): > File "./mkt.py", line 351, in loop_timeout > self.process(self.event.get_next()) > File "./mkt.py", line 361, in process > self.player.play(command[1]) > File "./mkt.py", line 107, in play > if self.is_playing(): > File "./mkt.py", line 78, in is_playing > info = rfd.readlines() > IOError: [Errno 4] Interrupted system call I don't know if this is a valid behavior or not, perhaps it's a bug inside Python signal handling, but anyway, why don't you just catch the exception? -- Gabriel Genellina From cbarker at austin.utexas.edu Tue Feb 27 19:01:40 2007 From: cbarker at austin.utexas.edu (Barker, CJ) Date: Tue, 27 Feb 2007 18:01:40 -0600 Subject: Python, SOAP & SSL Message-ID: <5B59870CA143DD408BD6279374B74C8B053F40DC@MAIL02.austin.utexas.edu> Was this ever solved? I'm running into the same problem right now. Any help is much appreciated. -cjb From jstroud at mbi.ucla.edu Thu Feb 22 15:21:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Feb 2007 12:21:23 -0800 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? In-Reply-To: <1172144943.794384.73270@s48g2000cws.googlegroups.com> References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> Message-ID: openopt at ukr.net wrote: > I don't know to which forum should I post the message > I hope someone related to the Python kernel development will read & > consider the idea > I'm (a former? meanwhile not sure) MATLAB user & it's very annoing > typing each time for example > while i: > print i > ... > instead of > while i > print i > ... > of course if all is written in a single line ':' I guess should not be > omited > > Thank you for you suggestions. > Sorry my bad English. > > WBR, Dmitrey > Its a compromise in that python has way-less of this kind of cruft than a lot of other languages. James From grahamd at dscpl.com.au Mon Feb 5 17:45:21 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 5 Feb 2007 14:45:21 -0800 Subject: Python does not play well with others In-Reply-To: <1170712668.870316.247580@q2g2000cwa.googlegroups.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> Message-ID: <1170715521.475189.18330@k78g2000cwa.googlegroups.com> On Feb 6, 8:57 am, "sjdevn... at yahoo.com" wrote: > On Feb 5, 12:52 pm, John Nagle wrote: > > > > > sjdevn... at yahoo.com wrote: > > > John Nagle wrote: > > > >>Graham Dumpleton wrote: > > > >>>On Feb 4, 1:05 pm, Paul Rubin wrote: > > > >>>>"Paul Boddie" writes: > > >> Realistically,mod_pythonis a dead end for large servers, > > >>because Python isn't really multi-threaded. The Global Python > > >>Lock means that a multi-core CPU won't help performance. > > > > The GIL doesn't affect seperate processes, and any large server that > > > cares about stability is going to be running a pre-forking MPM no > > > matter what language they're supporting. > > > Pre-forking doesn't reduce load; it just improves responsiveness. > > You still pay for loading all the modules on every request. > > No, you don't. Each server is persistent and serves many requests-- > it's not at all like CGI, and it reuses the loaded Python image. > > So if you have, say, an expensive to load Python module, that will > only be executed once for each server you start...e.g. if you have > Apache configured to accept up to 50 connections, the module will be > run at most 50 times; once each of the 50 processes has started up, > they stick around until you restart Apache, unless you've configured > apache to only serve X requests in one process before restarting it. > (The one major feature thatmod_python_is_ missing is the ability to > do some setup in the Python module prior to forking. That would make > restarting Apache somewhat nicer). There would be a few issues with preloading modules before the main Apache child process performed the fork. The first is whether it would be possible for code to be run with elevated privileges given that the main Apache process usually is started as root. I'm not sure at what point it switches to the special user Apache generally runs as and whether in the main process the way this switch is done is enough to prevent code getting back root privileges in some way, so would need to be looked into. The second issue is that there can be multiple Python interpreters ultimately created depending on how URLs are mapped, thus it isn't just an issue with loading a module once, you would need to create all the interpreters you think might need it and preload it into each. All this will blow out the memory size of the main Apache process. There is also much more possibility for code, if it runs up extra threads, to interfere with the operation of the Apache parent process. One particular area which could be a problem is where Apache wants to do a restart, as it will attempt to unload the mod_python module and reload it. Right now this may not be an issue as mod_python does the wrong thing and doesn't shutdown Python allowing it to be reinitialised when mod_python is reloaded, but in mod_wsgi (when mod_python isn't also being loaded), it will shutdown Python. If there is user code executing in a thread within the parent process this may actually stop mod_wsgi from cleanly shutting down Python thus causing Apache to hang. All up, the risks of loading extra modules in the parent process aren't worth it and could just result in things being less stable. Graham From grante at visi.com Sun Feb 11 22:12:44 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 12 Feb 2007 03:12:44 -0000 Subject: Read/write 2D data from/to file..? References: <1171244850.077289.130330@s48g2000cws.googlegroups.com> <12svjvrpeev18fe@corp.supernews.com> Message-ID: <12svmpco0o05lc1@corp.supernews.com> On 2007-02-12, Grant Edwards wrote: > On 2007-02-12, mech point wrote: >> >> I was able to read the data from file into a two dimensional array >> (lists) >> >> rows=[map(float,line.split())for line in file("data")] >> >> but How to write them back into the file. > > for r in rows: > file.write(" ".join(map(str,r)) + "\n") Doh. Bad choice of names for my file object: f = file("data","w") for r in rows: f.write(" ".join(map(str,r)) + "\n") You can do it on one line if you want, but I find the above a little bit clearer. -- Grant Edwards grante Yow! Spreading peanut at butter reminds me of visi.com opera!! I wonder why? From http Tue Feb 20 10:10:46 2007 From: http (Paul Rubin) Date: 20 Feb 2007 07:10:46 -0800 Subject: Sorting directory contents References: Message-ID: <7xmz38q2yx.fsf@ruckus.brouhaha.com> Wolfgang Draxinger writes: > src_file_paths = dict() > for fname in os.listdir(sourcedir): > fpath = sourcedir+os.sep+fname > if not match_fname_pattern(fname): continue > src_file_paths[os.stat(fpath).st_mtime] = fpath > for ftime in src_file_paths.keys().sort(): > read_and_concatenate(src_file_paths[ftime]) Note you have to used sorted() and not .sort() to get back a value that you can iterate through. Untested: from itertools import ifilter goodfiles = ifilter(match_fname_pattern, (sourcedir+os.sep+fname for \ fname in os.listdir(sourcedir)) for f,t in sorted((fname,os.stat(f).st_mtime) for fname in goodfiles, key=lambda (fname,ftime): ftime): read_and_concatenate(f) If you're a lambda-phobe you can use operator.itemgetter(1) instead of the lambda. Obviously you don't need the separate goodfiles variable but things get a bit deeply nested without it. From horpner at yahoo.com Thu Feb 15 11:37:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Feb 2007 17:37:18 +0100 Subject: f---ing typechecking References: <1171526027.568047.186800@v33g2000cwv.googlegroups.com> Message-ID: On 2007-02-15, Paul McGuire wrote: > Since tuples are immutable, I think of them as fixed data objects with > some simple sequential structure, as opposed to lists which are much > more dynamically accessible/updateable data containers. Me, too. There are plenty of things that aren't strictly a sequence, but which you sometimes want to iterate over anyhow. If I had a set of fast, overpriced luxury cars in my garage, I would sometimes want to do something to each one (like wash them), even though they really aren't in any sequence. Dictionary keys are the same sort of thing. Even though they aren't in any sequence, it's still useful to iterate over them. -- Neil Cerutti From nospam at riddergarn.dk Tue Feb 13 09:06:17 2007 From: nospam at riddergarn.dk (NOSPAM plz) Date: Tue, 13 Feb 2007 15:06:17 +0100 Subject: Mulig SPAM: float print formatting In-Reply-To: References: Message-ID: <45D1C5D9.6030504@riddergarn.dk> hg skrev: > Hi, > > Considering the float 0.0, I would like to print 00.00. > > I tried '%02.02f' % 0.0 ... but I get 0.00 > > Any clue ? > > Thanks, > > hg > > Try this: a = 45.45 # the floating number print "some text", print a, print "some text again" or just this: print "some text", print 45.45, print "some text again" Hope it helped :D Andreas From mathiasDOTfranzius at webDELETEME.de Tue Feb 13 13:39:51 2007 From: mathiasDOTfranzius at webDELETEME.de (Mathias) Date: Tue, 13 Feb 2007 19:39:51 +0100 Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: John Nagle wrote: > Daniel Nogradi wrote: >>> I use the thread module (not threading) for a client/server app where I >>> distribute large amounts of pickled data over ssh tunnels. > > What module are you using for SSH? > > What's in your program that isn't pure Python? > The problem is probably in some non-Python component; you shouldn't > be able to force a memory protection error from within Python code. > > Also note that the "marshal" module may be unsafe. > > John Nagle I'm using os.popen2() to pipe into an ssh session via stdin/stdout. That's probably not the elegant way... Other modules: scipy 0.3.2 (with Numeric 24.2) and python 2.4 Does pickle/cPickle count as part of the marshal module? Mathias From ruan at jcmills.com Wed Feb 7 13:10:29 2007 From: ruan at jcmills.com (Ruan) Date: Wed, 7 Feb 2007 13:10:29 -0500 Subject: Why doesn't my heapify work? References: <52uiomF1olkevU1@mid.uni-berlin.de> Message-ID: Can't range go from larger to smaller? "Diez B. Roggisch" wrote in message news:52uiomF1olkevU1 at mid.uni-berlin.de... > Dongsheng Ruan wrote: > >> I want to turn an Array into a heap, but my code just doesn't work: no >> change after execution. >> >> A=[3,5,4,9,6,7] >> m=len(A)-1 >> >> >> >> for i in range(m,1): >> t=(i-1)/2 >> if A[i]>A[t]: >> A[i],A[t]=A[t],A[i] > > First of all, there is the module heapq that will just do it. > > And then you seem to misunderstand how the range-function works. range(m, > 1) > will always be the empty list. See > > pydoc range > > for how it operates. > > Overall, your code is very unpythonic, to say the least. I suggest you > start > reading the python tutorial first: > > http://docs.python.org/tut/ > > Especially the looping techniques section: > > http://docs.python.org/tut/node7.html#SECTION007600000000000000000 > > Diez From tiedon_jano at hotmail.com Sun Feb 4 05:31:01 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 04 Feb 2007 10:31:01 GMT Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Message-ID: Stef Mientki kirjoitti: > Is it possible to change the searchpath for modules on the flight, > under winXP ? What do you mean by *on the flight*: inside IDLE? using the command line? > Most preferred is some command to extend the searchpath. > (the environment variable PYTHONPATH needs a reboot) > No, it doesn't. PYTHONPATH can be updated somewhere in the environment options (sorry: I've got a Finnish language XP version, so I don't remember the exact terms) and the new path comes in effect immediately i.e. the launches after that see the new definition. That way of changing the PYTHONPATH is a little difficult, though. In command line usage i.e. CMD.EXE I have been using these kinds of bat files to alternate between versions 2.4 and 2.5 of Python. (These were suggested earlier by someone in this group I think): === Py24.bat (Py25.bat has Python25 instead of Python24 in it) === @echo off if .%1.==.. goto NODEV set DEMOHOME=%1 goto CONT :NODEV set DEMOHOME=C: :CONT set PYTHONHOME=%DEMOHOME%\Python24 set PYTHONPATH=%PYTHONHOME%; set PYTHON=%PYTHONHOME%\python.exe set PYTHONW=%PYTHONHOME%\pythonw.exe set PATH=%PYTHONHOME%;%PATH% === Py.bat (to launch Python) === "%PYTHON%" "%1.py" "%2" "%3" "%4" "%5" "%6" "%7" "%8" "%9" > thanks, > Stef Mientki HTH, Jussi From lbates at websafe.com Fri Feb 23 10:44:40 2007 From: lbates at websafe.com (Larry Bates) Date: Fri, 23 Feb 2007 09:44:40 -0600 Subject: Finding non ascii characters in a set of files In-Reply-To: <1172243566.906121.189930@h3g2000cwc.googlegroups.com> References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: <9sidnRutcqCLkULYnZ2dnUVZ_gydnZ2d@comcast.com> Peter Bengtsson wrote: > On Feb 23, 2:38 pm, b... at yahoo.com wrote: >> Hi, >> >> I'm updating my program to Python 2.5, but I keep running into >> encoding problems. I have no ecodings defined at the start of any of >> my scripts. What I'd like to do is scan a directory and list all the >> files in it that contain a non ascii character. How would I go about >> doing this? >> > > How about something like this: > content = open('file.py').read() > try: > content.encode('ascii') > except UnicodeDecodeError: > print "file.py contains non-ascii characters" > > The next problem will be that non-text files will contain non-ASCII characters (bytes). The other 'issue' is that OP didn't say how large the files were, so .read() might be a problem. -Larry From Shawn at Milochik.com Thu Feb 8 11:58:49 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Thu, 8 Feb 2007 11:58:49 -0500 Subject: Strings in Python In-Reply-To: <45CB5248.5060902@islandtraining.com> References: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> <45CB5248.5060902@islandtraining.com> Message-ID: <2dc0c81b0702080858i109c48bdg9e47e8aecd9c8f92@mail.gmail.com> On 2/8/07, Gary Herron wrote: > Johny wrote: > > Playing a little more with strings, I found out that string.find > > function provides the position of > > the first occurance of the substring in the string. > > Is there a way how to find out all substring's position ? > > To explain more, > > let's suppose > > > > mystring='12341' > > import string > > > > > >>>> string.find(mystring ,'1') > >>>> > > 0 > > > > But I need to find the possition the other '1' in mystring too. > > Is it possible? > > Or must I use regex? > > Thanks for help > > L > > > > > You could use a regular expression. The re module has s function > "findall" that does what you want. > > Also, if you read the documentation for strings find method, you'll find: > > 1 S.find(sub [,start [,end]]) -> int > 2 > 3 Return the lowest index in S where substring sub is found, > 4 such that sub is contained within s[start,end]. Optional > 5 arguments start and end are interpreted as in slice notation. > 6 > 7 Return -1 on failure. > > So put your find in a loop, starting the search one past the previously > found occurrence. > > i = string.find(mystring, i+1) > > Gary Herron > > > -- > http://mail.python.org/mailman/listinfo/python-list > Speaking of regex examples, that's basically what I did in the script below which James Kim and I were collaborating on yesterday and this morning, as a result of his thread. This matches not only a string, but a regex, then loops through each match to do something to it. I hope this helps. I submitted this to the list for recommendations on how to make it more Pythonic, but at least it works. Here are the most important, stripped down pieces: #! /usr/bin/python import re #match a date in this format: 05/MAR/2006 regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") for line in infile: matches = regex.findall(line) for someDate in matches: newDate = #do something here line = line.replace(someDate, newDate) Here is the full script: #! /usr/bin/python import sys import re month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} infile=file('TVA-0316','r') outfile=file('tmp.out','w') def formatDatePart(x): "take a number and transform it into a two-character string, zero padded" x = str(x) while len(x) < 2: x = "0" + x return x regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") for line in infile: matches = regex.findall(line) for someDate in matches: dayNum = formatDatePart(someDate[1:3]) monthNum = formatDatePart(month[someDate[4:7]]) yearNum = formatDatePart(someDate[8:12]) newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) line = line.replace(someDate, newDate) outfile.writelines(line) infile.close outfile.close From bdesth.quelquechose at free.quelquepart.fr Fri Feb 16 16:38:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 16 Feb 2007 22:38:46 +0100 Subject: sorting list of tuples by second (third...) tuple item In-Reply-To: References: Message-ID: <45d61cf9$0$28355$426a74cc@news.free.fr> Giovanni Toffoli a ?crit : > Hi, > > I'm not in the mailing list. > By Googling, I stepped into this an old post: (Thu Feb 14 20:40:08 CET > 2002) of Jeff Shannon: > http://mail.python.org/pipermail/python-list/2002-February/128438.html > > <<< > def SortOnItem(mylist, index): > templist = [ (line[index], line) for line in mylist ] > templist.sort() > return [ line[1:] for line in templist ] > > What this does is build a separate list containing a tuple of the > element that you want to sort on, and the entire line, sorts that > list (by the first element, of course), and then strips that first > element off .. It's the "decorate/sort/undecorate" pattern. You may also google for "schwarzian transform" >>>> > > It seems to me that the tuples aren't sorted only by the first element > but, I suppose, other elements are also used if needed to discriminate. Yes. When compared, tuples first compare on the first element, then on the second etc... > In some cases I got some exceptions when an element of the tuple, other > than the first, didn't admit comparison. > In these cases I had to use an ad hoc comparison function. Did you try the sorted() function ? Used with operator.itemgetter as the 'key' argument, it may do the trick. From rdmoores at gmail.com Sat Feb 10 07:11:41 2007 From: rdmoores at gmail.com (Dick Moores) Date: Sat, 10 Feb 2007 04:11:41 -0800 Subject: Unicode is confusing me Message-ID: As per p. 188 of Python for Dummies, I've created a sitecustomize.py in my site-packages directory: ============================ # sitecustomize.py (see p.188 of Python for Dummies) import sys sys.setdefaultencoding('utf-8') =============================== With that in place, at the interactive prompt this goes well: =============================== >>> import sys >>> sys.getdefaultencoding() 'utf-8' >>> a = [u'\u91cd', u'\u8981', u'\u6027'] >>>for x in range(3): . . . print a[x], . . . ? ? ? >>> =============================== The 3 CJK characters are printed very nicely. However, when I put the last 3 lines of that code in a script, ============================ a = [u'\u91cd', u'\u8981', u'\u6027'] for x in range(3): print a[x] =========================== and redirect the output to a text file, I get "Traceback (most recent call last): File "E:\Python25\dev\Untitled1.py", line 3, in ? print a[x] UnicodeEncodeError: 'ascii' codec can't encode character u'\u91cd' in position 0: ordinal not in range(128)" I thought maybe it would help if I made the first line, # -*- coding: utf-8 -*- but that made no difference. Got the same error. Can someone help me understand what's going on? Thanks, Dick Moores -- my configuration: Win XP Pro SP2 Python 2.5 wxPython 2.8.1.1 Unicode Python IDE: Ulipad 3.6 From fccoelho at gmail.com Thu Feb 1 13:59:31 2007 From: fccoelho at gmail.com (Flavio) Date: 1 Feb 2007 10:59:31 -0800 Subject: gdesklets question: import problem Message-ID: <1170356371.494997.134380@a34g2000cwb.googlegroups.com> Hi, sorry for posting here, but the forum in the projects page is not working. Maybe there is a gdesklet developer lurking... :-) I cant import anything from a script, it gives me a runtime error. is this a bug or a feature? without being able to import from python standard library or other modules, applets are rather limited in functionality... thanks, Fl?vio From skip at pobox.com Thu Feb 8 07:04:01 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 8 Feb 2007 06:04:01 -0600 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <52vtc4F1pngrdU1@mid.individual.net> References: <45C9A137.8090009@v.loewis.de> <52vtc4F1pngrdU1@mid.individual.net> Message-ID: <17867.4529.98859.983599@montanaro.dyndns.org> greg> When I want to do this, usually I define the parts as ordinary, greg> separate classes, and then define the main class as inheriting greg> from all of them. Agreed. Maybe it's just my feeble brain, but I find this the most compelling (and easy to understand) use for multiple inheritance by far. Skip From boris.smirnov at gmail.com Mon Feb 26 10:49:44 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 26 Feb 2007 07:49:44 -0800 Subject: Interactive os.environ vs. os.environ in script In-Reply-To: References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> Message-ID: <1172504983.452208.182490@p10g2000cwp.googlegroups.com> On Feb 26, 4:32 pm, Peter Otten <__pete... at web.de> wrote: > boris.smir... at gmail.com wrote: > > Hi there, > > > I have a problem with setting environment variable in my script that > > uses qt library. For this library I have to define a path to tell the > > script whre to find it. > > > I have a script called "shrink_bs_070226" that looks like this: > > ********************************** > > import sys, re, glob, shutil > > import os > > > os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > > > from qt import * > > *********************** > > > When I run this script I get this error: > > >> python shrink_bs_070226.py > > Traceback (most recent call last): > > File "shrink_bs_070226.py", line 25, in ? > > from qt import * > > File "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ > > qt.py", line 46, in ? > > import libsip > > ImportError: libadamsqt.so: cannot open shared object file: No such > > file or directory > > > What is important here that when I set this variable interactive in > > python session, there is no problem with import. > > >> python > > Python 2.2.3 (#1, Aug 8 2003, 08:44:02) > > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-13)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import os > > >>>> import shrink_bs_070226 > > Traceback (most recent call last): > > File "", line 1, in ? > > File "shrink_bs_070226.py", line 25, in ? > > from qt import * > > ImportError: No module named qt > > >>>> os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > > >>>> import shrink_bs_070226 > > > Could anybody explain me the logic here? Am I missing something? > > Until Python 2.4 a failed import could leave some debris which would make > you think a second import did succeed. > > Try > > >>> import os > >>> os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > >>> import shrink_bs_070226 # I expect that to fail > > in a fresh interpreter to verify that what you see is an artifact of your > test method. > > Peter- Hide quoted text - > > - Show quoted text - You are right: > python Python 2.2.3 (#1, Aug 8 2003, 08:44:02) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' >>> import shrink_bs_070226 Traceback (most recent call last): File "", line 1, in ? File "shrink_bs_070226.py", line 25, in ? from qt import * ImportError: No module named qt >>> OK then I have to reformulate my question. :) In my script I have a line with os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' but this line didn't work. But when I set this environment variable in Linux shell it works. Here is a small example. > python shrink_bs_070226.py Traceback (most recent call last): File "shrink_bs_070226.py", line 25, in ? from qt import * File "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ qt.py", line 46, in ? import libsip ImportError: libadamsqt.so: cannot open shared object file: No such file or directory > setenv LD_LIBRARY_PATH /path/Linux/rh_linux > python shrink_bs_070226.py Starting Script "Shrinker" .... Why it's not working in script with command os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' but in shell it works? I hope it's understandable. :) Thanks, boris From paddy3118 at netscape.net Sat Feb 3 04:26:19 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 01:26:19 -0800 Subject: Regd. Kodos In-Reply-To: <1170494239.351279.302030@m58g2000cwm.googlegroups.com> References: <1170494239.351279.302030@m58g2000cwm.googlegroups.com> Message-ID: <1170494779.270324.122030@h3g2000cwc.googlegroups.com> On Feb 3, 9:17 am, "Paddy" wrote: > On Feb 3, 8:59 am, vis... at veriwave.com wrote: > > > I am trying to use Kodos..but not getting thru'..dont know whats goin > > on..does anyone have a regular expression for time in hh:mm:ss > > -Vishal > > Well, with just knowing the above, the following raw string when used > as a regular expression will capture the hh,mm,ss as groups 1,2,3 > r'\b(\d\d):(\d\d):(\d\d)\b' > > - Paddy P.S. I fired up Kodos and cut and pasted your message into the search string box; left the bottom notebook on the groups tag to show what groups i had captured; left the flags al off; then started typing the regular expression into the regular expression pattern box. Thats when i realised that your email said hh:mm:ss and I needed to match something with numbers so appended 08:34:66 as a new ine in the search string box. After typing in the regex, the group tab showed what I was after I like Kodos because it helps me when the RE's are much longer but i have sample text that I can easily paste in. I usually paste in a large tet sample just to make sure my RE doesn't fail on something I'm not expecting. - Paddy. . From michele.simionato at gmail.com Wed Feb 7 11:49:52 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 Feb 2007 08:49:52 -0800 Subject: Object type check In-Reply-To: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> Message-ID: <1170866992.476715.212970@a34g2000cwb.googlegroups.com> On Feb 7, 5:17 pm, "king kikapu" wrote: > Hi to all, > > in statically-types languages, let's say C# for example, we use > polymorphism through interfaces. So we define an interface I with > method M and then a class C that implements I interface and write code > for the M method. > So, if we have a function that takes a parameter of type I, we know > before-hand that it will have an M method to call. > > But in dynamic languages this is not the case and we can pass whatever > we want to that function. Assuming that someone writes a library in > Python that other programmers will use, what is the correct way to > check inside that function if the parameter passed is of the correct > type, maybe "isinstance" BIF ? Usually, you don't check anything at all. However, in some cases, it may make sense to check that you passed the right object. For instance if you have the container class Example(object): def __init__(self, innerobj): self.innerobj = innerobj def amethod(self): self.innerobj.amethod() ex = Example(None) you will get an error only when calling ex.amethod(). If you are going to call ex.amethod() one hour after instantiation, you will get the error too late. So, it makes sense to put a check in the __init__ method, something like assert hasattr(self.innerobj, 'amethod') in order to get an error message as soon as possible. Notice that checking for the existance of the needed method is better than using isinstance, since it gives you much more freedom for innerobj. Do not require more than you need. HTH, Michele Simionato From gigs at hi.t-com.hr Thu Feb 1 19:33:03 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 02 Feb 2007 01:33:03 +0100 Subject: coping directories Message-ID: hi people I have problem with this example, not actually the problem, but [code] class FileVisitor(object): def __init__(self, data=None): self.context = data def run(self, startdir=os.curdir): os.path.walk(startdir, self.visitor, None) def visitor(self, data, dirname, filesindir): self.visitdir(dirname) for fname in filesindir: fpath = os.path.join(dirname, fname) if not os.path.isdir(fpath): self.visitfile(fpath) def visitdir(self, dirpath): # override or extend this method print dirpath, '...' def visitfile(self, filepath): # override or extend this method print self.fcount, '=>', filepath # class CVisitor(FileVisitor): def __init__(self, fromdir, todir): self.fromdirLen = len(fromdir) + 1 # here is my problem self.todir = todir FileVisitor.__init__(self, fromdir) def visitdir(self, dirpath): topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) os.mkdir(topath) def visitfile(self, filepath): topath = os.path.join(self.todir, filepath[self.fromdirLen:]) cpfile(filepath, topath) #copy contents from filepath to topath[/code] When I copy contents from C:\IronPython to C:\temp its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this self.fromdirLen = len(fromdir) + 1 but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen = len(fromdir) i get contents copied to C:\ (actually to parent dir) Can anyone explain me that? Thanks!!! :o From gagsl-py at yahoo.com.ar Thu Feb 15 19:48:22 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 21:48:22 -0300 Subject: output to console and to multiple files References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171498259.757320.127100@q2g2000cwa.googlegroups.com> <1171554821.510472.313950@s48g2000cws.googlegroups.com> <1171558306.121792.169430@h3g2000cwc.googlegroups.com> <1171578909.944542.188190@a75g2000cwd.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 19:35:10 -0300, Matimus escribi?: >> I think you should be able to use my or goodwolf's solution with the >> subprocess module. Something like this (untested): >> >> [code] >> class TeeFile(object): >> def __init__(self,*files): >> self.files = files >> def write(self,txt): >> for fp in self.files: >> fp.write(txt) >> > > I tried this at lunch and it doesn't work. Some version of this method > may work, but Popen tries to call the 'fileno' method of the TeeFile > object (at least it did on my setup) and it isn't there. This is just > a preemptive warning before someone comes back to let me know my code > doesn't work. I don't think any Python only solution could work. The pipe options available for subprocess are those of the underlying OS, and the OS knows nothing about Python file objects. -- Gabriel Genellina From sri1025 at gmail.com Thu Feb 8 07:03:32 2007 From: sri1025 at gmail.com (Srikanth) Date: 8 Feb 2007 04:03:32 -0800 Subject: Best Free and Open Source Python IDE Message-ID: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Yes, All I need is a good IDE, I can't find something like Eclipse (JDT). Eclipse has a Python IDE plug-in but it's not that great. Please recommend. Thanks, Srikanth From vishal at veriwave.com Sun Feb 11 02:06:41 2007 From: vishal at veriwave.com (Vishal Bhargava) Date: Sat, 10 Feb 2007 23:06:41 -0800 Subject: can't find a way to display and print pdf through python. In-Reply-To: Message-ID: <200702110706.l1B76hUa028502@nsa.veriwave.com> Are you trying to do real time or post real time. -Vishal -----Original Message----- From: krishnakant Mane [mailto:researchbase at gmail.com] Sent: Saturday, February 10, 2007 10:50 PM To: Vishal Bhargava Cc: python-list at python.org Subject: Re: can't find a way to display and print pdf through python. On 11/02/07, Vishal Bhargava wrote: > Use Report Lab... I mentioned in my first email that I am already using reportlab. but I can only generate pdf out of that. I want to display it on screen and I also will be giving a print button which should do the printing job. by the way I use wxpython for gui. Krishnakant. From mcfletch at vrplumber.com Sun Feb 11 23:44:03 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 11 Feb 2007 23:44:03 -0500 Subject: Saving PyOpenGl figures as ps In-Reply-To: <1171231889.667812.72930@q2g2000cwa.googlegroups.com> References: <1171231889.667812.72930@q2g2000cwa.googlegroups.com> Message-ID: <45CFF093.5000106@vrplumber.com> Frank wrote: > Hi, > > I installed pyopengl (opengl for python) on my linux box and > everything works fine. But now I want to save the generated images as, > e.g., ps or eps. How can I do that and how can I adjust the resolution > (if necessary)? This is probably simple but for some reason I can not > find out how to do that. > > I appreciate every hint! > > Thanks, Frank > Hi Frank, Take a look at the demos in OpenGL, particularly: OpenGL-ctypes/OpenGL/Demo/GLUT/tom/conesave.py which is a little GLUT application that renders into a GLUT windows and then allows you to save it. That's raster operation though (i.e. produces a PNG or JPG). Raster operations can only save a portion of the screen as rendered, so if you want a higher resolution image you need to make a larger window. If you want to get more advanced you can try using an off-screen buffer (pbuffer or MESA) for the rendering, which may (depending on implementation) allow for higher resolutions. If you want a true vector graphic (PS, EPS) you'll need to use something like GL2PS. http://www.geuz.org/gl2ps/ HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From __peter__ at web.de Wed Feb 21 08:57:05 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Feb 2007 14:57:05 +0100 Subject: metaclasses (beginner question) References: Message-ID: Laszlo Nagy wrote: > I would like to create a hierarchy classes, where the leaves have a > special attribute called "producer_id". In addition, I would like to > have a function that can give me back the class assigned to any > producer_id value. I tried to implement this with a metaclass, but I > failed. Please help me, what I did wrong? > class ProducerHandlerType(type): ... > class A(ProducerHandlerType): > pass > > class B(A): > producer_id = 1 > # Metaclass methods are not called above, and the line below prints an > empty dict. :-( Without looking into the details -- the (subclass of) type is meant to be the class of the class, or the other way round, your normal classes are instances of (a subclass of) type. You determine the factory Python uses to make a class by adding __metaclass__ = factory to the class body, so you'll probably end with something like class ProducerHandlerType(type): # your code class A: __metaclass__ = ProducerHandlerType The subclasses of A will now invoke your customised metaclass machinery. Peter From skip at pobox.com Sun Feb 25 06:28:38 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 25 Feb 2007 05:28:38 -0600 Subject: timeout in urllib.open() In-Reply-To: References: Message-ID: <17889.29414.374508.250326@montanaro.dyndns.org> >> I believe this can only be set globally: >> >> import socket >> socket.setdefaulttimeout(seconds) Stefan> Uuuh this is no solution for me, because the website-checking Stefan> tool is part of a very very big application running in an Stefan> application server, so globally setting the timeout may break a Stefan> lot of other things... Can you try this patch: http://python.org/sf/723312 ? It's against current CVS. Also, it doesn't include urllib or urllib2 changes, just httplib. Getting this completed would be nice. Skip From rganesan at myrealbox.com Wed Feb 21 23:29:22 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Thu, 22 Feb 2007 09:59:22 +0530 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172103048.160783.309470@l53g2000cwa.googlegroups.com> <12tq4rvmb0ke0a4@corp.supernews.com> Message-ID: >>>>> Grant Edwards writes: >> print base64.decodestring(open('sambleb.conf', 'r').read()) > It'll only remain obfuscated for about 30 seconds after even a > mildly curious user looks at the file. It depends on the requirement. If the intention is to just to discourage someone with messing around with some config settings, it's good enough. If the user can figure out that it's base64 encoded and takes pains to decode, modify, encode and save it back, then he's earned the right to mess around ;-). Ganesan -- Ganesan Rajagopal From ayaz at dev.slash.null Sat Feb 10 15:34:03 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Sun, 11 Feb 2007 01:34:03 +0500 Subject: Something like the getattr() trick. Message-ID: I'm working with the following class heirarchy (I've snipped out the code from the classes): class Vuln: def __init__(self, url): pass def _parse(self): pass def get_link(self): pass class VulnInfo(Vuln): pass class VulnDiscuss(Vuln): pass def main(url): vuln_class = ['Info', 'Discuss'] vuln = Vuln(url) vuln._parse() for link in vuln.get_link(): i = VulnInfo(link) i._parse() d = VulnDiscuss(link) d._parse() Is there a way to get references to VulnInfo and VulnDiscuss objects using something like the getattr trick? For example, something like: for _class in vuln_class: class_obj = getattr('Vuln%s' % (_class,) ..) a = class_obj(link) a._parse() getattr() takes an object as its first argument. I can't seem to figure out how to make it work here. -- Ayaz Ahmed Khan A witty saying proves nothing, but saying something pointless gets people's attention. From jon+usenet at unequivocal.co.uk Mon Feb 19 22:30:26 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 20 Feb 2007 03:30:26 GMT Subject: Checking for EOF in stream References: <12tkgeh32duee72@corp.supernews.com> <45DA45C3.2000707@gentlemail.com> Message-ID: In article , Gabriel Genellina wrote: > So this is the way to check for EOF. If you don't like how it was spelled, > try this: > > if data=="": break How about: if not data: break ? ;-) From greg at cosc.canterbury.ac.nz Fri Feb 2 19:01:45 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Feb 2007 13:01:45 +1300 Subject: Spring Python 0.2.0 is released In-Reply-To: References: <1170393447.301368.124140@l53g2000cwa.googlegroups.com> Message-ID: <52i1r7F1o9rotU1@mid.individual.net> Jonathan Curran wrote: > Greg, > You have managed to peak my interest. I think the word you're after here is "pique" (although I suppose "peak" kind of makes sense as well:-). -- Greg (a different one) From Shawn at Milochik.com Thu Feb 8 10:41:44 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Thu, 8 Feb 2007 10:41:44 -0500 Subject: Fwd: Python new user question - file writeline error In-Reply-To: <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <1170887579.160693.78160@a34g2000cwb.googlegroups.com> <813A863A-3D95-47B5-8E54-B6DDF5A57DF5@Milochik.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> Message-ID: <2dc0c81b0702080741w797192c8v8a8a7f8f9118e338@mail.gmail.com> To the list: I have come up with something that's working fine. However, I'm fairly new to Python, so I'd really appreciate any suggestions on how this can be made more Pythonic. Thanks, Shawn Okay, here's what I have come up with: #! /usr/bin/python import sys import re month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} infile=file('TVA-0316','r') outfile=file('tmp.out','w') def formatDatePart(x): "take a number and transform it into a two-character string, zero padded" x = str(x) while len(x) < 2: x = "0" + x return x regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") for line in infile: matches = regex.findall(line) for someDate in matches: dayNum = formatDatePart(someDate[1:3]) monthNum = formatDatePart(month[someDate[4:7]]) yearNum = formatDatePart(someDate[8:12]) newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) line = line.replace(someDate, newDate) outfile.writelines(line) infile.close outfile.close From B.Ogryczak at gmail.com Wed Feb 28 11:35:24 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 28 Feb 2007 08:35:24 -0800 Subject: cPickle FU on Solaris Message-ID: <1172680524.108341.207330@8g2000cwh.googlegroups.com> It seems, that on Solaris cPickle is unable to unpickle some values, which it is able to pickle. >>> import cPickle >>> cPickle.dumps(1e-310) 'F9.9999999999999694e-311\n.' >>> cPickle.loads(_) Traceback (most recent call last): File "", line 1, in ? ValueError: could not convert string to float >>> import pickle >>> pickle.loads(_) 9.9999999999999694e-311 From gagsl-py at yahoo.com.ar Thu Feb 8 11:23:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 8 Feb 2007 08:23:49 -0800 Subject: postgres backup script and popen2 In-Reply-To: References: Message-ID: <1170951829.472924.65040@q2g2000cwa.googlegroups.com> On 8 feb, 10:27, Ma?l Benjamin Mettler wrote: > flupke schrieb: > > i made a backup script to backup my postgres database. > > Problem is that it prompts for a password. It thought i > > could solve this by using popen2. > > Use pexpect:http://pexpect.sourceforge.net/ pexpect could work. But a better way would be to supply the password on the command line. I don't know how postgres does that things, but I hope there is some way to automate the backup process... -- Gabriel Genellina From dboussebha at yahoo.fr Sun Feb 11 12:47:52 2007 From: dboussebha at yahoo.fr (soussou97) Date: Sun, 11 Feb 2007 09:47:52 -0800 (PST) Subject: Pyhton script Message-ID: <8912801.post@talk.nabble.com> Hi; I would like to automatically delivery, I seek a script in python which will be excecute from a Windows station to allows via sftp: 1- to connect to a Linux server for storing of the files 2- Next execute on the Linux server, some actions: Copy, gzip, mv etc... 3- to use a config file for the parameters: server name, login, password... Regards; -- View this message in context: http://www.nabble.com/Pyhton-script-tf3209528.html#a8912801 Sent from the Python - python-list mailing list archive at Nabble.com. From stani.vsvv at gmail.com Wed Feb 7 07:26:37 2007 From: stani.vsvv at gmail.com (stani.vsvv at gmail.com) Date: 7 Feb 2007 04:26:37 -0800 Subject: Python editor In-Reply-To: <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> Message-ID: <1170851197.656670.179590@a75g2000cwd.googlegroups.com> On Feb 6, 11:01 pm, Stef Mientki wrote: > BBands wrote: > > No, no, no, this is not an invitation to the editor wars. > > I have been using Jos? Cl?udio Faria's superb Tinn-R,http://www.sciviews.org/Tinn-R/, > > with the R language,http://www.r-project.org/. This editor allows you > > to send code to the R shell for execution. You can easily send a line, > > the selection, the balance after the cursor or the whole script. In SPE you can use Edit>Execute in shell (Shift+Ctrl+E). If there is nothing selected SPE will run the whole script. Stani From __peter__ at web.de Sun Feb 18 04:58:55 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 18 Feb 2007 10:58:55 +0100 Subject: cmd all commands method? References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> <53per7F1t12jjU1@mid.individual.net> <1171786661.599128.234300@k78g2000cwa.googlegroups.com> <1171792183.564570.307940@m58g2000cwm.googlegroups.com> Message-ID: placid wrote: > On Feb 18, 7:17 pm, "Michele Simionato" > wrote: >> On Feb 17, 11:44 pm, Bjoern Schliessmann > >> >> >> mail-0306.20.chr0n... at spamgourmet.com> wrote: >> > placid wrote: >> > > if i want to treat every cmdloop prompt entry as a potential >> > > command then i need to overwrite the default() method ? >> >> > Excuse me, what's a cmdloop prompt? What's the "default() method"? >> >> > > What i want to achieve is to be able to support global variable >> > > creation for example; >> >> > > res = sum 1 2 >> >> > > this would create a variable res with the result of the method >> > > do_sum() ? >> >> > > then would i be able to run; >> >> > > sum a 5 >> >> > > this would return 8 or an error saying that res is not defined >> >> > Are you sure you're talking about Python here? >> >> Yes, he is talking about the cmd >> module:http://docs.python.org/dev/lib/Cmd-objects.html. However that >> module was never intended as a real interpreter, so defining variables >> as the OP wants would require some work. >> >> Michele Simionato > > How much work does it require ? Too much. However, here's how far I got: import cmd import shlex DEFAULT_TARGET = "_" def number(arg): for convert in int, float: try: return convert(arg) except ValueError: pass return arg class MyCmd(cmd.Cmd): def __init__(self, *args, **kw): cmd.Cmd.__init__(self, *args, **kw) self.namespace = {} self.target = DEFAULT_TARGET def precmd(self, line): parts = line.split(None, 2) if len(parts) == 3 and parts[1] == "=": self.target = parts[0] return parts[2] self.target = DEFAULT_TARGET return line def resolve(self, arg): args = shlex.split(arg) result = [] for arg in args: try: value = self.namespace[arg] except KeyError: value = number(arg) result.append(value) return result def calc(self, func, arg): try: result = self.namespace[self.target] = func(self.resolve(arg)) except Exception, e: print e else: print result def do_sum(self, arg): self.calc(sum, arg) def do_max(self, arg): self.calc(max, arg) def do_print(self, arg): print " ".join(str(arg) for arg in self.resolve(arg)) def do_values(self, arg): pairs = sorted(self.namespace.iteritems()) print "\n".join("%s = %s" % nv for nv in pairs) def do_EOF(self, arg): return True if __name__ == "__main__": c = MyCmd() c.cmdloop() Peter From jonc at icicled.net Sun Feb 11 14:31:47 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sun, 11 Feb 2007 13:31:47 -0600 Subject: Pyhton script In-Reply-To: <8912801.post@talk.nabble.com> References: <8912801.post@talk.nabble.com> Message-ID: <200702111331.47933.jonc@icicled.net> On Sunday 11 February 2007 11:47, soussou97 wrote: > Hi; > > I would like to automatically delivery, I seek a script in python which > will be excecute from a Windows station to allows via sftp: > > 1- to connect to a Linux server for storing of the files > 2- Next execute on the Linux server, some actions: Copy, gzip, mv etc... > 3- to use a config file for the parameters: server name, login, password... > > Regards; > -- > View this message in context: > http://www.nabble.com/Pyhton-script-tf3209528.html#a8912801 Sent from the > Python - python-list mailing list archive at Nabble.com. How much are you willing to spend on this script? ;-) From jordan.taylor2 at gmail.com Tue Feb 13 12:51:34 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 13 Feb 2007 09:51:34 -0800 Subject: Download parts not whole file in ones In-Reply-To: References: Message-ID: <1171389094.849308.170410@k78g2000cwa.googlegroups.com> On Feb 13, 8:09 am, NOSPAM plz wrote: > Hey, > > My problem is, is it possible to download parts of a file while. i think > is it is called threading > > My code thats download the whole webpage, and stunds the app while is is > downloading: > > -----------CODE----------- > import urllib > # the heavy file to download > f = urllib.urlopen("http://da.wikipedia.org/wiki/Wiki") > # This was supposed to print the file while it downloads > while 1: > print f.read(100) > -----------/CODE----------- > > In my example it just download the whole file, and then print it. > > Any suggestions? > > Regards > Andreas That's because urllib.urlopen() is not a low enough level function to allow what you want, it will simply open the . Take a look inside of urllib.py and maybe you'll find a way to subclass the urllopen() function to do what you want. Cheers, Jordan From jeremy at gransdenonline.com Mon Feb 19 15:37:41 2007 From: jeremy at gransdenonline.com (Jeremy Gransden) Date: Mon, 19 Feb 2007 15:37:41 -0500 Subject: How to call a function defined in another py file In-Reply-To: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> References: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> Message-ID: <07E09485-5BDC-4CC3-BE8F-F053C8020711@gransdenonline.com> from a import test be sure a is in your path. jeremy On Feb 19, 2007, at 3:20 PM, silverburgh.meryl at gmail.com wrote: > Hi, > > I have a function called 'test' defined in A.py. > How can I call that function test in my another file B.py? > > Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list From kbk at shore.net Wed Feb 28 23:02:12 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 28 Feb 2007 23:02:12 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200703010402.l2142C59003869@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 416 open ( +8) / 3593 closed ( +8) / 4009 total (+16) Bugs : 974 open ( +6) / 6520 closed (+15) / 7494 total (+21) RFE : 268 open ( +1) / 251 closed ( +0) / 519 total ( +1) New / Reopened Patches ______________________ Allow specifying headers for MIME parts (2007-02-23) http://python.org/sf/1666625 opened by J?rg Sonnenberger Time zone-capable variant of time.localtime (2007-02-24) http://python.org/sf/1667546 opened by Paul Boddie urllib2 raises an UnboundLocalError if "auth-int" is the qop (2007-02-24) http://python.org/sf/1667860 opened by Atul Varma urllib2.urlopen() raises OSError instead of URLError (2007-02-24) http://python.org/sf/1668100 opened by Jerry Seutter Fix for 767111, 'AttributeError thrown by urllib.open_http' (2007-02-25) http://python.org/sf/1668132 opened by Atul Varma don't use '-' and '_' in mkstemp (2007-02-25) http://python.org/sf/1668482 opened by Arvin Schnell bytes.fromhex() (2007-02-26) CLOSED http://python.org/sf/1669379 opened by Georg Brandl subprocess: Support close_fds on Win32 (2007-02-26) http://python.org/sf/1669481 opened by Jon Foster Change (fix!) os.path.isabs() semantics on Win32 (2007-02-26) http://python.org/sf/1669539 opened by Jon Foster methods for bytes (2007-02-27) CLOSED http://python.org/sf/1669633 opened by Pete Shinners Remove Py_PROTO from socket in py3k (2007-02-27) CLOSED http://python.org/sf/1670209 opened by Pete Shinners email.Generator: no header wrapping for multipart/signed (2007-02-28) http://python.org/sf/1670765 opened by Martin von Gagern Refactor test_threadedtempfile.py to use unittest. (2007-02-28) http://python.org/sf/1670993 opened by Jerry Seutter Class Decorators (2007-02-28) http://python.org/sf/1671208 opened by Jack Diederich Refactor test_class to use unittest lib (2007-02-28) http://python.org/sf/1671298 opened by Mike Verdone New File I/O type for Python 3000, plus .h and unit tests (2007-02-28) http://python.org/sf/1671314 opened by Daniel Stutzbach Patches Closed ______________ setuptools: avoid sets module for python>2.3 (2007-02-19) http://python.org/sf/1663226 closed by pje documentation for element interface (2007-02-11) http://python.org/sf/1657613 closed by fdrake fast subclasses of builtin types (2006-12-28) http://python.org/sf/1624059 closed by nnorwitz bytes.fromhex() (2007-02-26) http://python.org/sf/1669379 closed by gbrandl Optional Argument Syntax (2006-12-02) http://python.org/sf/1607548 closed by gvanrossum methods for bytes (2007-02-26) http://python.org/sf/1669633 closed by nnorwitz Remove Py_PROTO from socket in py3k (2007-02-27) http://python.org/sf/1670209 closed by nnorwitz The Unicode "lazy strings" patches (2007-01-06) http://python.org/sf/1629305 closed by gvanrossum New / Reopened Bugs ___________________ Calling tparm from extension lib fails in Python 2.5 (2007-02-13) http://python.org/sf/1659171 reopened by richyk shutil.copytree doesn't preserve directory permissions (2007-02-22) http://python.org/sf/1666318 opened by Jeff McNeil Incorrect file path reported by inspect.getabsfile() (2007-02-23) http://python.org/sf/1666807 opened by Fernando P?rez terminalcommand doesn't work under Darwin (2007-02-23) http://python.org/sf/1666952 opened by Jurjen N.E. Bos Install fails with no error (2007-02-24) http://python.org/sf/1667877 reopened by widgeteye Install fails with no error (2007-02-24) http://python.org/sf/1667877 opened by larry PyMem_Realloc docs don't specifiy out-of-mem behavior (2007-02-24) http://python.org/sf/1668032 opened by Daniel Stutzbach PyMem_Resize docs don't specify that it modifies an argument (2007-02-24) http://python.org/sf/1668036 opened by Daniel Stutzbach python-2.4.4 on freebsd-6: _curses extension doesn't build (2007-02-25) CLOSED http://python.org/sf/1668133 opened by clemens fischer Strange unicode behaviour (2007-02-25) CLOSED http://python.org/sf/1668295 reopened by sgala Strange unicode behaviour (2007-02-25) CLOSED http://python.org/sf/1668295 opened by Santiago Gala I can't change attribute __op__ in new-style classes (2007-02-25) CLOSED http://python.org/sf/1668540 opened by netimen inspect.getargspec() fails with keyword-only arguments (2007-02-25) http://python.org/sf/1668565 opened by Brett Cannon distutils chops the first character of filenames (2007-02-25) http://python.org/sf/1668596 opened by Sam Pointon PyErr_WriteUnraisable lacks exception type check (2007-02-26) CLOSED http://python.org/sf/1669182 opened by Gabriel Becedillas Clarify PyMem_Realloc and PyMem_Resize docs (2007-02-26) http://python.org/sf/1669304 opened by Steven Bethard document that shutil.copyfileobj does not seek() (2007-02-26) http://python.org/sf/1669331 opened by Steven Bethard make install fails if no previous Python installation (2007-02-26) http://python.org/sf/1669349 opened by Matthias S. Benkmann 2.4.4 Logging LogRecord attributes broken (2007-02-26) http://python.org/sf/1669498 opened by Glenn Murray 2.4.4 Logging LogRecord attributes broken (2007-02-26) CLOSED http://python.org/sf/1669578 opened by Glenn Murray Some Compiler Warnings on VC6 (2007-02-27) http://python.org/sf/1669637 opened by Hirokazu Yamamoto 2.4.4 Logging LogRecord attributes broken (2007-02-26) CLOSED http://python.org/sf/1669646 opened by Glenn Murray Python needs a way to detect implementation (2007-02-27) http://python.org/sf/1669743 opened by Kay Hayen slice obj with no start index is 0 instead of None sometimes (2007-02-28) http://python.org/sf/1671137 opened by Mike Verdone Bugs Closed ___________ finditer stuck in infinite loop (2007-02-16) http://python.org/sf/1661745 closed by gbrandl python-2.4.4 on freebsd-6: _curses extension doesn't build (2007-02-25) http://python.org/sf/1668133 closed by loewis Strange unicode behaviour (2007-02-25) http://python.org/sf/1668295 closed by gbrandl Strange unicode behaviour (2007-02-25) http://python.org/sf/1668295 closed by gbrandl crash in exec statement if uncode filename cannot be decoded (2007-02-21) http://python.org/sf/1664966 closed by jhylton sys.settrace cause curried parms to show up as attributes (2006-10-02) http://python.org/sf/1569356 closed by jhylton I can't change attribute __op__ in new-style classes (2007-02-25) http://python.org/sf/1668540 closed by gbrandl nested variables in 'class:' statements (2003-09-22) http://python.org/sf/810714 closed by jhylton os.wait child process fail when under stress (2007-02-13) http://python.org/sf/1658959 closed by thegroff mention side-lists from python-dev description (2007-01-03) http://python.org/sf/1627039 closed by jhylton minor inconsistency in socket.close (2006-12-22) http://python.org/sf/1620945 closed by jhylton PyErr_WriteUnraisable lacks exception type check (2007-02-26) http://python.org/sf/1669182 closed by nnorwitz 2.4.4 Logging LogRecord attributes broken (2007-02-26) http://python.org/sf/1669578 closed by nnorwitz 2.4.4 Logging LogRecord attributes broken (2007-02-26) http://python.org/sf/1669646 closed by nnorwitz New / Reopened RFE __________________ isinstance.__doc__ is somewhat irritating (2007-02-27) http://python.org/sf/1670167 opened by Ren? Fleschenberg From mintern at cse.ohio-state.edu Thu Feb 22 11:40:43 2007 From: mintern at cse.ohio-state.edu (Brandon Mintern) Date: Thu, 22 Feb 2007 11:40:43 -0500 Subject: paths in modules (solved) References: <1172161730.919703.46730@q2g2000cwa.googlegroups.com> Message-ID: On Thu, 22 Feb 2007 08:28:50 -0800, Paul Boddie wrote: > And you really want to refer to utility_dir relative to some_wrapper. > What you can try is to split the __file__ attribute of some_wrapper - > it's a standard attribute on imported modules - in order to refer to > the module's parent directory (which should correspond to > wrapper_dir): > > parent_dir, filename = os.path.split(__file__) > > Then you can join the parent directory to the path of the command: > > cmd = os.path.join(parent_dir, "utility_dir", "some_external_utility") > > The __file__ attribute of modules is documented here: > > http://docs.python.org/ref/ty__file__ is the pathname of the file from > which the module was loadedpes.html#l2h-109 > > Paul Thanks a lot. I was hoping for a solution like that, and it worked perfectly for me (admittedly, in my trivial test files, but I'm sure that the solution will extend to my actual use case). Also, I had actually read that documentation you pointed me to, but the language, "__file__ is the pathname of the file from which the module was loaded" had me thinking that it was the pathname of the file doing the loading, rather than the file being loaded. I guess I should have actually tried it out. Anyways, thanks for the quick response and for the clarification. From a.schmolck at gmail.com Fri Feb 9 11:28:55 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 09 Feb 2007 16:28:55 +0000 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> <1171016992.962017.10540@m58g2000cwm.googlegroups.com> Message-ID: [restoring context] "Ant" writes: > > On Feb 6, 12:21 am, greg wrote: > > > > Alexander Schmolck wrote: > > > For example I once wrote this (slow) code to display > > > part of a mandelbrot fractal: > > > load'viewmat' > > > viewmat+/2&>:|((j.~/~(%~i:)99)&+@:*:)^:(i.32)0 > > > It'll likely require you more typing in python, > > > > Yes, but with Python you wouldn't have to spend a > > couple of weeks sitting and thinking before starting > > to type that line... (it's actually reasonably straightforward, if someone really cares I might post a translation) > > This is a good point often overlooked. There is of course some truth in Greg's statement -- J code will likely have a higher thought/character ratio (even after adjusting for differences in average token-length) -- but I don't think that is in itself terribly interesting. What is in my opinion of interest is how much of the additional thought you need to put in in order to achieve higher terseness is spent a) on more pentrating insight on the problem as such, encouraged by the mind-set and abstractions associated with a language (let's call this expressiveness) and how much of it is spent b) on perl-golf style geek masturbation that focuses on recalling and exploiting the language's various behavioral oddities that are only of coincidental or low-level relevance to the problem (let's call this golf-syndrome) I'm not claiming that the boundaries between the two are always unambigious, but I think the distinction is pretty important when discussing pros and cons of differences in terseness between languages. Apart from scaling better, one reason that a), expressiveness, is much more interesting than b), golf-syndrome, is that it translates to some extent even to writing code in other languages as it enriches the programmer's reservoir of metaphors and abstractions. Typically this also has a beneficial effect for coding even in languages that offer no direct support for these abstractions (I bet a programmer with, say extensive python, J and prolog experience and just a little bit of C background is in many cases likely to come up with a superior C solutions to challenging problems than someone who's got the same amount of experience in C only). Therefore... > You often get these threads on c.l.python about "How can I do this in one > line", usually with some example of how it is done in only 13 characters in > Perl. Yes you may spend less time typing - but unless you are a true expert > in (J, Perl, other terse language) the time you spend actually working out > how to type it, and in debugging it far outweighs the time you'd spend on > all of that typing in a clean but more verbose language such as Python. ... I also don't think your pairing of J and Perl is particularly helpful. As long as no one can point me to some resonable examples demonstrating otherwise I flattly deny that Perl is more concise than python in an *interesting* way, i.e. by encouraging or enabling a) (BTW "not interesting" != "not practically relevant"; harking back to my previous posts, typing effort *does matter* in some contexts, such as command-line one-liners; IMO the only thing perl is useful for.) J, on the other hand, whilst also suffering somewhat from golf-syndrome, does in my opinion also enable a)-style terseness. Let me give an example: Before reading further, how would you code a program that gives the following output ('skewed' sierpinski-triangle) in python? I'll give some remarkably concise and IMO lucid J code and a python translation below. * ** * * **** * * ** ** * * * * ******** * * ** ** * * * * **** **** * * * * ** ** ** ** * * * * * * * * **************** SPOILERS AHEAD J solution ---------- I can think of two nice ways in J, 13 and 16 characters long respectively and each expressing something essential and non-trival about the problem in a way that would be more cumbersome in python. Here's the first one: (,,.~)^:4,'*' NB. due to Cliff Reiter, slightly adapted Possible Python translation --------------------------- Here's a python transiteration attempt: # ^: , ~ ,. print rep(hook(vertcat, self(horzcat)),4)('*') or slightly more idiomatic: def sierpinski(x): return vertcat(x,horzcat(x,x)) print rep(sierpinsky,4)('*') With: def identity(x): return x def rep(f,n): # f^:n if n < 0: return lambda *args: rep(inverse(f),-n)(*args) elif n == 0: return identity else: return lambda *args: rep(f,n-1)(f(*args)) # horzcat and vertcat are only string-based special purpose mockups for this # problem since python doesn't have arrays def horzcat(a,b): # a,.b return "\n".join(a_i+b_i for (a_i,b_i) in zip(a.split('\n'), b.split('\n'))) def vertcat(a,b): # a,b # fill "rows" of b up with spaces if a's rows are longer and vice versa dif = len(a.split('\n')[0]) - len(b.split('\n')[0]) if dif < 0: a = a.replace('\n', ' '*-dif + '\n') + ' '*-dif elif dif > 0: b = b.replace('\n', ' '*dif + '\n') + ' '*dif return a + '\n' + b def self(f): # f~ return lambda x: f(x,x) def hook(f,g): # (f g) return lambda x: f(x,g(x)) print rep(hook(vertcat, self(horzcat)),4)('*') I find above J solution is quite neat conceptually because it directly captures the self-similarity. The other J solution is ' *'{~2|!~/~i.*:2^4 Can you figure out how it works? (Hint: k!n = choose(k,n), 2|x = x%2) 'as From openopt at ukr.net Sun Feb 18 13:58:07 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 18 Feb 2007 10:58:07 -0800 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? Message-ID: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> Thank you in advance for your response. Dmitrey From robert.kern at gmail.com Sat Feb 3 16:40:45 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 03 Feb 2007 15:40:45 -0600 Subject: raise or not to raise [Newbie] In-Reply-To: References: Message-ID: Jacol wrote: > I understand that author generated exception and than extracted the name of > function from the exeption. But is any sens in using exeptions service if > we have smthing simpler: just print for example? In my opinion no, it > doesn't make sens. You are correct. The author of that code was using exceptions to get at particular information that, at the time, was only available through a traceback. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 15:27:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 21:27:58 +0100 Subject: Python new user question - file writeline error In-Reply-To: <1170876692.167248.244870@s48g2000cws.googlegroups.com> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> Message-ID: <45ca2f29$0$1620$426a74cc@news.free.fr> James a ?crit : > Hello, > > I'm a newbie to Python & wondering someone can help me with this... > > I have this code: > -------------------------- > #! /usr/bin/python > > import sys > > month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG': > 8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > infile=file('TVA-0316','r') > outfile=file('tmp.out','w') > > for line in infile: > item = line.split(',') CSV format ? http://docs.python.org/lib/module-csv.html > dob = item[6].split('/') > dob = dob[2]+'-'+str(month[dob[1]])+'-'+dob[0] Why did you use integers as values in the month dict if it's for using them as strings ? > lbdt = item[8].split('/') > lbdt = lbdt[2]+'-'+str(month[lbdt[1]])+'-'+lbdt[0] > lbrc = item[10].split('/') > lbrc = lbrc[2]+'-'+str(month[lbrc[1]])+'-'+lbrc[0] > lbrp = item[14].split('/') > lbrp = lbrp[2]+'-'+str(month[lbrp[1]])+'-'+lbrp[0] This may help too: http://docs.python.org/lib/module-datetime.html > item[6] = dob > item[8] = lbdt > item[10]=lbrc > item[14]=lbrp > list = ','.join(item) Better to avoid using builtin types names as identifiers. And FWIW, this is *not* a list... > outfile.writelines(list) You want file.writeline() or file.write(). And you have to manually add the newline. > infile.close You're not actually *calling* infile.close - just getting a reference on the file.close method. The parens are not optional in Python, they are the call operator. > outfile.close Idem. > ----------------------------- > > And the data file(TVA-0316) looks like this: > ----------------------------- > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,AST,19,U/L,5,40,, > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,GGT,34,U/L,11,32,h, > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,ALT,31,U/L,5,29,h, > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > NOV/2006,V1,,,21/NOV/2006,ALKP,61,U/L,40,135,, > ----------------------------- > > Basically I'm reading in each line and converting all date fields (05/ > MAR/1950) to different format (1950-03-05) in order to load into MySQL > table. > > I have two issues: > 1. the outfile doesn't complete with no error message. when I check > the last line in the python interpreter, it has read and processed the > last line, but the output file stopped before. Use the csv module and cleanly close your files, then come back if you still have problems. > 2. Is this the best way to do this in Python? Err... What to say... Obviously, no. From http Mon Feb 26 11:41:29 2007 From: http (Paul Rubin) Date: 26 Feb 2007 08:41:29 -0800 Subject: Python / Socket speed References: <1172501644.228475.57540@a75g2000cwd.googlegroups.com> <30EEh.2082$BE2.1124@newssvr27.news.prodigy.net> Message-ID: <7xirdoc1mu.fsf@ruckus.brouhaha.com> John Nagle writes: > Sockets and pipes are a terrible way to do local interprocess > communication, but it's what we've got. The problem is that what you > want is a subroutine call, but what the OS gives you is an I/O operation. Using TCP sockets is ridiculous but Unix domain sockets aren't that bad. There's also mmap or shm. From thebrasse at brasse.org Thu Feb 15 18:03:10 2007 From: thebrasse at brasse.org (=?iso-8859-1?B?TWF0dGlhcyBCcuRuZHN0cvZt?=) Date: 15 Feb 2007 15:03:10 -0800 Subject: filecmp.cmp() cache In-Reply-To: References: <1171554885.517477.316470@s48g2000cws.googlegroups.com> <1171577045.892167.46580@p10g2000cwp.googlegroups.com> Message-ID: <1171580590.899667.168270@s48g2000cws.googlegroups.com> On Feb 15, 11:43 pm, Peter Otten <__pete... at web.de> wrote: > Mattias Br?ndstr?m wrote: > > Just one small tought/question. How likely am I to run into trouble > > because of this? I mean, by setting _cache to another value I'm > > mucking about in filecmp's implementation details. Is this generally > > considered OK when dealing with Python's standard library? > > I think it's a feature that Python lends itself to monkey-patching, but > still there are a few things to consider: > > - Every hack increases the likelihood that your app will break in the next > version of Python. > - You take some responsibility for the "patched" code. It's no longer the > tried and tested module as provided by the core developers. > - The module may be used elsewhere in the standard library or third-party > packages, and failures (or in the above example: performance degradation) > may ensue. > > For a script and a relatively obscure module like 'filecmp' monkey-patching > is probably OK, but for a larger app or a module like 'os' that is heavily > used throughout the standard lib I would play it safe and reimplement. Thanks for the insight! Right now I need this for a unit test, so in this case I'm quite happy to use the NoCache solution you suggested. :.:: brasse From jdillworth at gmail.com Wed Feb 28 00:14:55 2007 From: jdillworth at gmail.com (Jeremy Dillworth) Date: 27 Feb 2007 21:14:55 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172637721.119848.188380@a75g2000cwd.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> Message-ID: <1172639695.024190.150680@z35g2000cwz.googlegroups.com> You'll need to run the command in the command-line window. If you're unfamiliar, here's how to start it up: Click "Start" then "Run..." then type "Cmd" in the open field. Click OK. Once you're at the command line there will be a little variation depending on where things are located on your PC. If Python is installed properly, you should be able to invoke the Python interpreter from the command-line regardless of your current working directory, so you don't need to unzip java2python under the Python 2.5 folder. You should do something like this: cd \path\to\java2python\unzipped python setup.py install From sjmachin at lexicon.net Fri Feb 23 20:26:23 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Feb 2007 17:26:23 -0800 Subject: Regex Speed In-Reply-To: <549glaF1vhdlcU1@mid.individual.net> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172079285.197453.131490@h3g2000cwc.googlegroups.com> <1172272548.867795.289560@m58g2000cwm.googlegroups.com> <549glaF1vhdlcU1@mid.individual.net> Message-ID: <1172280382.958066.319350@k78g2000cwa.googlegroups.com> On Feb 24, 11:51 am, greg wrote: > garri... at gmail.com wrote: > > the author of this citation states that > > any regex can be expressed as a DFA machine. However ... > > > I appear to have found one example of a regex > > > which breaks this assumption. > > > "ab+c|abd" > > > Am I correct? > > No. Any NFA can be converted to an equivalent DFA. Correct. However ... > This is how scanner generators like Lex work -- they > first construct an NFA from the regex, and then > convert it to a DFA. Going directly from the regex > to a DFA, like you're trying to do, would be a lot > harder, and I'd be surprised if anyone ever does > it that way. >From "Compilers; Principles, Techniques, and Tools" aka "the dragon book" by Aho, Sethi and Ullman, 1986, page 134: "The first algorithm is suitable for inclusion in a Lex compiler because it constructs a DFA directly from a regular expression, without constructing an intermediate NFA along the way." > > There's a description of the NFA-to-DFA algorithm > here: > > http://www.gamedev.net/reference/articles/article2170.asp which is on a really serious site (pop-up flashing whizz-bangs inciting one to get an iPod now!) and which uses the (a|b)*abb example from the dragon book (and the diagram of its Thompson-constructed NFA) without any credit or mention of the book, in fact no references or attributions at all. From phil at riverbankcomputing.co.uk Wed Feb 28 02:56:34 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 28 Feb 2007 07:56:34 +0000 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <1172617785.871756.77380@j27g2000cwj.googlegroups.com> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172609807.109748.93170@8g2000cwh.googlegroups.com> <1172617785.871756.77380@j27g2000cwj.googlegroups.com> Message-ID: <200702280756.34765.phil@riverbankcomputing.co.uk> On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > When your programs stops with the error, it should also be printing a > stack trace. This is a list of all the functions that have been called > when Python had the problem. > > You shouldn't have to do anything extra to get the stack trace. The error is raised in Qt and aborts immediately. It never gets back to Python to generate a trace. He needs to produce a short and complete test which demonstrates the problem, then we can point out where the QPaintDevice is being created. Phil From eurleif at ecritters.biz Tue Feb 6 05:20:50 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 06 Feb 2007 05:20:50 -0500 Subject: HTMLParser's start_tag method never called ? In-Reply-To: <1170084691.837503.10520@j27g2000cwj.googlegroups.com> References: <1170084691.837503.10520@j27g2000cwj.googlegroups.com> Message-ID: <45c85673$0$6828$4d3efbfe@news.sover.net> ychaouche wrote: > class ParseurHTML(HTMLParser): > def __init__(self): > HTMLParser.__init__(self) > > def start_body(self,attrs): > print "this is my body" def start_tag(self, name, attrs): if name == 'body': print "this is my body" From alainpoint at yahoo.fr Fri Feb 2 07:41:48 2007 From: alainpoint at yahoo.fr (alain) Date: 2 Feb 2007 04:41:48 -0800 Subject: Why does this not work? Message-ID: <1170420108.701432.77090@q2g2000cwa.googlegroups.com> I tried the following: myobj=object() myobj.newattr=5 results in: Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'newattr' Any idea? Alain From noone at nowhere.com Sun Feb 4 01:55:17 2007 From: noone at nowhere.com (avidfan) Date: Sun, 04 Feb 2007 00:55:17 -0600 Subject: log parser design question References: <1170048047.660118.164850@l53g2000cwa.googlegroups.com> Message-ID: On Mon, 29 Jan 2007 23:11:32 -0600, avidfan wrote: >On 28 Jan 2007 21:20:47 -0800, "Paul McGuire" >wrote: > >>On Jan 27, 10:43 pm, avidfan wrote: >>> I need to parse a log file using python and I need some advice/wisdom >>> on the best way to go about it: >>> >>> The log file entries will consist of something like this: >>> >>> ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled >>> locked working.lock >>> status running >>> status complete >>> >>> ID=9009 IID=87234785 execute wait - 01.21.2007 status wait >>> waiting to lock >>> status wait >>> waiting on ID=8688 >>> >>> and so on... >>> >>For the parsing of this data, here is a pyparsing approach. Once >>parse, the pyparsing ParseResults data structures can be massaged into >>a queryable list. See the examples at the end for accessing the >>individual parsed fields. >> >>-- Paul >> >>data = """ >>ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled >> locked working.lock >> status running >> status complete >> >> >>ID=9009 IID=87234785 execute wait - 01.21.2007 status wait >> waiting to lock >> status wait >> waiting on ID=8688 >> >>""" >>from pyparsing import * >> >>integer=Word(nums) >>idref = "ID=" + integer.setResultsName("id") >>iidref = "IID=" + integer.setResultsName("iid") >>date = Regex(r"\d\d\.\d\d\.\d{4}") >> >>logLabel = Group("execute" + oneOf("begin wait")) >>logStatus = Group("status" + oneOf("enabled wait")) >>lockQual = Group("locked" + Word(alphanums+".")) >>waitingOnQual = Group("waiting on" + idref) >>statusQual = Group("status" + oneOf("running complete wait")) >>waitingToLockQual = Group(Literal("waiting to lock")) >>statusQualifier = statusQual | waitingOnQual | waitingToLockQual | >>lockQual >>logEntry = idref + iidref + logLabel.setResultsName("logtype") + "-" \ >> + date + logStatus.setResultsName("status") \ >> + ZeroOrMore(statusQualifier).setResultsName("quals") >> >>for tokens in logEntry.searchString(data): >> print tokens >> print tokens.dump() >> print tokens.id >> print tokens.iid >> print tokens.status >> print tokens.quals >> print >> >>prints: >> >>['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', >>'01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], >>['status', 'running'], ['status', 'complete']] >>['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', >>'01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], >>['status', 'running'], ['status', 'complete']] >>- id: 8688 >>- iid: 98889998 >>- logtype: ['execute', 'begin'] >>- quals: [['locked', 'working.lock'], ['status', 'running'], >>['status', 'complete']] >>- status: ['status', 'enabled'] >>8688 >>98889998 >>['status', 'enabled'] >>[['locked', 'working.lock'], ['status', 'running'], ['status', >>'complete']] >> >>['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', >>'01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', >>'wait'], ['waiting on', 'ID=', '8688']] >>['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', >>'01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', >>'wait'], ['waiting on', 'ID=', '8688']] >>- id: 9009 >>- iid: 87234785 >>- logtype: ['execute', 'wait'] >>- quals: [['waiting to lock'], ['status', 'wait'], ['waiting on', >>'ID=', '8688']] >>- status: ['status', 'wait'] >>9009 >>87234785 >>['status', 'wait'] >>[['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', >>'8688']] > >Paul, > >Thanks! That's a great module. I've been going through the docs and >it seems to do exactly what I need... > >I appreciate your help! http://www.camelrichard.org/roller/page/camelblog?entry=h3_parsing_log_files_with Thanks, Paul! From deets at nospam.web.de Fri Feb 16 08:16:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 Feb 2007 14:16:23 +0100 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <45d5a499$0$5995$b9f67a60@news.newsdemon.com> <1171631180.776312.258100@v33g2000cwv.googlegroups.com> Message-ID: <53lp57F1t2g4mU2@mid.uni-berlin.de> > Maybe this line of mine was a bit too condensed ;) I fully agree with > you on what you say about CORBA. It's just that for most people IDL > looks a bit out of place. Especially because it resembles C. But once > you actually wrote a few projects using CORBA, you actually begin to > see it's elegance ;) It looks out of the place in comparison to what exactly? A WSDL-document? You certainly me laugh hard on that.... > I find Webservices "easier" as you can (although it's not > recommendable) leave out the WSDL part. And some implementations > actually generate the WSDL for you. You can't leave WSDL out of SOAP, you can leave it out of XMLRPC. Which is nice and easy, but lacks any contract whatsoever. Nothing I as a Pythoneer care to much about, but some people bother. And generating the WSDL works from what exactly? ah, Java-code for example, using java2wsdl. Which has a striking resemblance to.... C. Funny.... > But it's true, comparing WSDL and > IDL I'd rather write some IDL than WSDL ;) So - you say that yourself, but still you previously claimed IDL looks strange to the eye? Diez From skip at pobox.com Mon Feb 5 06:01:28 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 5 Feb 2007 05:01:28 -0600 Subject: in place-ness of list.append In-Reply-To: References: Message-ID: <17863.3720.339689.188664@montanaro.dyndns.org> Bart> #-------------------------------------------------- Bart> def addnumber(alist, num): Bart> """ work around the inplace-ness of .append """ Bart> mylist = alist[:] Bart> mylist.append(num) Bart> return mylist Bart> #-------------------------------------------------- Bart> and I am wondering if this is good practice or not. Bart> any advice on this matter? Such an operation will be O(N**2), and thus expensive if performed frequently on lists of moderate length. I've never been tempted to do this. Can you say a little about why you'd want to do this? Knowing that, perhaps someone here can point you in a more Pythonic direction. Skip From nagle at animats.com Wed Feb 21 00:19:26 2007 From: nagle at animats.com (John Nagle) Date: Tue, 20 Feb 2007 21:19:26 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: <7x1wkkxnmn.fsf@ruckus.brouhaha.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> <7x1wkkxnmn.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Nagle writes: > >> There's always the possiblity that Python 3 won't happen. Look at >>what happened with Perl 6. That's been talked about for >>seven years now. The user base just wasn't interested. >>Perl 5 was good enough, and users migrated to PHP for the >>little stuff and other languages for the bigger stuff. >>As Wikipedia says, "As of 2007, Perl 6 was still under development, >>with no planned completion date." > > > I like to think PyPy will replace CPython as the main Python > implementation. Well, something faster really should take over. It's a bit embarassing that the main implementation of Python is still a pure interpreter. Even Javascript has a JIT compiler now. And it's tiny, under 1MB. John Nagle From rds1226 at sh163.net Thu Feb 22 19:24:29 2007 From: rds1226 at sh163.net (John) Date: Thu, 22 Feb 2007 19:24:29 -0500 Subject: What is the best queue implemetation in Python? References: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> Message-ID: Than C or PASCAL I mean, list or dictionary in Python are so powerful than the traditional array. Maybe I can make use of it? "John Machin" wrote in message news:1172190018.915043.200560 at v45g2000cwv.googlegroups.com... > On Feb 23, 11:12 am, "John" wrote: > > I want to write a code for Breadth First Traveral for Graph, which needs a > > queue to implement. > > > > I wonder that for such a powerful language as Python, whether there is a > > better and simpler implementation for a traditional FIFO queue? > > > > Better and simpler than *WHAT*? > > > > From rshepard at nospam.appl-ecosys.com Mon Feb 26 22:48:04 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 27 Feb 2007 03:48:04 GMT Subject: Lists: Converting Double to Single References: <45e38410$0$6830$4d3efbfe@news.sover.net> Message-ID: On 2007-02-27, Leif K-Brooks wrote: Lief, Bjoern: > l = l[0] Of course! If I had let it work in my mind overnight I would almost certainly have seen this. Thank you both for your patient responses, Rich From sergey at fidoman.ru Wed Feb 14 16:50:03 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Thu, 15 Feb 2007 00:50:03 +0300 Subject: f---ing typechecking References: Message-ID: "James Stroud" wrote in message news:eqvuo1$kk7$1 at zinnia.noc.ucla.edu... >>>>>[1]+(1,) >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: can only concatenate list (not "tuple") to list >> >> >> Its ugly and boring. > > Agreed. This would be similar to: > > py> 1 + 1.0 > > Traceback: can only add int to int. Etc. > > But then again, the unimaginative defense would be that it wouldn't be > python if you could catentate a list and a tuple. Maybe, but I don't think that it is best side of the languague. If we want constant objects like tuple why not to specify it explicitly? If we want lists as dict keys, why not to use copy-on-write? From uymqlp502 at sneakemail.com Thu Feb 22 15:03:54 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 22 Feb 2007 12:03:54 -0800 Subject: jython import search path In-Reply-To: <5457q8F1rqvu1U1@mid.uni-berlin.de> References: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> <1172105604.157543.191450@k78g2000cwa.googlegroups.com> <5457q8F1rqvu1U1@mid.uni-berlin.de> Message-ID: <1172174634.566542.312360@h3g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > >> Maybe Jython expert has the perfect answer but til then. > >> > >> Did you try: > >> > >> sys.path.append('path to search') > >> > >> Usually this works if nothing else does. > >> > >> -Larry > > > > Thanks. That's a good workaround, but I would like to know the > > "correct" way to do it too if anyone out there knows. > > That is pretty much an accepted strategy. Another one is to alter the > registry file, which has a property python.path. It might even be possible > to use Accepted strategy? It doesn't seem very portable. It assumes that everyone puts their library modules in the exact same place. Or do they just figure that changing the sys.path.append line is easy enough? > java -Dpython.path= I'm not using Java at all. I just want to generate Java bytecode for purposes of code analysis by existing tools. From jstroud at mbi.ucla.edu Thu Feb 22 15:17:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Feb 2007 12:17:01 -0800 Subject: metaclasses (beginner question) In-Reply-To: References: Message-ID: Peter Otten wrote: > You determine the factory Python uses to > make a class by adding > > __metaclass__ = factory > > to the class body, so you'll probably end with something like > > class ProducerHandlerType(type): > # your code > > class A: > __metaclass__ = ProducerHandlerType > > The subclasses of A will now invoke your customised metaclass machinery. This is the most perfectly succinct description of the __metaclass__ attribute I have ever seen. Beautiful. James From bignose+hates-spam at benfinney.id.au Thu Feb 8 15:46:36 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 09 Feb 2007 07:46:36 +1100 Subject: Best Free and Open Source Python IDE References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <87zm7o9y37.fsf@benfinney.id.au> "Srikanth" writes: > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. A powerful, well-supported text editor (either Emacs or Vim) plus the corresponding Python support. -- \ "I went to a garage sale. 'How much for the garage?' 'It's not | `\ for sale.'" -- Steven Wright | _o__) | Ben Finney From spammers-die at spam.microsoft.com Tue Feb 20 07:55:36 2007 From: spammers-die at spam.microsoft.com (John McCallum) Date: Tue, 20 Feb 2007 12:55:36 +0000 Subject: Weird result returned from adding floats depending on order I add them References: Message-ID: Hi, > I'm getting different results when I add up a list of floats depending > on the order that I list the floats. For example, the following returns > > [snip summation] > > if totalProp != 1: >From a numerical analysis point of view, never ever do this. The values you are adding are approximations to the numbers you require, you then test for equality (the real no no)... There is even a section in the Python tutorial about it: http://docs.python.org/tut/node16.html Cheers, John McCallum Edinburgh From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 28 21:27:33 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 03:27:33 +0100 Subject: text wrapping help References: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> <1172710705.158010.204480@m58g2000cwm.googlegroups.com> Message-ID: <54ms0lF21c6h3U1@mid.individual.net> Ryan K wrote: > It doesn't even run but when I go through it interactively it > seems okay. Once again, any help is appreciated. I haven't tested yet, but why don't you make a list of words of the text (with split), and then accumulate words in a list until the next word would make the line too long. Then just join the word list, fill with spaces until line end and start over. Regards, Bj?rn -- BOFH excuse #325: Your processor does not develop enough heat. From skip at pobox.com Mon Feb 5 08:31:21 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 5 Feb 2007 07:31:21 -0600 Subject: in place-ness of list.append In-Reply-To: References: Message-ID: <17863.12713.847518.235653@montanaro.dyndns.org> >>>>> "Bart" == Bart Van Loon writes: >> Such an operation will be O(N**2), Bart> why is that? The a[:] operation makes a copy of a (as will the x = a + [n] idiom). Bart> I am building a binary tree where each node is a list. the two Bart> children are the parent list + 1 and the parent list + 2. You might consider creating each node as left = [parent, 1] right = [parent, 2] You thus wind up with a nested set of two-element nodes, e.g.: [] [[], 1] [[], 2] [[[], 1], 1] [[[], 1], 2] [[[], 2], 1] [[[], 2], 2] where the left-hand side of each node is just a reference to the parent node. Once the tree is built if you can flatten the resulting node lists to generate lists which are more efficient for direct element access. Again, this all depends on how big your trees are, what you do with them once they are built, if you need to search the tree while building the tree, etc. Skip From sjmachin at lexicon.net Sun Feb 4 18:12:47 2007 From: sjmachin at lexicon.net (John Machin) Date: 4 Feb 2007 15:12:47 -0800 Subject: Missing member In-Reply-To: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> References: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> Message-ID: <1170630766.995011.176660@v45g2000cwv.googlegroups.com> On Feb 5, 9:45 am, "Mizipzor" wrote: > I have some troubles with a member variable that seems to be missing > in a class. In short, heres what I do; class A is the parent class, B > inherits from A and C inherits from B (hope I used the right words > there). Now, I create an instance of C, which calls A's __init__ which > in turn creates all the member variables. Then I call C.move() (a > function defined in A), but then, one of the variables seems to have > become 'NoneType'. > > The code can be found here (Ive taken away unnecessery stuff):http://pastebin.com/875394 > > The exact error is (which occur on line 15 in the pasted code): > TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' Line 15 is: self.pos += (self._direction * self.stats.speed) So obviously(???) self._direction is None What does line 8 do: self._direction = vector() ??? I'd suggest adding line 8.1: assert self._direction is not None > Any comments are welcome. :) I doubt that you really mean that, so I have refrained from commenting :-) Cheers, John From stj911 at rock.com Sat Feb 3 10:31:12 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 3 Feb 2007 07:31:12 -0800 Subject: What is the Decisive "Clash" of Our Time? In-Reply-To: References: <1170289871.307738.216710@v33g2000cwv.googlegroups.com> <1170479874.053127.211780@k78g2000cwa.googlegroups.com> Message-ID: <1170516671.914953.28910@k78g2000cwa.googlegroups.com> On Feb 3, 7:09 am, "Overlord" wrote: > Another conspiracy theory nutter....You guys are so boring. > > OL > > wrote in message > > news:1170479874.053127.211780 at k78g2000cwa.googlegroups.com... > > > Forget about the lunacy ... just enjoy these fun movies that are also > > on optics education. You can also save them by right clicking the > > links and saving them as flv files and download a free flv player. > > google is your friend. > > > "Bush Administration Insider Says U.S. Government Behind 911.flv" > > "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w" > > > "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http:// > > youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" > > > "911 Truth, Consequences of Revealing the Truth about 911.flv" "http:// > > youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" > > > "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv" > > "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" > > > "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax- > > v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" > > > "Bush gets caught off guard on 9/11 prior knowledge question.flv" > > "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" > > > "Bush gets caught off guard on 911 prior knowledge question.flv" > > "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" > > > "World Trade Center -- Controlled Demolition.flv" "http:// > > v187.youtube.com/get_video?video_id=87fyJ-3o2ws" > > > "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv" > > "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90" > > > On Jan 31, 7:56 pm, "Overlord" wrote: > >> I never thought it would be possible for anyone to rival the lunacy of > >> Bitter Anko, but I was wrong... > > >> OL LOL, thanks for the free service From nagle at animats.com Thu Feb 15 01:19:55 2007 From: nagle at animats.com (John Nagle) Date: Thu, 15 Feb 2007 06:19:55 GMT Subject: threading and multicores, pros and cons In-Reply-To: <7xr6ssdkqo.fsf@ruckus.brouhaha.com> References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> <7xzm7gt2sg.fsf@ruckus.brouhaha.com> <7xr6ssdkqo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Nagle writes: > >> If locking is expensive on x86, it's implemented wrong. >>It's done right in QNX, with inline code for the non-blocking case. > > > Acquiring the lock still takes an expensive instruction, LOCK XCHG or > whatever. I think QNX is usually run on embedded cpu's with less > extensive caching as these multicore x86's, so the lock prefix may be > less expensive in the QNX systems. That's not so bad. See http://lists.freebsd.org/pipermail/freebsd-current/2004-August/033462.html But there are dumb thread implementations that make a system call for every lock. John Nagle From shanekwon at gmail.com Wed Feb 14 01:45:41 2007 From: shanekwon at gmail.com (agent-s) Date: 13 Feb 2007 22:45:41 -0800 Subject: python not returning true In-Reply-To: <1171431443.737052.183960@j27g2000cwj.googlegroups.com> References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171431443.737052.183960@j27g2000cwj.googlegroups.com> Message-ID: <1171435541.291367.299290@j27g2000cwj.googlegroups.com> On Feb 13, 9:37 pm, "John Machin" wrote: > On Feb 14, 4:15 pm, "agent-s" wrote: > > > I have a function, generally described as so: > > > def function(args): > > if condition: > > if condition2: > > function(args+1) > > return None> elif condition3: > > print "text" > > return True > > else: > > return False > > else: > return None > > There are two cases, indicated above, where you don't explicitly do a > "return", so you fall off the end of the function, and Python returns > None. > > Then when the function's caller tests the returned value, None is > treated as logically false. > > > which is used in: > > > if function(args): > > print "ok" > > > so here basically "text" will print out when condition3 is true but it > > will not print out "ok" when condition3 is true. When it's true it > > should print out borth "text" and "ok" > > In the second last sentence, it is difficult to determine what you > think is expected behaviour and what you say is the actual behaviour. > In the last sentence, what does the first "it" refer to? > > If the knowledge about returning None doesn't help you, try some > standard(??) techniques like inserting print statements or debugger > break-points. > > HTH, > John Thanks! That was exactly what it was. I solved it by using "return function(args+1)" instead of simply "function(args+1)." btw Steven you are so witty I hope to one day pwn noobs on newsgroups too. From steve at REMOVEME.cybersource.com.au Tue Feb 27 02:24:59 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Feb 2007 18:24:59 +1100 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: On Tue, 27 Feb 2007 06:40:29 +0000, Alan Isaac wrote: > "Ben Finney" wrote in message > news:mailman.4438.1172534289.32031.python-list at python.org... >> The Pythonic design is: don't expect to have such control over users >> of your code. > > I know this is a popular response, It's popular for good reason. > but the fact of the matter remains that > it can be helpful to know when someone > tries to set a value for a nonexisting attribute. I'm afraid your understanding of the word "fact" is different from my understanding of the word "fact". But be that as it may, if you wish to waste^H^H^H^H^H spend time trying to prevent people from adding attributes to their instances, Just Because, you can do something like this: class Difficult(object): def __setattr__(self, name, value): if self.__dict__.has_key(name): print "'%s' exists as an instance attribute" % name self.__dict__[name] = value elif self.__class__.__dict__.has_key(name): print "'%s' exists as a class attribute" % name self.__class__.__dict__[name] = value else: print "Can't create new attributes, 'cos I said so!" There ought to be a name for that anti-pattern of molly-coddling, bondage-and-domination philosophy of "you're only allowed to use my class the way I want you to use it". (Excuse my cynicism, for all I know you've got a really good reason for wanting to do this, perhaps as part of a cold-fusion machine.) -- Steven D'Aprano From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 13:14:53 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 19:14:53 +0100 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: Thinker wrote: > Since PyArg_ParseTuple() is supposed to parse arguments, I recommand you > to use PyTuple_GetItem() or PyTuple_GET_ITEM(). Ok. Now I do it this way: c_real = PyFloat_AsDouble(PyTuple_GetItem(coord,0)); c_imag = PyFloat_AsDouble(PyTuple_GetItem(coord,1)); And it worked... once. The problem is really funny - in the interactive the function fails every second time. >>> mandelpixel((1.5, 1.5), 9, 2.2) args parsed coord parsed ii3 >>> mandelpixel((1.5, 1.5), 9, 2.2) TypeError: bad argument type for built-in operation >>> mandelpixel((1.5, 1.5), 9, 2.2) args parsed coord parsed ii3 >>> mandelpixel((1.5, 1.5), 9, 2.2) TypeError: bad argument type for built-in operation etcaetera.... (the "args parsed" "coord parsed" and "i" are effect of printfs in the code, as you see when it fails, it doesn't even manage to parse the arguments. zefciu From malaclypse2 at gmail.com Wed Feb 7 18:07:17 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 7 Feb 2007 18:07:17 -0500 Subject: Python new user question - file writeline error In-Reply-To: <1170876692.167248.244870@s48g2000cws.googlegroups.com> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> Message-ID: <16651e80702071507n39c2b64di97c4de28fed01fde@mail.gmail.com> On 7 Feb 2007 11:31:32 -0800, James wrote: > I have this code: ... > infile.close > outfile.close ... > 1. the outfile doesn't complete with no error message. when I check > the last line in the python interpreter, it has read and processed the > last line, but the output file stopped before. You need to call the close methods on your file objects like this: outfile.close() If you leave off the parentheses, you get the method object, but don't do anything with it. > 2. Is this the best way to do this in Python? I would parse your dates using the python time module, like this: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.2 >>> import time >>> line = r'06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/NOV/2006,V1,,,21/NOV/2006,AST,19,U/L,5,40,,' >>> item = line.split(',') >>> time.strftime('%a, %d %b %Y', timedate) 'Sun, 05 Mar 1950' >>> dob = item[6] >>> dob_time = time.strptime(dob, '%d/%b/%Y') >>> dob_time (1950, 3, 5, 0, 0, 0, 6, 64, -1) >>> time.strftime('%Y-%m-%d', dob_time) '1950-03-05' See the docs for the time module here: http://docs.python.org/lib/module-time.html Using that will probably result in code that's quite a bit easier to read if you ever have to come back to it. You also might want to investigate the csv module (http://docs.python.org/lib/module-csv.html) for a bunch of tools specifically tailored to working with files full of comma separated values like your input files. -- Jerry From jstroud at mbi.ucla.edu Fri Feb 9 19:37:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 09 Feb 2007 16:37:48 -0800 Subject: Retry:Question about optparse/OptionParser callback. In-Reply-To: References: Message-ID: Steven W. Orr wrote: > I decided I could be more articulate. I hope this helps. > > I'm writing a program that needs to process options. Due to the nature > of the program with its large number of commandline options, I would > like to write a callback to be set inside add_option. > > Something like this: > > parser.add_option("-b", action="callback", callback=optionhandlr, dest='b') > > The Cookbook almost takes me there with a callback function that only > works for an option called b that takes no argument: > > def optionhndlr(option, opt_str, value, parser): > if parser.values.b: > raise OptionValueError("can't use %s after -b" % opt_str) > setattr(parser.values, option.dest, 1) > > but warns that "it needs a bit of work: the error message and the flag > that it sets must be generalized". I do need to do my option processing > in an option processor with many options and I'd both like to do it in > one method (if possible) and learn a trick or two while I'm at it. Is it > possible to have a single callback that could be used in the general case? > > All I need is to be taught how to fish... > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things > have .0. > happened but none stranger than this. Does your driver's license say > Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are > all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net If I understand your question, you are already half way there: def optionhndlr(option, opt_str, value, parser): if getattr(parser.values, option.dest): msg = "can't use %s afer -%s" % (opt_str, option.dest) raise OptionValueError, msg setattr(parser.values, option.dest, 1) James From arnodel at googlemail.com Sun Feb 25 15:37:07 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 25 Feb 2007 12:37:07 -0800 Subject: Nested Parameter Definitions In-Reply-To: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> Message-ID: <1172435827.794518.36170@t69g2000cwt.googlegroups.com> On Feb 25, 6:00 pm, "Paddy" wrote: > I blogged on finding a new-to-me feature of Python, in that you are > allowed to nnest parameter definitions: > > >>> def x ((p0, p1), p2): > > ... return p0,p1,p2 > ...>>> x(('Does', 'this'), 'work') > > ('Does', 'this', 'work') Reminds me of LeLisp! It had a similar feature. IIRC you could write for example (I think 'df' was LeLisp for 'defun'): (df mycar (a . b) a) or (df mylist L L) or (df mycaadr (a (b . c) . e) b) I didn't know that this was possible in python and it does surprise me. It feels at odd with the python philosophy. -- Arnaud From grahamd at dscpl.com.au Sun Feb 4 16:40:04 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 4 Feb 2007 13:40:04 -0800 Subject: Python does not play well with others In-Reply-To: <7xfy9mekxr.fsf@ruckus.brouhaha.com> References: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> Message-ID: <1170625204.156763.178460@j27g2000cwj.googlegroups.com> On Feb 4, 1:05 pm, Paul Rubin wrote: > "Paul Boddie" writes: >> Probably the biggest inhibitor, as far as I can see, has been the >> server technology chosen. Many hosting providers have historically >> offered no better than CGI for Python, whilst PHP runs within Apache >> itself, and it has previously been stated that mod_python has been >> undesirable with regard to isolating processes from each other. >> Consequently, a number of Python people seem to have held out for >> other "high performance" solutions, which various companies now offer. > > Your point that shared hosting with Python isn't so easy because of > insufficient isolation between apps is valid. Maybe Python 3.0 can do > something about that and it seems like a valid thing to consider while > fleshing out the 3.0 design. To clarify some points about mod_python, since these posts do not properly explain the reality of the situation and I feel people are getting the wrong impression. First off, when using mod_python it is possible to have it create multiple sub interpreters within each Apache child process. These distinct sub interpreters can be linked to different parts of the URL namespace. This means that it is possible to host more than one mod_python application where each executes within in their own distinct sub interpreter. The outcome of this is that each application can have their own sys.path, own os.environ, own sets of modules and potentially with different versions of some module. Maintaining separation using sub interpreters eliminates the bulk of problems with applications interfering which each other at least within a process. Some problems can still arise though where third party extension modules for Python aren't written so as to be usable from multiple sub interpreters at the same time however. This is not a failing of mod_python though, but a failing of the module writers. The main area where interference can occur is where applications needs to write to the file system. This is because all code will be executing as the user that Apache runs as. Thus, distinct applications could overwrite each others data within the file system. On one level this just means that applications need to be configured to always use their own part of the file system. For example, if using the support in mod_python for sessions, the distinct applications should perhaps use separate session databases rather than use the same common database. Ultimately though, a rogue application could write where ever it wants to, but from what I know (and could be wrong), this isn't different to other languages systems within Apache such as PHP and mod_perl. Another possibility for interference is where an application simply does something bad like get stuck in a tight loop or consume lots of memory. Such an event can possibly interfere with other applications, even across language boundaries, however, how bad the impact will be depend on what MPM is used by Apache. If "prefork" MPM is used, then the request being handled by that application is the only thing which would be running within that child process at that particular time. Thus, if it stops the functioning of just that one process it doesn't matter as Apache will just farm requests off to other child processes. If that initial child process crashes because of the problem, then again it doesn't matter as Apache will just create another child process to replace it and will otherwise keep running. If the "worker" MPM is used the impact can be greater as there could be other requests being handled concurrently within the same child process and the performance of those requests may be hindered. If the worst happens and the child process crashes, only other requests being handled within that specific child process would be affected, those in other child processes would again continue unaffected as would Apache as a whole. The worst case is the "winnt" MPM (ie., Windows boxes). This is because there is only one Apache process and thus a rogue application can affect the whole Apache web server. It should be highlighted though that this class of problem is not unique to Python or mod_python as you could get rogue code in a PHP page or mod_perl application just as easily. What it all really comes down to is that the only features that are really missing are the ability for distinct applications to run as distinct users, or for applications to run inside of some sort of chroot environment. Some aspects of this are addressed by FCGI and SCGI, but again lack of this feature within mod_python itself is not unique to it and that as far as I know is also going to be an issue for other language systems for Apache such as PHP or mod_perl. Having said all that, perhaps those who are complaining about lack of support for specific features in mod_python can now clarify what actually you are talking about. At the moment the brief comments being made seem to possibly cover some things that mod_python can already do but may not be obvious. Graham From rschroev_nospam_ml at fastmail.fm Fri Feb 16 09:27:50 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 16 Feb 2007 14:27:50 GMT Subject: Pep 3105: the end of print? In-Reply-To: References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: Edward K Ream schreef: >> There are a tool called "2to3" that translates things like "print foo" to >> print(foo). > > The point of my original post was that if I want to maintain a common code > base the tool must translate 'print foo' to 'print2(foo)'. At first sight it seems to me that it's pretty straightforward to translate print(foo) to print2(foo) once "2to3" has done its job. It looks your main issue is that you're complaining that Python 3000 is going to break things in a non-backward compatible way. If you want to change that, you're going to be fighting an uphill battle, as this quote from PEP 3000 illustrates: "We need a meta-PEP to describe the compatibility requirements. Python 3000 will break backwards compatibility. There is no requirement that Python 2.9 code will run unmodified on Python 3.0. I'm not sure whether it is reasonable to require that Python 2.x code can be mechanically translated to equivalent Python 3.0 code; Python's dynamic typing combined with the plans to change the semantics of certain methods of dictionaries, for example, would make this task really hard. However, it would be great if there was some tool that did at least an 80% job of translation, pointing out areas where it wasn't sure using comments or warnings. Perhaps such a tool could be based on something like Pychecker." -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From bignose+hates-spam at benfinney.id.au Thu Feb 1 22:58:46 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 14:58:46 +1100 Subject: need help on a data structure problem References: Message-ID: <87bqkdus5l.fsf@benfinney.id.au> "Dongsheng Ruan" writes: > Not quite related with Python. But my Data Structure course is > experiemented on python and there is no data structure group, So I > have to post here: Better, you should discuss it in your class, with your teacher. -- \ "As we enjoy great advantages from the inventions of others, we | `\ should be glad to serve others by any invention of ours; and | _o__) this we should do freely and generously." -- Benjamin Franklin | Ben Finney From CRhode at LacusVeris.com Tue Feb 27 10:16:54 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Tue, 27 Feb 2007 09:16:54 -0600 Subject: Python Source Code Beautifier References: Message-ID: Franz Steinhaeusler wrote this on Tue, 27 Feb 2007 09:45:42 +0100. My reply is below. > Hello, I did not find any reasonable pyhton source code beautifier > program (preferable gui). -snip- > Is there such a tool around? Why, yes! Yes, there is: o http://lacusveris.com/PythonTidy/PythonTidy.python It doesn't have a graphical user interface, and it doesn't do everything you want, and it isn't reasonable (It's of an unreasonable size.), but it is a beginning. For future reference, look in: o http://cheeseshop.python.org/pypi ... under "reformat." -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 26? ? Wind WNW 5 mph ? Sky overcast. Mist. From rpmuller at gmail.com Thu Feb 15 20:57:19 2007 From: rpmuller at gmail.com (RickMuller) Date: 15 Feb 2007 17:57:19 -0800 Subject: numpy, numarray, or numeric? In-Reply-To: References: Message-ID: <1171591039.085342.21280@l53g2000cwa.googlegroups.com> On Feb 15, 5:40 pm, "Christian Convey" wrote: > I need to bang out an image processing library (it's schoolwork, so I > can't just use an existing one). But I see three libraries competing > for my love: numpy, numarray, and numeric. > > Can anyone recommend which one I should use? If one is considered the > officially blessed one going forward, that would be my ideal. > > Thanks, > Christian Use numpy; it is the "officially blessed one" that you refer to. It has all of the advantages of the other two. Numeric was the first library, but it had some drawbacks that led some people to develop Numarray, which had some additional features. Finally, the numpy project was started to unify the two groups by providing some of the new features in a code base consistent with the old library as well. From ullrich at math.okstate.edu Sat Feb 24 07:26:31 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sat, 24 Feb 2007 06:26:31 -0600 Subject: CSV(???) References: <1172244695.585282.111350@s48g2000cws.googlegroups.com> Message-ID: <9g80u2d2kvsocg4opftpek11rrsd1qqnob@4ax.com> On 23 Feb 2007 07:31:35 -0800, "John Machin" wrote: >On Feb 23, 10:11 pm, David C. Ullrich >wrote: >> Is there a csvlib out there somewhere? > >I can make available the following which should be capable of running >on 1.5.2 -- unless they've suffered bitrot :-) > >(a) a csv.py which does simple line-at-a-time hard-coded-delimiter-etc >pack and unpack i.e. very similar to your functionality *except* that >it doesn't handle newline embedded in a field. You may in any case be >interested to see a different way of writing this sort of thing: my >unpack does extensive error checking; it uses a finite state machine >so unexpected input in any state is automatically an error. Actually a finite-state machine was the first thing I thought of. Then while I was thinking about what states would be needed, etc, it ocurred to me that I could get something working _now_ by just noticing that (assuming valid input) a quoted field would be terminated by '",' or '"[eos]'. A finite-state machine seems like the "right" way to do it, but there are plenty of other parts of the project where doing it right is much more important - yes, in my experience doing it "right" saves time in the long run, but that finite-state machine would have taken more time _yesterday_. >(b) an extension module (i.e. written in C) with the same API. The >python version (a) imports and uses (b) if it exists. > >(c) an extension module which parameterises everything including the >ability to handle embedded newlines. > >The two extension modules have never been compiled & tested on other >than Windows but they both should IIRC be compilable with both gcc >(MinGW) and the free Borland 5.5 compiler -- in other words vanilla C >which should compile OK on Linux etc. > >If you are interested in any of the above, just e-mail me. Keen. >> >> And/or does anyone see any problems with >> the code below? >> >> What csvline does is straightforward: fields >> is a list of strings. csvline(fields) returns >> the strings concatenated into one string >> separated by commas. Except that if a field >> contains a comma or a double quote then the >> double quote is escaped to a pair of double >> quotes and the field is enclosed in double >> quotes. >> >> The part that seems somewhat hideous is >> parsecsvline. The intention is that >> parsecsvline(csvline(fields)) should be >> the same as fields. Haven't attempted >> to deal with parsecsvline(data) where >> data is in an invalid format - in the >> intended application data will always >> be something that was returned by >> csvline. > >"Always"? Famous last words :-) Heh. Otoh, having read about all the existing variations in csv files, I don't think I'd attempt to write something that parses csv provided from an external source. >> It seems right after some >> testing... also seems blechitudinous. > >I agree that it's bletchworthy, but only mildly so. If it'll make you >feel better, I can send you as a yardstick csv pack and unpack written >in awk -- that's definitely *not* a thing of beauty and a joy >forever :-) > >I presume that you don't write csvline() output to a file, using >newline as a record terminator and then try to read them back and pull >them apart with parsecsvline() -- such a tactic would of course blow >up on the first embedded newline. Indeed. Thanks - this is exactly the sort of problem I was hoping people would point out (although in fact this one is irrelevant, since I already realized this). In fact the fields will not contain linefeeds (the data is coming from on an html form, which means that unless someone's _trying_ to cause trouble a linefeed is impossible, right? Regardless, incoming data is filtered. Fields containing newlines are quoted just to make the thing usable in other situations - I wouldn't use parsecsvline without being very careful, but there's no reason csvline shouldn't have general applicability.) And in any case, no, I don't intend to be parsing multi-record csv files. Although come to think of it one could modify the above to do that without too much trouble, at least assuming valid input - end-of-field followed by linefeed must be end-of-record, right? >So as a matter of curiosity, where/ >how are you storing multiple csvline() outputs? Since you ask: the project is to allow alumni to store contact information on a web site, and then let office staff access the information for various purposes. So each almunus' data is stored as a csvline in an anydbm "database" - when someone in the office requests the information it's dumped into a csv file, the idea being that the office staff opens that in Excel or whatever. (Why not simply provide a suitable interface to the data instead of just giving them the csv file? So they can use the data in ways I haven't anticipated. Why not give them access to a real database? They know how to use Excel. I do think I'll provide a few access thingies in addition to the csv file, for example an automatic mass mailer...) So why put csv data into an anydbm thing instead of using shelve or something? Laughably or not, the reason is to speed up what seems like the main bottleneck: If I use my parsecsvline() that will be very slow. But that doesn't matter, since that only happens once or twice a day on one record, when an alumnus logs in and edits his contact information. But when the office requests the data we run through the entire database - if we store the data as csv then we don't have any conversion to do at that point, we just write the raw data in the database to a file. Should be much quicker than converting something else to csv at that point. (So why not just store the data in a csv file? Random access.) Since you asked, if you had any comments on what's silly about the general plan there by all means say so. Hmm. Why not use one of the many Python web tools out there? (i) Doing it myself is more interesting. I'm not getting paid for this. (ii) If I do it muself it's going to be easier for me to be certain I know exactly where user input is at all times. The boss wanted me to use php because Python was going to be too hard for someone else to read. That's nonsense, of course. Anyway, he gave me a book on php security. The book raised a lot of issues that I wouldn't have thought of, but it also convinced me I wouldn't want to use php - all through the book we're warned that php will do this or that bad thing if you're not careful. Don't want to have to learn all the things you need not to do with whatever tool I use. Here, the only write access to the database is through an Alum object; Alum objects filter their data on creation, and they're read-only (via the magic of ___setattr__), so a maintainer would have _try_ if he wanted to insert unfiltered data - wouldn't be hard to do, but he can't do it by accident. And the only html output is through PostHTML, which filters everything through cgi.escape(). In particular print statements raise exceptions (via sys.stdout = PrintExploder().) Again, a maintainer could easily write to sys.__stdout__ to get around this, but that's not going to happen by accident. Altogether seems much cleaner than the php stuff I saw in that book - the way he does things you need to be careful every time you do something, with the current setup I only need to be careful twice, in Alum.__init__ and in PostHTML. Could be I'm being arrogant putting more trust in asetup like that instead of some well-known Python web thingie. But I don't see anyplace things can leak out, and using someone else's thing I'd either have to just believe them or read a lot of code. That'll teach you to express curiosity about something I'm doing. Been thinking about all this for a few weeks, you asked a question and the fingers started ty[ing. >> >> (Um: Believe it or not I'm _still_ using >> python 1.5.7. So comments about iterators, >> list comprehensions, string methods, etc >> are irrelevent. Comments about errors in >> the algorithm would be great. Thanks.) > >1.5.7 ? Well I _said_ you wouldn't believe it... >[big snip] > >Cheers, >John ************************ David C. Ullrich From aahz at pythoncraft.com Mon Feb 26 19:03:55 2007 From: aahz at pythoncraft.com (Aahz) Date: 26 Feb 2007 16:03:55 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: In article , Dan Bensen wrote: >Tech HR wrote: >> >> easier to train a Java programmer or a Perler on Python than Lisp. > >Are your technical problems simple enough to be solved by Python trainees? If they're already good programmers, yes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From gagsl-py at yahoo.com.ar Mon Feb 5 17:55:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 19:55:42 -0300 Subject: stlib name clash when using python as ASP language References: <1170323389.184681.250640@v45g2000cwv.googlegroups.com> <1170593602.308391.225180@a34g2000cwb.googlegroups.com> Message-ID: En Sun, 04 Feb 2007 09:53:22 -0300, Joost escribi?: >> You *assume* that [0] is the IIS path, but perhaps some other imported >> module changed sys.path too, and now it's not the first one anymore. >> If you know exactly the path, try sys.path.remove(iis_path). >> > > It's was a hack and definitely not meant to go in to production ;) > Since gzip.py lives in python24\lib I thought setting sys.path[0] to > python24\lib would load this load this module, no matter what. > However, in some magically way the sys.path gets modified during the > request by IIS. Maybe IIS resets the global sys.path per new request, > causing sporadic problems when request are handled concurrently? I > just don't know. The iis/inetsrv path is included in sys.path for a > reason and I don't want to fiddle around with sys.path to create > problems in other parts of the code. I was wandering if there is some > way to prevent a name clashes by using a custom importer or something > like that. Python 2.5 has absolute and relative imports, that should handle such problems in the future. But in your case I can think of: - *prepend* python24\lib instead of replacing index 0: sys.path.insert(0, python24\lib) - copy gzip.py to another, empty directory, and put *that* directory in front of sys.path - play with ihooks.py -- Gabriel Genellina From eopadoan at altavix.com Fri Feb 2 07:36:27 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 2 Feb 2007 10:36:27 -0200 Subject: compound statement from C "?:" In-Reply-To: References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> Message-ID: http://effbot.org/pyfaq/is-there-an-equivalent-of-c-s-ternary-operator.htm -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com From steve at REMOVEME.cybersource.com.au Wed Feb 14 23:52:03 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 15:52:03 +1100 Subject: f---ing typechecking References: Message-ID: On Wed, 14 Feb 2007 19:45:14 -0800, James Stroud wrote: > Steven D'Aprano wrote: >> On Wed, 14 Feb 2007 13:25:21 -0800, James Stroud wrote: >> >> >>>But then again, the unimaginative defense would be that it wouldn't be >>>python if you could catentate a list and a tuple. >> >> >> Since lists and tuples are completely different objects with completely >> different usages, what should concatenating a list and a tuple give? >> Should it depend on the order you pass them? > > Is that a guess or just common sense? Sorry, is *what* a guess? Conceptually, ints are a subset of floats (they certainly are in pure mathematics). Automatic coercions from ints to floats makes sense; automatic coercions the other way rarely do -- should you round up or round down or truncate? What is right in one application is not right for another. Lists and tuples, on the other hand, are conceptually two distinct data types. Adding a list to a tuple is no more sensible than adding a list to a string -- just because they're both sequences doesn't mean adding them together is meaningful. >> 1.0 + 1 == 1 + 1.0 for very good reasons: we consider (for pragmatic >> reasons to do with loss of significant digits) that floats coerce ints >> into floats rather than the other way around. But what should lists and >> tuples do? >> >> From the Zen of Python: >> "In the face of ambiguity, refuse the temptation to guess." > > Do you guess with __add__ and __radd__? No. If there is an obviously correct behaviour for addition (like with ints and floats) then I coerce the objects appropriately. If there is no obviously correct behaviour, I refuse to guess. The user's expected behaviour for [1] + (1,) might be to return a list, or it might be to return a tuple. Since there is no obviously correct behaviour, the right thing to do is to refuse to guess. -- Steven D'Aprano From naima.mans at gmail.com Tue Feb 27 05:52:10 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 27 Feb 2007 02:52:10 -0800 Subject: spawnl and waitpid In-Reply-To: References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> Message-ID: <1172573530.625901.36420@k78g2000cwa.googlegroups.com> On 27 f?v, 11:28, Thinker wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > naima.m... at gmail.com wrote: > > hello, > > > I run a python cgi script under Apache... > > > and while the script is running i want to display a "please wait" > > message until the script finish. > > > I have tried to do this but the "please wait" message appears at > > the script end (which is useless at this time! ) > > You should flush sys.stdout after you print messages, or > the message will keep in buffer untill buffer is full or process > terminated. > > - -- > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF5Afi1LDUVnWfY8gRAgaoAJ9fccAjo00QupE7SRFqgbmOUGZMugCgjvdH > cFoxm+jiZiIpKOfd+fHCt/M= > =9COv > -----END PGP SIGNATURE----- Hello thanks for answering i have flush like this but same result .. the server wait until the end... pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python","Main.py") sys.stdout.flush() ret = os.waitpid(pid,0) if ( ret[1] != 0): print """ wait %i """ %ret[1] sys.stdout.flush() else: print """ end %i """ %ret[1] sys.stdout.flush() From pklos at osmium.mv.net Mon Feb 12 09:47:56 2007 From: pklos at osmium.mv.net (Patrick Klos) Date: Mon, 12 Feb 2007 14:47:56 +0000 (UTC) Subject: How to Speed Up Internet Searches?? References: <1171129634.795533.325560@k78g2000cwa.googlegroups.com> Message-ID: In article <1171129634.795533.325560 at k78g2000cwa.googlegroups.com>, wrote: >How to Speed Up Internet Searches?? >When you go to a web site, the first thing that happens is that......... >and for networking tips see at > : : : Please don't post this kind of stuff here any more. It's off topic and unappreciated! From brusstoc at gmail.com Fri Feb 9 15:06:22 2007 From: brusstoc at gmail.com (brusstoc at gmail.com) Date: 9 Feb 2007 12:06:22 -0800 Subject: python linux distro In-Reply-To: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: <1171051582.332913.6980@v33g2000cwv.googlegroups.com> Try this. It's a pre-build VMware image. Torrent hasn't worked for me. I tracked down a physical copy. http://www.vmware.com/vmtn/appliances/directory/289 From mralokkp at gmail.com Sat Feb 24 12:08:42 2007 From: mralokkp at gmail.com (mralokkp) Date: 24 Feb 2007 09:08:42 -0800 Subject: Any Idea about thread safe issue with python In-Reply-To: <53mbupF1sepr5U1@mid.individual.net> References: <1171623555.377250.228240@j27g2000cwj.googlegroups.com> <53mbupF1sepr5U1@mid.individual.net> Message-ID: <1172336922.633157.181730@z35g2000cwz.googlegroups.com> On Feb 16, 11:37 pm, Bjoern Schliessmann wrote: > mralokkp wrote: > > I need help guys. I have a code running properly and execute again > > after a certain time. > > In Simple words [incomplete and useless code line] is not solving > > my purpose. Would any body like to help. > > Please be so kind and read this paragraph: > > http://www.catb.org/~esr/faqs/smart-questions.html#explicit > > Regards, > > Bj?rn > > -- > BOFH excuse #331: > > those damn raccoons! I am newbie here at your system.I was not aware of the system policies you follows guys. Any way The problem is sort out.Thanks for the reply. Regards Alok From matbsn at gmail.com Sat Feb 10 14:30:35 2007 From: matbsn at gmail.com (Bruno Nascimento) Date: 10 Feb 2007 11:30:35 -0800 Subject: Problems - using widgets.CheckboxTable - I would like examples... Message-ID: <1171135835.178650.212650@m58g2000cwm.googlegroups.com> oi I'm trying to use the checkboxtable and I'm having serios problems. I would like some idea or example. Somebory could help me? Any ideas.... Thanks Bruno Nascimento From tinaweb at bestemselv.com Sun Feb 11 03:29:09 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sun, 11 Feb 2007 09:29:09 +0100 Subject: irclib problems Message-ID: <28idnXfKwMtLTlPYRVnzvA@telenor.com> I'm playing around with the 'irclib' library working with the first example at http://www.devshed.com/c/a/Python/IRC-on-a-Higher-Level-Concluded/ When copying the example verbatim and running it from a console it works flawlessly. It connects to the server, join the channel and sits there 'forever'... However, I want to use it in a PyQt application and have done the following. I have created a module named 'irclibtest.py' that looks like this: ### irclibtest start ### import irclib irclib.DEBUG = True class Conn: def __init__(self): # Network information self.network = '192.x.x.x' self.port = 6667 self.channel = '#test' self.nick = 'IRClibt' self.name = 'Python Test' # Subclass SimpleIRCClient class ClientClass ( irclib.SimpleIRCClient ): pass # Create an instance of ClientClass and connect. self.client = ClientClass() self.client.connect ( self.network, self.port, self.nick, ircname = self.name ) self.client.connection.join ( self.channel ) ##irclibtest end ### And my main Qt application: ### Main application start ### #!/usr/bin/python # -*- coding: utf-8 -*- import sys, irclib from PyQt4 import QtGui , QtCore from tircUI import Ui_MainWindow from irclibtest import Conn class TircMain(QtGui.QMainWindow , Conn): def __init__(self): QtGui.QMainWindow.__init__(self ) Conn.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.connect(self.ui.sendButton, QtCore.SIGNAL("clicked()"), self.doSend) def doSend(self): ''' Just a test to see if I can send to channel''' self.client.connection.privmsg('#test' , 'Test text') if __name__ == "__main__": app = QtGui.QApplication(sys.argv) f = TircMain() f.show() sys.exit(app.exec_()) ### Main application end ## The problem is that this pings out (PING timeout). As far as I understand it rclib.SimpleIRCClient is supposed to handle PING-PONG with the server so I don't understand why it does not in my Qt test, but it does 'raw'. I can send to the channel right up to the point it times out by the way. Anyone know what I'm missing here? Thanks Tina From franz.steinhaeusler at gmx.at Thu Feb 1 10:02:52 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Thu, 01 Feb 2007 16:02:52 +0100 Subject: Ubunu - Linux - Unicode - encoding Message-ID: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> Hello NG, a little longer question, I'm working on our project DrPython and try fix bugs in Linux, (on windows, it works very good now with latin-1 encoding). On Windows, it works good now, using setappdefaultencoding and the right encoding for open with styled text control with the right encoding the files. (I see the german Umlauts ??? and the "strong 's'" "?") The case: I have a file on a WindowsXP partition which has as contents german umlauts and the filename itself has umlauts like i????k.txt If I want to append this file to a list, I get somehow latin-1, cannot decode 'utf-8'. sys.setappdefaultencoding(self.prefs.defaultencoding) would be the easiest solution which should be the same aus sys.setdefaultencoding in linux. Why is there a setappdefaultencoding on Windows and sys.setdefaultencoding on linux. I googled, and I found a strange solution (sys.setdefaultencoding is not available) import sys reload (sys) only then this function is available. Why is this setdefaultencoding otherwise not working on linux? (Also Filemanagers like Nautilus or Krusader cannot display the files correctly). Is there a system wide linux language setting (encoding), which I have to install and adjust? I know, there are the methods encode, unicode, decode, but how do I know, when they are needed, I don't want to replace all the source for encode, ... for string access. So setappdefaultencoding would be the easiest way. Should I use also/instead the wx.SetDefaultPyEncoding in DrPython? This would be the easiest solution, setappdefaultencoding, (getting it from preferences) but it doesn't work. Beside I tried other editors like spe, pype, boa, ulipad, but none of them displayed the file, which have german umlauts in the filesnames, correctly. Thank you verrrry much in advance for a possible solution. From steve at holdenweb.com Wed Feb 7 13:07:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Feb 2007 18:07:53 +0000 Subject: multithreading concept In-Reply-To: References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> Message-ID: <45CA1579.8060300@holdenweb.com> John Nagle wrote: > sturlamolden wrote: >> On Feb 7, 2:53 am, "S.Mohideen" >> wrote: >> This has been discussed to death before. Win32 threads and pthreads >> (which is what Python normally uses, depending on the platform) are >> designed to stay idle most of the time. They are therefore not a tool >> for utilizing the power of multiple CPUs, but rather make certain kind >> of programming tasks easier to program (i.e. non-blocking I/O, >> responsive UIs). > > Multithread compute-bound programs on multiple CPUs are > how you get heavy number-crunching work done on multiprocessors. > Of course, that's not something you use Python for, at least not > until it gets a real compiler. > > It's also the direction games are going. The XBox 360 forced > game developers to go that way, since it's a 3-CPU shared memory > multiprocessor. That translates directly to multicore desktops > and laptops. > > I went to a talk at Stanford last week by one of Intel's > CPU architects, and he said we're going have hundreds of > CPUs per chip reasonably soon. Python needs to get ready. > Define "Python". Does "it" include you? What does it need to do to get ready. How do you plan to help? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From mail at timgolden.me.uk Thu Feb 22 15:07:23 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 22 Feb 2007 20:07:23 +0000 Subject: How can I track/monitor an application and system resources. In-Reply-To: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> References: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> Message-ID: <45DDF7FB.2070804@timgolden.me.uk> richard_l at latter.demon.co.uk wrote: > Hello All, > > I'm a newbie to Python! > > I am trying to develop a program that monitors the performance of an > application. The kind of information I am interested in is the CPU/ > Process/Thread and memory performance. Specifically, I would like to > track the following > > CPU usage > Used Memory on Phone > Free Memory on Phone > Number of Processes running > Number of threads running > Number of Filehandles currently open > Memory used by a process/thread > Process/Thread CPU activity. > > All this under Windows Not sure about the "... on Phone" bit. Assuming you're on a supported platform, sounds like you want to look at the WMI stuff, in particular Win32_PerfFormattedData[1]. There are examples around the web, usually in VBS style. They're easy enough to translate into Python, either using the win32com module[2] directly, or using my WMI helper module[3]. [1] http://msdn2.microsoft.com/en-us/library/aa394253.aspx [2] http://pywin32.sf.net [3] http://timgolden.me.uk/python/wmi.html TJG From skip at pobox.com Tue Feb 27 15:28:54 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 27 Feb 2007 14:28:54 -0600 Subject: difference between string and list In-Reply-To: <45E4465D020000C50000701E@gw.osc.edu> References: <45E4465D020000C50000701E@gw.osc.edu> Message-ID: <17892.38022.134349.633488@montanaro.dyndns.org> lincoln> strings have methods like string.count("f") returns 1. What lincoln> methods do lists have? Is it a similar class to string? Similar in some ways, different in others. Some things to play with: 1. At an interpreter prompt, execute: help("") help([]) 2. Check the relevant sections of the tutorial: http://docs.python.org/dev/tut/node5.html#SECTION005120000000000000000 http://docs.python.org/dev/tut/node5.html#SECTION005140000000000000000 Two significant differences: 1. Strings are immutable. 2. Lists can contain any kind of object, not just characters. Skip From jstroud at mbi.ucla.edu Tue Feb 27 19:39:03 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 27 Feb 2007 16:39:03 -0800 Subject: Vector, matrix, normalize, rotate. What package? In-Reply-To: <1172616572.045690.17550@k78g2000cwa.googlegroups.com> References: <1172616572.045690.17550@k78g2000cwa.googlegroups.com> Message-ID: Mattias Br?ndstr?m wrote: > Hello! > > I'm trying to find what package I should use if I want to: > > 1. Create 3d vectors. > 2. Normalize those vectors. > 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in > radians. > 4. Perform matrix multiplication. > > It seems to me that perhaps numpy should be able to help me with this. > However, I can only figure out how to do 1 and 4 using numpy. Meybe > someone knows a way to use numpy for 2 and 3? If not, what Python > package helps me with geometry related tasks such as 2 and 3? > > Any help here would be greatly appreciated! > > Regards, > Mattias > As Paul is hinting, your best bet is to make use of quaternions, you will save yourself a lot of frustration as soon as you need to do anything with them outside of matrix-multiplying a bunch of 3D coordinates. See the Scientific Python module: Scientific.Geometry.Quaternion. To make a matrix from Quaternion, q, use "q.asRotations().tensor". To make a quaternion from an axis and an angle, here is what I use: ####################################################################### # axis_angle_to_quaternion() ####################################################################### def axis_angle_to_quaternion(axis, angle): """ Takes an I{axis} (3x1 array) and an I{angle} (in degrees) and returns the rotation as a I{Scientific.Geometry.Quaternion.Quaternion}. @param axis: 3x1 array specifiying an axis @type axis: numarray.array @param angle: C{float} specifying the rotation around I{axis} @type angle: float @return: a I{Quaternion} from an I{axis} and an I{angle} @rtype: Quaternion """ axis = normalize(axis) angle = math.radians(float(angle)) qx = float(axis[0]) qy = float(axis[1]) qz = float(axis[2]) sin_a = math.sin(angle / 2.0) cos_a = math.cos(angle / 2.0) qx = qx * sin_a qy = qy * sin_a qz = qz * sin_a qw = cos_a return Quaternion(qw, qx, qy, qz).normalized() See your linear algebra text on how to normalize a 1x3 vector. James From steve at holdenweb.com Thu Feb 8 11:04:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Feb 2007 16:04:11 +0000 Subject: Simple Interpolation in Numpy? In-Reply-To: <134863FF4EA9A54E8EC307A2F4214566096E0E51@ACCLUST01EVS1.ugd.att.com> References: <134863FF4EA9A54E8EC307A2F4214566096E0E51@ACCLUST01EVS1.ugd.att.com> Message-ID: <45CB49FB.4030706@holdenweb.com> LAPI, VINCENT J, ATTLABS wrote: > Hi, > Please bear with me as I am new to Python and have not done any > programming in about 20 years. I am attempting to do a simple > interpolation of a line's intermediate points given the x,y coordinates > of the line's two endpoints within an Active State Python script that I > am working with. Is there a simple way to do this simple interpolation > in the Active state Python 2.4 that I have or do I need to get Numeric > Python? And where do I get it? > Thanks, > Vince Lapi > You shouldn't really *need* Numeric (NumPy or numpy, nowadays) for a relatively simple problem like that, since the formulae involved are pretty simple. Given known points on the line at (xa, ya) and (xb, yb) then for any point (x, y) on the line we get y = ya + ((x - xa) * (yb - ya))/(xb - xa) So you just need to plug the values for x and the known points into the formula to get the interpolated value of y. If you are interpolating a non-linear formula through a number of samples clearly there'd be a little more jiggery pokery involved to identify the particular interval on which interpolation is required, but nothing horrendous. Numpy, which is derived from the old Numeric code, is at http://numpy.scipy.org/ should you wish to investigate its features. It probably has better-than-linear interpolation algorithms in it. Note that if you decide to download it you should choose the Python 2.4 version - extensions coded in compiled languages are specific to a particular version of the language. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gerald.kaszuba at gmail.com Sat Feb 10 02:13:16 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 9 Feb 2007 23:13:16 -0800 Subject: pycallgraph 0.2.0 Message-ID: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> Hi I just released a new version of pycallgraph. It has many improvements over 0.1.0. Here is an example of a call graph made in pycallgraph 0.2.0: http://pycallgraph.slowchop.com/pycallgraph/wiki/RegExpExample There are more examples on the web site: http://pycallgraph.slowchop.com/ The changes are: * Windows access denied bug fixed * graph uses different colours depending on the number of calls made to the function * graph settings and look are very customisable * exclude and include filters * stop_trace() is not required anymore, it is called automatically by make_graph() * will throw an exception if there is an error from dot/neato * removed obvious use of __main__ as the module name * added some examples There is no documentation yet but if you browse the source you'll be able to figure out a lot. Enjoy! Gerald From gagsl-py at yahoo.com.ar Fri Feb 23 18:20:12 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Feb 2007 20:20:12 -0300 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> Message-ID: En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns escribi?: > I am starting to use rationals and since I found no batteries included, > I tried out the mxNumber package. > > However, I get strange warnings on comparison operations > (which however seem to yield correct results): mx.Number.Rational is horribly broken. They break this rule: a==b => hash(a)==hash(b) so they can'b be used as dictionary keys, by example. Try the other packages suggested. I've used clnum without problems. -- Gabriel Genellina From fccoelho at gmail.com Thu Feb 22 13:50:15 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 10:50:15 -0800 Subject: plugin development best practices In-Reply-To: <1172160258.523074.299770@q2g2000cwa.googlegroups.com> References: <545q9iF1ujiklU1@mid.uni-berlin.de> <1172160258.523074.299770@q2g2000cwa.googlegroups.com> Message-ID: <1172170213.356412.302920@v45g2000cwv.googlegroups.com> On Feb 22, 2:04 pm, "Paul Boddie" wrote: > On 22 Feb, 16:13, "Diez B. Roggisch" wrote: > > > > > Darn. You're right of course - I just got the basic idea, and formed in my > > mind the "get the modules filename, thus the path, glob over it for *py, > > and thus get the subsequent module names"-pattern. Which is trivial of > > course, but not as trivial as just dir(module) > > The __init__.py file of a plugins package could contain something like > this: > > # Start > def init(): > import os > global __all__ > this_dir = os.path.split(__file__)[0] > py_suffix = os.path.extsep + "py" > __all__ = [] > for filename in os.listdir(this_dir): > if os.path.isdir(os.path.join(this_dir, filename)) and \ > os.path.exists(os.path.join(this_dir, filename, "__init__" > + py_suffix)): > __all__.append(filename) > else: > module, suffix = os.path.splitext(filename) > if suffix == py_suffix and module != "__init__": > __all__.append(module) > init() > del init > # End > > This should populate the __all__ attribute of the package with then > names of any submodules or subpackages. Although that in itself won't > provide the names of the plugins via the dir function, the __all__ > attribute is some kind of standard, and things like "from plugins > import *" will import all the known plugins. In fact, if you add such > an import statement to the end of the above code, you'll get all the > names of the plugins stored within the package (and thus returned by > the dir function) because the submodules and subpackages will actually > have been imported. Even reloading the plugins package will update the > __all__ attribute, although things like the unloading or removal of > plugins might be challenging in a solution where such things are > automatically imported. > > Having a variation of the above function in the standard library could > be fairly useful, I suppose. > > Paul Hi Paul, Thanks for the fix. I had not tested my idea. anyway here goes another solution: I create a plugins package containing a single plugin named a.py, with just a single line: print "hi" here is the code for the __init.py: import os plugindir = os.path.split(__file__)[0] for f in os.listdir(plugindir): f = os.path.split(f)[-1] if f.endswith('.py'): f = f.split('.')[0] try: exec('import %s'%f) except: pass Now, if we import the plugins package, we can see module a, in the output of dir: In [1]:import plugins hi In [2]:dir(plugins) Out[2]: ['__builtins__', '__doc__', '__file__', '__init__', '__name__', '__path__', 'a', 'f', 'os', 'plugindir'] best, Fl?vio From robin at reportlab.com Mon Feb 5 13:04:14 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 05 Feb 2007 18:04:14 +0000 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: <45C7719E.9020306@chamonix.reportlab.co.uk> Dennis Lee Bieber wrote: > On Mon, 05 Feb 2007 17:52:27 +0100, Bjoern Schliessmann > declaimed the following > in comp.lang.python: > >> Mh, just looking at some "advanced" J source taken from >> wikipedia.org makes me feel sick: >> >> | Here's a J program to calculate the average of a list of numbers: >> | avg=: +/ % # >> | avg 1 2 3 4 >> | 2.5 >> > That looks like some variation of APL my colleague informs me that it is indeed associated with some of the same people if not with Mr Iverson. -- Robin Becker From rds1226 at sh163.net Thu Feb 22 12:43:43 2007 From: rds1226 at sh163.net (John) Date: Thu, 22 Feb 2007 12:43:43 -0500 Subject: How to covert ASCII to integer in Python? Message-ID: Is there any built in function that converts ASCII to integer or vice versa in Python? Thanks! From cniharral at gmail.com Fri Feb 2 08:09:29 2007 From: cniharral at gmail.com (cniharral at gmail.com) Date: 2 Feb 2007 05:09:29 -0800 Subject: How do I print out in the standard output coloured lines In-Reply-To: References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> <1170419225.989358.311600@h3g2000cwc.googlegroups.com> Message-ID: <1170421768.302283.173170@a34g2000cwb.googlegroups.com> On Feb 2, 1:38 pm, rzed wrote: > cnihar... at gmail.com wrote innews:1170419225.989358.311600 at h3g2000cwc.googlegroups.com: > > > > > On Feb 2, 1:16 pm, rzed wrote: > >> cnihar... at gmail.com wrote > >> innews:1170417631.268771.108090 at v45g2000cwv.googlegroups.com: > > >> > Hi, > > >> > I'm interested in printing out coloured lines of my > >> > application and > >> > I don't know what to use. Can anybody give me an idea?? > > >> You could speed up the process if you explain what your > >> application is and what you mean by colored lines. Does your > >> application emit output to a plotter, an ink-jet printer, or a > >> color laser printer? Is it a drawing program? An editor in > >> which you want lines colored to highlight context? It might be > >> useful to know what system you are running as well. Just a > >> little detail here. > > >> -- > >> rzed > > > Well, yes, it's a program that prints out lines to the standard > > output with a print command, and I want to print them coloured. > > For example: > > > print "Hello World!!" > > > I want it in red colour. > > > That's all. > > If you're on Linux, you could use the curses module. There may be > a precompiled Windows version compatible with your Python version, > or maybe not, but the Windows source is available, and you may be > able to get it to work with your Python with some effort. Linux > distros include curses, I think. For Windows curses, take a look > at . You will understand why > the phrase "Windows curses" is used, I expect. > > -- > rzed Yes, I'm on a Linux box. I've tried with the curses module, but I don't how I could fetch the current use of curses of my shell. I don't know if I'm talking about something impossible. I've made some tests with the curses module and works fine, but I need to capture the current window and change the attributes of texts. Carlos Niharra L?pez From bdesth.quelquechose at free.quelquepart.fr Mon Feb 19 16:27:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Feb 2007 22:27:18 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171850479.140864.210400@j27g2000cwj.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <1171850479.140864.210400@j27g2000cwj.googlegroups.com> Message-ID: <45da0eb2$0$31502$426a34cc@news.free.fr> olsongt at verizon.net a ?crit : > On Feb 16, 4:22 pm, ifti_cr... at yahoo.com wrote: > >>I am VB6 programmer and wants to start new programming language but i >>am unable to deciced. >> >>i have read about Python, Ruby and Visual C++. but i want to go >>through with GUI based programming language like VB.net >> >>so will you please guide me which GUI based language has worth with >>complete OOPS Characteristics >> >>will wait for the answer >> >>hope to have a right direction from you Programmer >> >>Regards >>Iftikhar >>itzon... at yahoo.com > > > Despite what "real programmers" and various apologists might say, > there isn't much out there that comes close to the ease-of-use and > functionality of VB when it comes to designing a GUI. Lol. From sjmachin at lexicon.net Tue Feb 6 17:36:14 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Feb 2007 14:36:14 -0800 Subject: Help reading binary data from files In-Reply-To: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> References: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> Message-ID: <1170801374.007817.8310@k78g2000cwa.googlegroups.com> On Feb 7, 9:01 am, "jeff" wrote: > I am stumped trying to read binary data from simple files. Here is a > code snippet, where I am trying to simply print little-endian encoded > data from files in a directory. > > for name in os.listdir(DOWNLOAD_DIR): > filename = s.path.join(DOWNLOAD_DIR, name) > if os.path.isfile(filename): > f = open(filename, 'rb') > while True: > ele = unpack(' print ele > > When the code runs, 0 is always the data printed, but the data files > are not all zero. > > Any quick tips? Looks to me like it should work -- at least until it hits the end of the first file. What do you expect to happen at the end of the first file?? Or did you so snippetise the code so that even if the missing import statements are added back, it still won't get into the 2nd file? I suggest a few more print statements, so that you can see what is happening. Try something like this (untested): f = open(filename, 'rb') print "Opened", filename while True: buff = f.read(2) if not buff: break # EOF if len(buff) == 1: print repr(buff), ord(buff) break ele = unpack(' I am creating an alternative mouse device(like wiimote), i use Xlib to move mouse, but now I need also to create the right and left click event, I can use already Xlib or there is another library that make it? It is possibile beacuse the wiimote code click also(I tryed to understand that code but it is too complicated!). From gerald.kaszuba at gmail.com Sat Feb 10 14:05:40 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 10 Feb 2007 11:05:40 -0800 Subject: pycallgraph 0.2.0 In-Reply-To: <5d727$45cdb6fb$d443bb3a$6935@news.speedlinq.nl> References: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> <5d727$45cdb6fb$d443bb3a$6935@news.speedlinq.nl> Message-ID: <1171134340.086570.217110@p10g2000cwp.googlegroups.com> On Feb 10, 11:14 pm, Stef Mientki wrote: > My first test was terrible: a file of 800kB was created, > Trying to view it, resulted in the following: > - Paint Shop Pro told me it was not a valid PNG file, > - Mozilla crashed after 5 minutes, > - GIMP gave me a preview after half an hour ;-) Impressive! :) > So a few suggestions: > - is there a way to limit the number of nodes ? Not yet, I will have a maximum stack-depth option in the next version. > - "pycallgraph." nodes are "non-information" > (maybe you can find another way to place your "signature" ;-) This should be fixed in the next version. > - how do I exclude modules/files/objects (sorry I'm still a newbie in Python) Say you want to only display your own modules called 'foo' and 'bar': import pycallgraph pycallgraph.settings['include_module'] = ['foo', bar] pycallgraph.start_trace() pycallgraph.make_graph('blah.png') >From the source there are these options for inclusion and exclusion: 'exclude_module': [], 'exclude_class': [], 'exclude_func': [], 'exclude_specific': ['stop_trace', 'make_graph'], 'include_module': [], 'include_class': [], 'include_func': [], 'include_specific': [], "specific" means the whole name of a node, e.g. "foo.MyBarClass.__init__" Gerald From harlinseritt at yahoo.com Wed Feb 21 19:10:48 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 21 Feb 2007 16:10:48 -0800 Subject: Convert to binary and convert back to strings In-Reply-To: References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <1172103048.160783.309470@l53g2000cwa.googlegroups.com> On Feb 21, 7:02 pm, "Colin J. Williams" wrote: > Harlin Seritt wrote: > > Hi... > > > I would like to take a string like 'supercalifragilisticexpialidocius' > > and write it to a file in binary forms -- this way a user cannot read > > the string in case they were try to open in something like ascii text > > editor. I'd also like to be able to read the binary formed data back > > into string format so that it shows the original value. Is there any > > way to do this in Python? > > > Thanks! > > > Harlin > > Try opening your file in the 'wb' mode. > > Colin W. Thanks for the help. I tried doing this: text = 'supercalifragilisticexpialidocius' open('sambleb.conf', 'wb').write(text) Afterwards, I was able to successfully open the file with a text editor and it showed: 'supercalifragilisticexpialidocius' I am hoping to have it show up some weird un-readable text. And then of course be able to convert it right back to a string. Is this even possible? Thanks, Harlin From http Tue Feb 6 18:35:58 2007 From: http (Paul Rubin) Date: 06 Feb 2007 15:35:58 -0800 Subject: Python does not play well with others References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> <1170796761.537999.224480@q2g2000cwa.googlegroups.com> <7xzm7rvuwo.fsf@ruckus.brouhaha.com> <1170804587.505119.230590@q2g2000cwa.googlegroups.com> Message-ID: <7xmz3qkgf5.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" writes: > It's possible that we could build it all in a startup module and then > pickle everything we've built into a file that each child would > unpickle, but I'm a bit leery about that approach. Yeah, that's not so great. You could look at POSH. From danb_83 at yahoo.com Thu Feb 1 19:54:50 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 1 Feb 2007 16:54:50 -0800 Subject: Calculating future dates In-Reply-To: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> References: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> Message-ID: <1170377690.176241.96590@p10g2000cwp.googlegroups.com> On Feb 1, 6:51 pm, "Toine" wrote: > Hello, > > I'm new to Python so please bare with me... > > I need to calculate a date that is exactly 31 days from the current > date in YYYY-MM-DD format. I know that date.today() returns the > current date, but how can I add 31 days to this result? I'm sure this > task is simple, but I haven't been able to figure it out. > > Thanks str(datetime.date.today() + datetime.timedelta(31)) From Uri.Nix at gmail.com Wed Feb 21 02:46:37 2007 From: Uri.Nix at gmail.com (Uri Nix) Date: 20 Feb 2007 23:46:37 -0800 Subject: ctypes and DLL exceptions Message-ID: <1172043996.966236.10980@h3g2000cwc.googlegroups.com> Hi all, Is there a method to deal with exceptions originating from a DLL creatively? After experimentation, I've observed that calling a ctypes wrapped DLL exception raises WindowsError, and an accompanying code. Does the code mean something? Can I throw an object from C++ and somehow catch it in Python? [Using Python 2.4 on Windows XP] Cheers, Uri From rschroev_nospam_ml at fastmail.fm Wed Feb 7 06:03:58 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 07 Feb 2007 11:03:58 GMT Subject: division by 7 efficiently ??? In-Reply-To: References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> <1170775779.707583.131420@k78g2000cwa.googlegroups.com> <1170806044.201254.289080@l53g2000cwa.googlegroups.com> <1170806724.447542.206120@m58g2000cwm.googlegroups.com> Message-ID: Roel Schroeven schreef: > garrickp at gmail.com schreef: >> I had considered this, but to halve, you need to divide by 2. Using >> random, while potentially increasing the number of iterations, removes >> the dependency of language tricks and division. > > It's possible to use Fibonacci numbers instead of halving each time; > that requires only addition and subtraction. Unfortunately I forgot > exactly how that works, and I don't have the time to look it up or to > try to reproduce it now. Maybe later. > > AFAIK that method is not commonly used since binary computers are very > good at dividing numbers by two, but it would be a good method on > ternary or decimal computers. Responding to myself since I found an explanation in the obvious place: http://en.wikipedia.org/wiki/Fibonacci_search_technique It is meant for search in ordered arrays though; I don't think it can be adapted for searching in mathematic intervals. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From miki.tebeka at gmail.com Tue Feb 20 15:32:04 2007 From: miki.tebeka at gmail.com (Miki) Date: 20 Feb 2007 12:32:04 -0800 Subject: question with inspect module In-Reply-To: <1171998273.748507.14070@h3g2000cwc.googlegroups.com> References: <1171998273.748507.14070@h3g2000cwc.googlegroups.com> Message-ID: <1172003524.934883.237070@v45g2000cwv.googlegroups.com> Hello, > I would like to retrieve all the classes, methods and functions of a > module. > I've used the inspect module for this, but inside a given class > (subclass of some other one), I wanted to retrieve only the methods > I've written, not the inherited one. How can I do ? class A: def a_method(self): pass def common_method(self): pass class B(A): def common_method(self): pass def b_method(self): pass import inspect from os.path import abspath lines, start_line = inspect.getsourcelines(B) end_line = start_line + len(lines) filename = abspath(inspect.getsourcefile(B)) for name in dir(B): method = getattr(B, name) if not callable(method): continue lnum = method.func_code.co_firstlineno fname = abspath(method.func_code.co_filename) if (lnum >= start_line) and (lnum <= end_line) and (fname == filename): print "%s is from B" % name HTH, -- Miki Tebeka http://pythonwise.blogspot.com From cvanarsdall at mvista.com Thu Feb 8 16:44:59 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 08 Feb 2007 13:44:59 -0800 Subject: multithreading concept In-Reply-To: <52vdp2F1qp2n6U2@mid.individual.net> References: <1170865166.423764.87050@s48g2000cws.googlegroups.com><1170872694.018720.301410@m58g2000cwm.googlegroups.com> <52vdp2F1qp2n6U2@mid.individual.net> Message-ID: <45CB99DB.1080102@mvista.com> Bjoern Schliessmann wrote: > [snip] > What makes you think that'll be faster? > > Remember: > - If you have one CPU, there is no parallelity at all. > - If you do have multiple CPUs but only one network device, there is > no parallel networking. > > Not necessarily, if he's on a full duplex ethernet connection, then there is some parallelity he can take advantage of. He has upstream and downstream. -c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From Bulkan at gmail.com Thu Feb 15 00:12:39 2007 From: Bulkan at gmail.com (placid) Date: 14 Feb 2007 21:12:39 -0800 Subject: Method overloading? In-Reply-To: <12t7qehj9jm0a21@corp.supernews.com> References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <12t7qehj9jm0a21@corp.supernews.com> Message-ID: <1171516359.202035.35020@q2g2000cwa.googlegroups.com> On Feb 15, 4:04 pm, Grant Edwards wrote: > On 2007-02-15, placid wrote: > > > > > Is it possible to be able to do the following in Python? > > > class Test: > > def __init__(self): > > pass > > > def puts(self, str): > > print str > > > def puts(self, str,str2): > > print str,str2 > > > if __name__ == "__main__": > > t = Test() > > t.puts("hi") > > t.puts("hi","hello") > > You tell us: what happened when you tried it? Well, when i run it i get this error "puts() takes exactly 3 arguments (2 given)" which means that the second a time i try to define the puts() method "overwrites" the first one > > And then what happens when you do this? > > class Test: > def __init__(self): > pass > > def puts(self, *args): > print ' '.join(args) > > if __name__ == "__main__": > t = Test() > t.puts("hi") > t.puts("hi","hello") but this isn't overloading. > > Now an exercise for the gentle reader: change the puts method > so that this call works: > > t.puts("hi",1,3.45) > > -- > Grant Edwards grante Yow! Yow! I'm imagining > at a surfer van filled with > visi.com soy sauce! From aboudouvas at panafonet.gr Thu Feb 1 05:13:01 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 1 Feb 2007 02:13:01 -0800 Subject: "Correct" db adapter In-Reply-To: <52c4fdF1o9fd9U1@mid.uni-berlin.de> References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> <1170262532.590048.247580@a75g2000cwd.googlegroups.com> <52c4fdF1o9fd9U1@mid.uni-berlin.de> Message-ID: <1170324781.762209.115060@p10g2000cwp.googlegroups.com> Ok, i see.. Thanks a lot all of you for the help. I know from my Win/.Net/Sql Server expertise that odbc put a layer in the mix. That's why, for example, in .Net we have a native SqlClient data provider that talks to Sql Server directly. But one of the reasons that i started learning Python, is to NOT to be tied-up again with ANY company or specific product again (i had enough MS addiction over these years...). So, based on this direction, i am using pyodbc, which is DB-API2 compliant and i suppose that the code i write this way, will have little changes to use another db in the future. I dig the net and found that there are several efforts for modules specific to some databases but some of them are incomplete, faded, or not db-api2 compliant. So, i will check mxOdbc and see if there is a reason to use it over pyodbc. From jth02 at arcor.de Wed Feb 7 16:23:29 2007 From: jth02 at arcor.de (Jens Theisen) Date: 07 Feb 2007 21:23:29 +0000 Subject: idea for testing tools Message-ID: <87ejp1mzla.fsf@arcor.de> Hello, I find it annoying that one has to write self.assertEqual(x, y) rather than just assert x == y when writing tests. This is a nuisance in all the programming languages I know of (which are not too many). In Python however, there appears to be a better alternative. The piece of code below gives the benefit of printing the violating values in case of a testing failure as well as the concise syntax: The snippet def test_test(): def foo(x): return x + 3 x = 1 y = 2 assert foo(x) < y + x try: test_test() except AssertionError: analyse() would give: Traceback (most recent call last): File "./ast-post.py", line 138, in ? test_test() File "./ast-post.py", line 134, in test_test assert foo(x) < y + x AssertionError failure analysis: foo: x: 1 ( x ): 1 foo ( x ): 4 y: 2 x: 1 y + x: 3 foo ( x ) < y + x: False The code that makes this possible relies only on code present in the standard library (being traceback, inspect and the parsing stuff) while being as short as: #!/usr/bin/python import sys, types import traceback, inspect import parser, symbol, token import StringIO def get_inner_frame(tb): while tb.tb_next: tb = tb.tb_next return tb.tb_frame def visit_ast(visitor, ast): sym = ast[0] vals = ast[1:] assert len(vals) > 0 is_simple = len(vals) == 1 is_leaf = is_simple and type(vals[0]) != types.TupleType if not is_leaf: visitor.enter() for val in vals: visit_ast(visitor, val) visitor.leave() if is_leaf: visitor.leaf(sym, vals[0]) elif is_simple: visitor.simple(sym, vals[0]) else: visitor.compound(sym, vals) class ast_visitor: def enter(self): pass def leave(self): pass def leaf(self, sym, val): pass def simple(self, sym, val): pass def compound(self, sym, vals): pass class simple_printer(ast_visitor): def __init__(self, stream): self.stream = stream def leaf(self, sym, val): print >>self.stream, val, def str_from_ast(ast): s = StringIO.StringIO() visit_ast(simple_printer(s), ast) return s.getvalue() class assertion_collector(ast_visitor): def __init__(self, statements): self.statements = statements def compound(self, sym, vals): if sym == symbol.assert_stmt: # two nodes: the "assert" name and the expression self.statements.append(vals[1]) class pretty_evaluate(ast_visitor): def __init__(self, globals_, locals_): self.globals = globals_ self.locals = locals_ def _expr(self, expression): code = compile(expression, '', 'eval') try: result = eval(code, self.globals, self.locals) except Exception, e: result = e print '%50s: %s' % (expression, str(result)) def compound(self, sym, vals): ast = [ sym ] ast.extend(vals) expression = str_from_ast(ast) self._expr(expression) def leaf(self, sym, val): if sym == token.NAME: self._expr(val) def analyse(): type_, exc, tb = sys.exc_info() frame = get_inner_frame(tb) try: filename, line, fun, context, index = ( inspect.getframeinfo(frame, 1) ) ast = parser.suite(context[0].lstrip()).totuple() assert_statements = [ ] visit_ast(assertion_collector(assert_statements), ast) traceback.print_exc() print "\nfailure analysis:\n" for statement in assert_statements: visit_ast( pretty_evaluate(frame.f_globals, frame.f_locals), statement) finally: del frame -- Cheers, Jens From cyberco at gmail.com Tue Feb 27 02:57:26 2007 From: cyberco at gmail.com (cyberco) Date: 26 Feb 2007 23:57:26 -0800 Subject: Tip: 'Open IPython here' in Windows context menu In-Reply-To: References: Message-ID: <1172563046.483509.248840@a75g2000cwd.googlegroups.com> Great! That really helps me, thanks. 2B From troy.melhase at gmail.com Sun Feb 25 05:34:02 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Sun, 25 Feb 2007 01:34:02 -0900 Subject: Find the first element that meets the condition In-Reply-To: <1172397176.024303.257890@t69g2000cwt.googlegroups.com> References: <1172397176.024303.257890@t69g2000cwt.googlegroups.com> Message-ID: > I have implemented it this way, may be, there should be a built in > hiding somewhere in the standard libraries? the itertools module might have what you're after. something similar to your example: >>> import itertools >>> r = iter(range(100)) >>> n = itertools.dropwhile(lambda x:x<=13, r) >>> n.next() 14 From bdesth.quelquechose at free.quelquepart.fr Mon Feb 19 16:16:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Feb 2007 22:16:35 +0100 Subject: Declare a variable global In-Reply-To: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> Message-ID: <45da0c30$0$24461$426a74cc@news.free.fr> yinglcs at gmail.com a ?crit : > Hi, > > I have the following code: > > colorIndex = 0; You don't need the ; > > def test(): > print colorIndex; Idem. > This won't work. Why ? Or more exactly : for which definition of "won't work" ? (hint: this code prints 0 on sys.stdout - I don't know what else you where expecting...) > But it works if i do this: > > colorIndex = 0; > > def test(): > global colorIndex; > print colorIndex; Have mercy : keep those ; out of here. > My question is why do I have to explicit declaring 'global' for > 'colorIndex'? Can't python automatically looks in the global scope > when i access 'colorIndex' in my function 'test()'? It does. You only need to declare a name global in a function if you intend to rebind the name in the function. From ask at me Tue Feb 20 19:12:42 2007 From: ask at me (alf) Date: Tue, 20 Feb 2007 18:12:42 -0600 Subject: converting u'11\xa022' to '11\xa022' Message-ID: Hi, is there a more elegant way to do that: ''.join([chr(ord(i)) for i in u'11\xa022' ]) -- thx, alf From gagsl-py at yahoo.com.ar Tue Feb 13 13:46:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 15:46:51 -0300 Subject: _ssl.pyd is buggy? References: <45D1F804.8050609@designaproduct.biz> Message-ID: En Tue, 13 Feb 2007 14:40:20 -0300, Laszlo Nagy escribi?: > I just installed Python 2.5 and now I do not get the error message in > the event log. But the service still cannot be stopped and does not log > anything. I'm using the logging module and RotatingFileHandler, so the > service should start logging into a new file immediately after startup. > According to the event log, the service is started, but it does nothing. > If I start the same program as an application, it works fine. The > program only uses the standard lib. Any ideas, what can be the problem? Services usually run under the LOCAL_SERVICE account, which is rather limited on what it is allowed to do (It has no access to network shares, by example). Perhaps this is afecting your program. -- Gabriel Genellina From hg at nospam.org Sun Feb 25 09:37:28 2007 From: hg at nospam.org (hg) Date: Sun, 25 Feb 2007 15:37:28 +0100 Subject: Help on object scope? References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> Message-ID: <0knEh.4753$3b5.1201@newsfe24.lga> bmaron2 at hotmail.com wrote: > Hello everybody, > > I have a (hopefully) simple question about scoping in python. I have a > program written as a package, with two files of interest. The two > files are /p.py and /lib/q.py > > My file p.py looks like this: > > --- > > from lib import q > > def main(): > global r > r = q.object1() > s = q.object2() > > if __name__ == "__main__": > main() > > --- > > My file q.py in the subdirectory lib looks like this: > > class object1: > t = 3 > > class object2: > print r.t > > --- > > Python gives me an error, saying it can't recognize global name r. > However I define r as global in the top-level main definition! Can > anyone suggest how I can get around this, if I want to define and bind > global names inside of main() which are valid in all sub-modules? > > Thanks very much for your help! Might be wrong, but globals can only be global to the module they're declared in. I suggest you find another way such as passing your object as a parameter hg From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 18:50:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 00:50:23 +0100 Subject: Object type check In-Reply-To: <1170885971.374044.181150@v45g2000cwv.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <45ca32ed$0$32232$426a74cc@news.free.fr> <1170879597.935278.240000@m58g2000cwm.googlegroups.com> <45ca4035$0$4321$426a74cc@news.free.fr> <1170885971.374044.181150@v45g2000cwv.googlegroups.com> Message-ID: <45ca5e99$0$23858$426a74cc@news.free.fr> king kikapu a ?crit : >>And so what ? Once an exception got caught, what are you going to do ? > > > You have absolutely right, that's the reason i rejected this. hear hear !-) ( snip) > All of the efforts all these years to declare everything correct, to > fight with the compiler (and to always have him win...), to ...[put > whatever here] and now Python...What can i say!... http://www.lesher.ws/choose_python.pdf From horpner at yahoo.com Mon Feb 12 18:34:32 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 12 Feb 2007 23:34:32 GMT Subject: Vim scripting with python References: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Message-ID: On 2007-02-12, J. Clifford Dyer wrote: > Stuart D. Gathman wrote: >> On Sat, 03 Feb 2007 05:02:54 -0800, Tool69 wrote: >> Use :py inside your vimrc - don't run python externally. > > Which versions of vim is this valid for? I tried ":py print > 'Hello'", and got "E319: Sorry, the command is not available in > this version" The latest Windows build has the Python bindings included. The one I have is version 7.0. Earlier Windows binaries didn't generally have it. -- Neil Cerutti From mikael at isy.liu.se Wed Feb 28 04:38:02 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 28 Feb 2007 10:38:02 +0100 Subject: newbie question(file-delete trailing comma) In-Reply-To: <495461.77638.qm@web7801.mail.in.yahoo.com> References: <495461.77638.qm@web7801.mail.in.yahoo.com> Message-ID: <45E54D7A.8060203@isy.liu.se> kavitha thankaian wrote: > my script writes a dictionary to a file.but i need only the values > from the dictionary which should be sepearted by a comma,,,so i did as > following: > [snip code that generates the incorrect original file] > when i execute the above code,my test.txt file has the following: > a,b,c,d, > now i need to delete the comma at the end,,,this is my problem,,, This is the first time you mention that you have control over the generation of the original file. Then I suggest that you fix the problem before generating the file. For instance, consider the following interactive session. >>> some={1:'a',2:7,3:'c',4:'d'} >>> some {1: 'a', 2: 7, 3: 'c', 4: 'd'} >>> some.values() ['a', 7, 'c', 'd'] >>> [str(x) for x in some.values()] ['a', '7', 'c', 'd'] >>> ','.join([str(x) for x in some.values()]) 'a,7,c,d' Then write that to your file instead. /MiO From Eric.Gabrielson at gmail.com Mon Feb 5 21:03:48 2007 From: Eric.Gabrielson at gmail.com (Eric.Gabrielson at gmail.com) Date: 5 Feb 2007 18:03:48 -0800 Subject: Coordinate Grid Points In-Reply-To: References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> Message-ID: <1170727428.120082.47690@a75g2000cwd.googlegroups.com> On Feb 5, 3:29 pm, James Stroud wrote: > Eric.Gabriel... at gmail.com wrote: > > Hello, > > I am very knew to python and am attempting to write a program > > in python that a friend of mine is having to write in java. I am doing > > this for fun and would like some help as to how i can generate random > > coordinate points (x,y) and compare them with user inputted coordinate > > points. For example how will I be able to access the separate values, > > the x from the x,y position. I think I understand everything except > > 1)the random coordinate points 2) the getting the users inputted x and > > y values in one line ("Please guess a coordinate point from (1,1) to > > (20,20): ") as opposed to ("Please enter an x value:" and "Please > > enter a y value") and finally 3) acessing the x value from the x,y > > coordinate function. the assignment description is located here http:// > >www.cs.washington.edu/education/courses/142/07wi/homework/ > > homework.html if you would like to see a more in depth discription of > > the game. > > > Many Thanks, > > Eric > > For 1: see the random module (e.g. random.randint) > For 2: see the "eval" function and "raw input" > For 2 (without cheating): see the re module. For example: > ***************************************************************************** > ***map(int, re.compile("\(?(\d+),(\d+)\)?").search(inpt).groups())**** > ***************************************************************************** > (Giving you the latter because eval will do this for you anyway.) > > Also see "raw_input". > > James Thank you very much for your response i will play around with the code when I have some time ( hopefully later tonight) but could you please breakdown what the part that I surrounded with asterisks, I think I recognize it but don't understand it. Eric From arnodel at googlemail.com Sun Feb 25 05:57:52 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 25 Feb 2007 02:57:52 -0800 Subject: finding out the precision of floats Message-ID: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> Hi all, I want to know the precision (number of significant digits) of a float in a platform-independent manner. I have scoured through the docs but I can't find anything about it! At the moment I use this terrible substitute: FLOAT_PREC = repr(1.0/3).count('3') How can I do this properly or where is relevant part of the docs? Thanks -- Arnaud From B.Ogryczak at gmail.com Wed Feb 21 06:20:37 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 21 Feb 2007 03:20:37 -0800 Subject: eval('000052') = 42? In-Reply-To: References: Message-ID: <1172056837.020473.125480@h3g2000cwc.googlegroups.com> On Feb 21, 5:09 am, Astan Chee wrote: > Hi, > I just tried to do > eval('00052') and it returned 42. > Is this a known bug in the eval function? Or have I missed the way eval > function works? It works just fine. Read up on integer literals. >>> 52 #decimal 52 >>> 052 #octal 42 >>> 0x52 #hexadecimal 82 From cjw at sympatico.ca Wed Feb 21 19:02:17 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 21 Feb 2007 19:02:17 -0500 Subject: Convert to binary and convert back to strings In-Reply-To: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <45DCDD89.70609@sympatico.ca> Harlin Seritt wrote: > Hi... > > I would like to take a string like 'supercalifragilisticexpialidocius' > and write it to a file in binary forms -- this way a user cannot read > the string in case they were try to open in something like ascii text > editor. I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is there any > way to do this in Python? > > Thanks! > > Harlin > Try opening your file in the 'wb' mode. Colin W. From rshepard at nospam.appl-ecosys.com Fri Feb 9 19:03:32 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 10 Feb 2007 00:03:32 GMT Subject: Matching Strings Message-ID: I'm not sure how to change a string so that it matches another one. My application (using wxPython and SQLite3 via pysqlite2) needs to compare a string selected from the database into a list of tuples with another string selected in a display widget. An extract of the relevant code is: selName = self.polTree.GetItemText(selID) ... for item in self.appData.polNat: print 'Item: ', item, '\n', 'selName: ', selName, '\n' if item == selName: print '***** ', self.appData.polNat[1] The last comparison and print statement never work because the strings are presented this way: Item: (u'ground water',) selName: ground water What do I need to do to 'Item' to strip the parentheses, unicode symbol, single quotes, and comma? Do I want 'raw' output? If so, how do I specify that in the line 'if item == selName:'? TIA, Rich From hipertracker at filtr.gmail.com Fri Feb 2 20:18:04 2007 From: hipertracker at filtr.gmail.com (Jaroslaw Zabiello) Date: Sat, 3 Feb 2007 01:18:04 +0000 Subject: What happened to SPE? References: Message-ID: <1l3xeojrs48dh.dlg@zabiello.com> Dnia 11 Jan 2007 17:02:49 +0100, Neil Cerutti napisa?(a): > SPE lost its web host, and last I heard is looking for a new > home. For now you can get it here: > > http://sourceforge.net/projects/spe/ That is old addres. Never is http://developer.berlios.de/projects/python/ -- Jaroslaw Zabiello http://blog.zabiello.com From zaz600 at gmail.com Mon Feb 5 19:32:23 2007 From: zaz600 at gmail.com (NoName) Date: 5 Feb 2007 16:32:23 -0800 Subject: Why? Message-ID: <1170721943.034518.223210@l53g2000cwa.googlegroups.com> # -*- coding: cp1251 -*- from glob import glob src= "C:\\0000\\????? ?????\\*.*" print glob(src) ['C:\\0000\\\xcd\xee\xe2\xe0\xff \xef\xe0\xef\xea\xe0\\ksdjfk.txt', 'C: \\0000\\\xcd\xee\xe2\xe0\xff \xef \xe0\xef\xea\xe0\\\xeb\xfb\xe2\xee\xe0\xeb\xee\xe0\xeb.txt'] Why not "C:\\0000\\????? ?????\\ksdjfk.txt" and etc? From edreamleo at charter.net Fri Feb 16 09:01:11 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 08:01:11 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: > Why won't it be possible to make 'print' in Python 3 that supports all > the functionality of the current print statement, and then translate to > that ? > I saw an assertion to the effect that it wasn't possible - but no proof. As discussed in the original post, the problem is the reverse: the Python 2.x print statement does not support the keyword args required by the pep, so that print(foo) **in Python 2.x** can not simulate the effect of the print statement with a trailing comma. Here is the theorum carefully stated and proved. Theorem: is not possible to define a function called print in Python 3.x such that A) print (whatever) is syntaxtically valid in Python 2.x and B) print(whatever) outputs what 'print whatever' outputs in Python 2.x for all values of 'whatever'. Proof: It is impossible for the print function to simulate the effect of the print statement with a trailing comma. Indeed, print ('line'), and print ('line',) (note the position of the commas) are valid in Python 2.x, but neither does what is wanted. And print('line',end='') is invalid in Python 2.x. Let's look at some examples: 1. The following works (prints 'line after\n') in Python 2.x, but will not suppress the newline in Python 3.x: print('line'), print('after') 2. The following doesn't work in Python 2.x. (It prints "('line',)\nafter"). print ('line',) print ('after') 3. print ('line',end='') produces a syntax error in Python 2.x: print ('line',end='') ^ SyntaxError: invalid syntax That's the proof. Can you find a flaw in it? Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From http Thu Feb 1 14:06:02 2007 From: http (Paul Rubin) Date: 01 Feb 2007 11:06:02 -0800 Subject: Question about a single underscore. References: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> <7xveilzpvs.fsf@ruckus.brouhaha.com> Message-ID: <7xy7nhk89x.fsf@ruckus.brouhaha.com> "Steven W. Orr" writes: > AttributeError: _const instance has no attribute '_const' > >>> > What am I missing here? (Sorry if it should be obvious) Oh I see. No it's not obvious. module "const" has gotten overwritten by the _const instance. I think that module author was too clever for his or her own good. From jura.grozni at gmail.com Fri Feb 9 01:37:22 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 22:37:22 -0800 Subject: Is Python for me? In-Reply-To: References: Message-ID: <1171003042.853235.210090@k78g2000cwa.googlegroups.com> i hope you know that for this task, if you want it to be successfull, you need a really big database. it sounds very simple to this. it sounds like go through all possible permutations. before you start writing any code take a pencil and a big paper and do some maths. i sugesst you read and practise this for about a year about data structures, algorithms and graph theory (just for the begining). Then take a look on data mining and then incpect the era model so you can design a good database. Tic Tac Toe is a much easier problem and there are a lot of possible different games (9*8*7*6*5*4*3*2*1=362 880 i dont consider the rotations). it's true that you learn best by solving a problem, but if stoped on basic on higjschool, then you will need a lot of time to solve this problem. If you remember basic than you should learn python according to basic's possibillities in maximum a month. depending on talent and spare time. i sugesst you take some a "a little bit" easier problem to learn python. For this speciffic problem it shold be good to learn on other games. I started about 7 years ago on tic tac toe and then with reversi. You are from USA? I come from a differtent continent so i don't know what you learn in schools. But if you didn't learn it, take a look on statistics. very usefull. you should at least know what specific terms mean althought python has them in the numpy module. don't be afraid of all that i said. keep learning and it will pay off. at the end when you crack the poker machine :-) that's the life of a geek. learn , learn, learn and one day comes the jackpot. -------------------------------------------------------------- and no, I am not a junkee, I'm addicted to Python From aboudouvas at panafonet.gr Wed Feb 7 15:19:57 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 7 Feb 2007 12:19:57 -0800 Subject: Object type check In-Reply-To: <45ca32ed$0$32232$426a74cc@news.free.fr> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <45ca32ed$0$32232$426a74cc@news.free.fr> Message-ID: <1170879597.935278.240000@m58g2000cwm.googlegroups.com> at first, thanks you all for your help! So, i will follow your advice.In a moment though, i thought that "ok, do not check anything of the parameter's type but do a try/catch at the calls inside the function" But this way, i would rather defeat the purpose because i have to try/ catch in *every* call inside the func. So, i suppose that i wouldn't want to do that and just try to make the call in whatever they passed me in. Strange world the dynamic one.... From john.hsu at sovereign.co.nz Mon Feb 26 21:00:00 2007 From: john.hsu at sovereign.co.nz (JH) Date: 26 Feb 2007 18:00:00 -0800 Subject: Is type object an instance or class? Message-ID: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a instance is created by "calling" a class object. A object should not be both a class and an instance at the same time. Further I found out there is a special type call "type" that is a subclass of base type "object". All other types are instances of this type. Even base type "object" is an instance of this special type. What is role of this type "type" in object creation? Could someone there straighten this concept a little? For example (Python2.5): >>> issubclass(int, object) True >>> isinstance(int, object) True >>> print type(int) >>> isinstance(int, type) True >>> issubclass(int, type) False >>> issubclass(type, object) True >>> isinstance(type, object) True >>> isinstance(object, type) True >>> From aleaxit at gmail.com Sun Feb 25 14:48:30 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 25 Feb 2007 11:48:30 -0800 Subject: Rational numbers In-Reply-To: References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> Message-ID: <1172432910.457442.232480@s48g2000cws.googlegroups.com> On Feb 24, 12:25 am, Toby A Inkster wrote: > aleaxit wrote: > > If anybody who has easy access to Microsoft's MSVC++.NET (and is willing > > to try building GMP 4.2 with/for it), or a PPC Mac with XCode installed > > (possibly with MacOSX 10.3...) > > I'm writing this message on a MacOS 10.3.9 box with Xcode 1.5 (gcc 3.3) > installed. If you tell me how, I'd be happy to compile it for you. > > Contact me through the feedback form on the site below. Thanks, but unfortunately getting GMP 4.2 built right on any platform is never a trivial task -- GMP's maintainer is apparently actively hostile to any attempts of making fixes to GMP to make it build correctly on MAC OS X, in particular. I have a correspondent who thinks he's got a working patch (for PPC on MacOSX 10.4, at least); he's very busy but I hope he'll send it to me eventually. gmpy itself is or should be pretty trivial to build on any platform (and I'll always happily accept any fixes that make it better on any specific platform, since it's easy to make them conditional so they'll apply to that platform only), but the underlying GMP is anything but:- (. Alex From eopadoan at altavix.com Fri Feb 2 06:32:44 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 2 Feb 2007 09:32:44 -0200 Subject: Inconsistent list/pointer problem In-Reply-To: References: <45c31e25$0$31426$426a74cc@news.free.fr> Message-ID: > Won't do for the OP's needs - he wants to modify the objects contained > in listB without impacting the ones in listA (or at least that's what I > understand). Sorry. That is true - the items referenced on the [:] copy are the same as in the original. Rereading what the OP msg, I think we agree. From gibo at gentlemail.com Mon Feb 19 20:30:59 2007 From: gibo at gentlemail.com (GiBo) Date: Tue, 20 Feb 2007 14:30:59 +1300 Subject: New-style classes (was Re: Checking for EOF in stream) In-Reply-To: <45DA39B0.7020403@gentlemail.com> References: <45DA39B0.7020403@gentlemail.com> Message-ID: <45DA4F53.90505@gentlemail.com> GiBo wrote: > Hi! > > Classic situation - I have to process an input stream of unknown length > until a I reach its end (EOF, End Of File). How do I check for EOF? > [...] > I'd better like something like: > > while not stream.eof(): > ... Is there a reason why some classes distributed with Python 2.5 are not new-style classes? For instance StringIO is apparently "old-style" class i.e. not inherited from "object". Can I somehow turn an existing old-style class to a new-style one? I tried for example: class MyStreamIO(StreamIO, object): pass but got an error. Is my only chance taking StringIO.py from python tree, adding "(object)" to the class declaration and distributing it with my source? FWIW I created a wrapper class that does what I need with the EOF problem in quite elegant way, but due to __getattribute__() stuff it only works with new-style classes :-( class MyStreamer(object): def __init__(self, stream): self._stream = stream self.eof = False def read(self, amount = None): data = self._stream.read(amount) if len(data) == 0: self.eof = True raise EOFError return data def __getattribute__(self, attribute): try: return object.__getattribute__(self, attribute) except AttributeError: pass return self._stream.__getattribute__(attribute) GiBo From gagsl-py at yahoo.com.ar Sun Feb 18 16:47:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Feb 2007 18:47:57 -0300 Subject: string.find returns -1 when string evidently in source file References: <3bb44c6e0702180204p4d2ddd93s61c46eecc125377f@mail.gmail.com> Message-ID: En Sun, 18 Feb 2007 07:04:27 -0300, bryan rasmussen escribi?: > the following is returning -1: > > x = open("latvian.txt",'r') > x1 = x.read() > print x1.find("LAYOUT") > the encoding of the file is Unicode, I am able to return instances of > individual characters but not whole words. "Unicode" can't be the encoding. It's better to convert from bytes to unicode objects just after reading, and then work on Unicode always. x = open("latvian.txt",'r') x1 = x.read().decode() # or .decode("utf8") or the right encoding for the file print type(x1) # should print x1.find(u"LAYOUT") -- Gabriel Genellina From bruno.desthuilliers at gmail.com Tue Feb 27 11:34:15 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 27 Feb 2007 08:34:15 -0800 Subject: Python, Embedded linux and web development In-Reply-To: <1172579243.995924.87580@m58g2000cwm.googlegroups.com> References: <1172578332.957236.247800@8g2000cwh.googlegroups.com> <1172579243.995924.87580@m58g2000cwm.googlegroups.com> Message-ID: <1172594055.316966.257270@a75g2000cwd.googlegroups.com> On 27 f?v, 13:27, "Paul Boddie" wrote: > On 27 Feb, 13:12, "Tzury" wrote: > > > > > c) small web application that will be used as front end to configure > > the system (flat files and sqlite3 db are the back-end). > > > Our platform is base on the Intel PXA270 processor (XSCALE family, > > which is ARM compatible) running at 312MHz. > > You might want to read this article which got mentioned fairly > recently either on comp.lang.python or on some blog or other: > > http://www.linuxdevices.com/articles/AT5550934609.html > Don't know for sure if it's relevant, but this might be of interest too: http://william-os4y.livejournal.com/2924.html From bignose+hates-spam at benfinney.id.au Thu Feb 1 22:56:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 14:56:51 +1100 Subject: Python does not play well with others References: Message-ID: <87fy9pus8s.fsf@benfinney.id.au> John Nagle writes: > Python is the only major open source project I've encountered where > there's so much hostility to bug reports. Bear in mind that if you send a message only to this mailing list, that's not a bug report. That's a discussion, which may be worth having, but not one you can reasonably expect to result in a fix for a bug. A bug report should be sent to the bug tracker for the software against which you're reporting a bug. Only at that point does it become something on which you can comment about attitude toward bug reports, because before that point the bug report doesn't exist in a useful form. > For a while, I tried submitting long, detailed bug reports showing > where in the C code a problem lies, and pointing out ways to fix it. That's great. I hope your attention to detail was well received. > But I don't want to take over maintenance on the SSL package; it's > too delicate. That's fair enough. But if no-one maintains it to your satisfaction, you do get what you pay for. If it's important to you, it should be worth an investment of *some* kind from you, to ensure it is maintained. -- \ "The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing." -- Steven Wright | _o__) | Ben Finney From sjmachin at lexicon.net Sat Feb 10 20:13:38 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 Feb 2007 17:13:38 -0800 Subject: Regular Expressions In-Reply-To: References: Message-ID: <1171156418.267223.318460@v45g2000cwv.googlegroups.com> On Feb 11, 10:26 am, "Geoff Hill" wrote: > What's the way to go about learning Python's regular expressions? I feel > like such an idiot - being so strong in a programming language but knowing > nothing about RE. I suggest that you work through the re HOWTO http://www.amk.ca/python/howto/regex/ and by work through, I don't mean "read". I mean as each new concept is introduced: 1. try the given example(s) yourself at the interactive prompt 2. try variations on the examples 3. read the relevant part of the Library Reference Manual Also I'd suggest reading threads in this newsgroup where people are asking for help with re. HTH, John From mhellwig at xs4all.nl Wed Feb 14 12:01:48 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 14 Feb 2007 18:01:48 +0100 Subject: rot13 in a more Pythonic style? In-Reply-To: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: <45d3403a$0$337$e4fe514c@news.xs4all.nl> Andy Dingley wrote: > I'm trying to write rot13, but to do it in a better and more Pythonic > style than I'm currrently using. What would you reckon to the > following pretty ugly thing? How would you improve it? In > particular, I don't like the way a three-way selection is done by > nesting two binary selections. Also I dislike stating the same > algorithm twice, but can't see how to parameterise them neatly. > > Yes, I know of .encode() and .translate(). > No, I don't actually need rot13 itself, it's just a convenient > substitute example for the real job-specific task. > No, I don't have to do it with lambdas, but it would be nice if the > final function was a lambda. > > > #!/bin/python > import string > > lc_rot13 = lambda c : (chr((ord(c) - ord('a') + 13) % 26 + ord('a'))) > > uc_rot13 = lambda c : (chr((ord(c) - ord('A') + 13) % 26 + ord('A'))) > > c_rot13 = lambda c : (((c, uc_rot13(c)) [c in > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']), lc_rot13(c) )[c in > 'abcdefghijklmnopqrstuvwxyz'] > > rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'') > > > print rot13( 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' ) > Well first of all, for me (personal) being Pythonic means that I should separate the logic and variables, in this case there is the rotation mechanism and the variable with the amount it should rotate. Then of course the letters case is something I consider as a state of the letter itself, the meaning of the letter doesn't change. And being a sucker for dictionaries I use them a lot So with that in mind I would write a class like this: ### class Rot(object): def __init__(self,amount = 13): self.__alpha = 'abcdefghijklmnopqrstuvwxyz' self.__amount = amount self.__index_string = dict() self.__crypt_index_string = dict() self.__string_index = dict() self.__crypt_string_index = dict() self.__position = 0 self.__create_dicts() def __cypher(self,number): alpha_len = len(self.__alpha) rotation_overflow = alpha_len - self.__amount new_number = None if number > rotation_overflow: new_number = number - self.__amount else: new_number = self.__position + self.__amount return(new_number) def __create_dicts(self): for letter in self.__alpha: self.__position += 1 self.__index_string[self.__position] = letter self.__crypt_index_string[self.__cypher(self.__position)] = letter self.__string_index[letter] = self.__position self.__crypt_string_index[letter] = self.__cypher(self.__position) def encrypt(self,text): text_list = list() letter_capital = None for letter in text: letter_capital = letter.isupper() letter = letter.lower() if letter not in self.__alpha: text_list.append(letter) else: position_plain = self.__string_index[letter] letter_crypt = self.__crypt_index_string[position_plain] if letter_capital: letter_crypt = letter_crypt.upper() text_list.append(letter_crypt) return("".join(text_list)) def decrypt(self,text): text_list = list() letter_capital = None for letter in text: letter_capital = letter.isupper() letter = letter.lower() if letter not in self.__alpha: text_list.append(letter) else: position_crypt = self.__crypt_string_index[letter] letter_plain = self.__index_string[position_crypt] if letter_capital: letter_plain = letter_plain.upper() text_list.append(letter_plain) return("".join(text_list)) ### Testing if it works: >>> rot13.decrypt(rot13.encrypt("This is a TEST")) 'This is a TEST' -- mph From stumblecrab at gmail.com Wed Feb 7 09:33:52 2007 From: stumblecrab at gmail.com (stumblecrab) Date: 7 Feb 2007 06:33:52 -0800 Subject: wxPython running other applications or console Message-ID: <1170858831.994649.239320@v33g2000cwv.googlegroups.com> Is it possible to run another application like vim or a terminal window from within a wxPython frame? From SoutoJohn at gmail.com Sat Feb 3 18:22:38 2007 From: SoutoJohn at gmail.com (SoutoJohn at gmail.com) Date: 3 Feb 2007 15:22:38 -0800 Subject: CTypes In-Reply-To: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> References: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> Message-ID: <1170544958.865802.120010@s48g2000cws.googlegroups.com> I forgot to mention I am running Windows 98SE. From andrewfelch at gmail.com Tue Feb 27 14:41:11 2007 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 27 Feb 2007 11:41:11 -0800 Subject: Automatic reloading, metaclasses, and pickle Message-ID: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> Hello all, I'm using the metaclass trick for automatic reloading of class member functions, found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 My problem is that if I 1) pickle an object that inherits from "AutoReloader" 2) unpickle the object 3) modify one of the pickled' object's derived class methods 4) reload the module holding the class ... then the changes don't affect the unpickled object. If I unpickle the object again, of course the changes take effect. My friend that loves Smalltalk is laughing at me. I thought I had the upperhand when I discovered the metaclasses but now I am not sure what to do. I really don't want to have to unpickle again, I'm processing video and it can take a long time. By the way, I used to avoid all of these problems by never making classes, and always building complex structures of lists, dictionaries, and tuples with global functions. It's going to take me a while to kick those horrible habits (during my transition, I'm deriving from list, dict, etc. hehe), perhaps a link to the metaclass trick is in order in the tutorial's comments on reload? Any help that avoids having to unpickle again is appreciated! Thanks, Andrew Felch From robin at NOSPAMreportlab.com Sat Feb 3 07:02:50 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 03 Feb 2007 12:02:50 +0000 Subject: Python 2.5 Quick Reference In-Reply-To: References: Message-ID: <45C479EA.20908@jessikat.plus.net> Dick Moores wrote: > > Is this reliable? (Looks good to me, but...) > ..... I really like these for a good overview -- Robin Becker From pDOTpagel at gsf.de Fri Feb 9 07:38:08 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Fri, 9 Feb 2007 12:38:08 +0000 (UTC) Subject: os.popen and broken pipes References: <1171020973.891832.166420@j27g2000cwj.googlegroups.com> Message-ID: Chris wrote: > It could easily be the 2gig file size limitation, how large are the > extracts? The files are much smaller than that, so that's not the issue. Anyway, Antoon pointed me in the right direction. Thanks for the help Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From http Sat Feb 10 18:30:04 2007 From: http (Paul Rubin) Date: 10 Feb 2007 15:30:04 -0800 Subject: Regular Expressions References: Message-ID: <7xfy9da8w3.fsf@ruckus.brouhaha.com> "Geoff Hill" writes: > What's the way to go about learning Python's regular expressions? I feel > like such an idiot - being so strong in a programming language but knowing > nothing about RE. Read the documentation? From richard at commonground.com.au Wed Feb 14 23:08:14 2007 From: richard at commonground.com.au (Richard Jones) Date: Thu, 15 Feb 2007 15:08:14 +1100 Subject: Roundup Issue Tracker release 1.3.3 Message-ID: <1901474C-A5E3-4AEC-BEAE-97D6FC33CE5A@commonground.com.au> I'm proud to release version 1.3.3 of Roundup. Fixed in 1.3.3: - If-Modified-Since handling was broken - Updated documentation for customising hard-coded searches in page.html - Updated Windows installation docs (thanks Bo Berglund) - Handle rounding of seconds generating invalid date values - Handle 8-bit untranslateable messages from database properties - Fix scripts/roundup-reminder date calculation (sf bug 1649979) - Improved due_date and timelog customisation docs (sf bug 1625124) New Features in 1.3.0: - WSGI support via roundup.cgi.wsgi_handler If you're upgrading from an older version of Roundup you *must* follow the "Software Upgrade" guidelines given in the maintenance documentation. Roundup requires python 2.3 or later for correct operation. To give Roundup a try, just download (see below), unpack and run:: roundup-demo Release info and download page: http://cheeseshop.python.org/pypi/roundup Source and documentation is available at the website: http://roundup.sourceforge.net/ Mailing lists - the place to ask questions: http://sourceforge.net/mail/?group_id=31577 About Roundup ============= Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces. It is based on the winning design from Ka-Ping Yee in the Software Carpentry "Track" design competition. Note: Ping is not responsible for this project. The contact for this project is richard at users.sourceforge.net. Roundup manages a number of issues (with flexible properties such as "description", "priority", and so on) and provides the ability to: (a) submit new issues, (b) find and edit existing issues, and (c) discuss issues with other participants. The system will facilitate communication among the participants by managing discussions and notifying interested parties when issues are edited. One of the major design goals for Roundup that it be simple to get going. Roundup is therefore usable "out of the box" with any python 2.3+ installation. It doesn't even need to be "installed" to be operational, though a disutils-based install script is provided. It comes with two issue tracker templates (a classic bug/feature tracker and a minimal skeleton) and five database back-ends (anydbm, sqlite, metakit, mysql and postgresql). From emami at knmi.nl Tue Feb 27 10:34:52 2007 From: emami at knmi.nl (Nader Emami) Date: Tue, 27 Feb 2007 16:34:52 +0100 Subject: installing "pysqlite" In-Reply-To: <1172588999.749895.3310@j27g2000cwj.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <1172579710.514139.103170@s48g2000cws.googlegroups.com> <1172588999.749895.3310@j27g2000cwj.googlegroups.com> Message-ID: <4670c$45e44f9d$9117fe9b$29410@news1.tudelft.nl> Paul Boddie wrote: > On 27 Feb, 13:35, "Nader" wrote: >> Thank for your reaction. I don't know also how the interaction sith >> 'easy_install' is. I think that I have to install 'pysqlite' from >> source code also, because i can change ther the 'setup.cfg' file and I >> can give there where the 'libsqlie3' is. > > What I did was to go to the pysqlite site (http://www.initd.org/ > tracker/pysqlite/wiki/pysqlite), download the sources for the latest > version, then change the setup.cfg file so that include_dirs refers to > the place where the SQLite headers (eg. sqlite.h) were installed, and > that library_dirs refers to the place where the SQLite libraries were > installed. For example: > > include_dirs=/opt/sqlite/usr/include > library_dirs=/opt/sqlite/usr/lib > > (You'd get the above if you configured SQLite to install into /opt/ > sqlite/usr.) > > Then, just do the usual build: > > python setup.py build > > And install with a prefix: > > python setup.py install --prefix=/opt/pysqlite/usr > > Since you seem to be installing things in non-root-controlled places, > I imagine you're familiar with specifying things like the --prefix > above, as well as setting up your PYTHONPATH afterwards. > > Paul > I have first installed "sqlite" and then I have configure the "setup.cfg" file of "pysqlite" package. I had to do two things in 'pysqlite' directory: 1- python setup.py build 2- python setup.py install It has done without any error. I suppose that the installation is well done, but I haven't yet test whether I can import the 'pysqlite' module in python. But how you mean about "PYTHONPATH"? If I do "echo $PYTHONPAT" i get an empty string. That meant that I don't have any "PYTHONPATH". How can I assign a correct "path" to this variable? Nader From gnewsg at gmail.com Wed Feb 14 08:39:56 2007 From: gnewsg at gmail.com (billie) Date: 14 Feb 2007 05:39:56 -0800 Subject: WindowsNT user authentication In-Reply-To: References: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> <1171294708.261232.18290@p10g2000cwp.googlegroups.com> <1171357845.968797.229580@m58g2000cwm.googlegroups.com> <1171458314.065280.164360@v33g2000cwv.googlegroups.com> <45D30C5D.7040207@timgolden.me.uk> Message-ID: <1171460396.160429.230060@a75g2000cwd.googlegroups.com> On 14 Feb, 14:30, Tim Golden wrote: > Tim Golden wrote: > > billie wrote: > >> Another question, I'm sorry. > >> Do you got any idea about how to get permissions of a file/directory > >> given the username? > >> For example: I would like to know if C:\my_file.ext is readable/ > >> writable by user 'x' or not. > > > This is an unfortunately messy question. > > I'm sorry; that probably came out wrong. What I meant > was that, although the question was perfectly intelligible, > the answer is going to be more complex than you probably > expected ;) > > TJG No problem about that. ;) I'll try to check demos folder then let you know something about it. Thanks again. From sjdevnull at yahoo.com Tue Feb 6 18:29:47 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 6 Feb 2007 15:29:47 -0800 Subject: Python does not play well with others In-Reply-To: <7xzm7rvuwo.fsf@ruckus.brouhaha.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> <1170796761.537999.224480@q2g2000cwa.googlegroups.com> <7xzm7rvuwo.fsf@ruckus.brouhaha.com> Message-ID: <1170804587.505119.230590@q2g2000cwa.googlegroups.com> On Feb 6, 4:27 pm, Paul Rubin wrote: > "sjdevn... at yahoo.com" writes: > > In our case, the issue is this: we load a ton of info at server > > restart, from the database. Some of it gets processed a bit based on > > configuration files and so forth. If this were done in my own C > > server, I'd do all of that and set up the (read-only) runtime data > > structures prior to forking. That would mean that: > > a) The processing time would be lower since you're just doing the pre- > > processing once; and > > b) The memory footprint could be lower if large data structures were > > created prior to fork; they'd be in shared copy-on-write pages. > > If you completely control the server, write an apache module that > dumps this data into a file on startup, then mmap it into your Python app. The final data after loading is in the form of a bunch of python objects in a number of complex data structures, so that's not really a good solution as far as I can tell. We read in a bunch of data from the database and build a data layer describing all the various classes (and some kinds of global configuration data, etc) used by the various applications in the system. It's possible that we could build it all in a startup module and then pickle everything we've built into a file that each child would unpickle, but I'm a bit leery about that approach. From arkanes at gmail.com Tue Feb 27 17:04:51 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 27 Feb 2007 16:04:51 -0600 Subject: boolean flag vs threading.Event In-Reply-To: <1172612232.442199.29720@s48g2000cws.googlegroups.com> References: <1172612232.442199.29720@s48g2000cws.googlegroups.com> Message-ID: <4866bea60702271404y4a77f80h8574b4cca0e8bd32@mail.gmail.com> On 27 Feb 2007 13:37:12 -0800, Daniel wrote: > I have a class similar to this: > > > class MyThread(threading.Thread): > > def __init__(self): > self.terminated = False > > def run(self): > while not self.terminated: > pass # do stuff here > > def join(self): > self.terminated = True > threading.Thread.join(self) > > > Recently I was reading in the Python Cookbook (9.2 Terminating a > Thread) about how to do this sort of thing. That recipe uses a > threading.Event object to signal the thread termination. Here's my > class recoded to use an event: > > > class MyThread(threading.Thread): > > def __init__(self): > self.event = threading.Event() > > def run(self): > while not self.event.isSet(): > pass # do stuff here > > def join(self): > self.event.set() > threading.Thread.join(self) > > > If I understand the GIL correctly, it synchronizes all access to > Python data structures (such as my boolean 'terminated' flag). If that > is the case, why bother using threading.Event for this purpose? > The GIL is an implementation detail and relying on it to synchronize things for you isn't futureproof. You're likely to have lots of warning, but using threading.Event() isn't any harder, and it's more correct and safer in the long term. There's a whole bunch of other cases where you might want to use an event, too. For example, you can have a single event which signals multiple threads to stop, and you can wait on a thread without busy looping. If you don't care about doing any of those things, and you're confident in relying on undocumented features of the GIL to protect you, and you'll never port your code to a different Python implementation, then I guess you can go ahead and use the boolean. But what are you gaining, really? From cfbolz at gmx.de Sat Feb 17 14:10:13 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sat, 17 Feb 2007 20:10:13 +0100 Subject: PyPy 0.99 released Message-ID: ====================================================================== pypy-0.99.0: new object spaces, optimizations, configuration ... ====================================================================== Welcome to the PyPy 0.99.0 release - a major snapshot and milestone of the last 8 months of work and contributions since PyPy-0.9.0 came out in June 2006! Main entry point for getting-started/download and documentation: http://codespeak.net/pypy/dist/pypy/doc/index.html Further below you'll find some notes about PyPy, the 0.99.0 highlights and our aims for PyPy 1.0. have fun, the PyPy team, Samuele Pedroni, Carl Friedrich Bolz, Armin Rigo, Michael Hudson, Maciej Fijalkowski, Anders Chrigstroem, Holger Krekel, Guido Wesdorp and many others: http://codespeak.net/pypy/dist/pypy/doc/contributor.html What is PyPy? ================================ Technically, PyPy is both a Python Interpreter implementation and an advanced Compiler, actually a framework for implementing dynamic languages and generating virtual machines for them. The Framework allows for alternative frontends and for alternative backends, currently C, LLVM and .NET. For our main target "C", we can can "mix in" different Garbage Collectors and threading models, including micro-threads aka "Stackless". The inherent complexity that arises from this ambitious approach is mostly kept away from the Python interpreter implementation, our main frontend. Socially, PyPy is a collaborative effort of many individuals working together in a distributed and sprint-driven way since 2003. PyPy would not have gotten as far without the coding, feedback and general support from numerous people. Formally, many of the current developers are involved in executing an EU contract with the goal of exploring and researching new approaches to Language/Compiler development and software engineering. This contract's duration is about to end March 2007 and we are working and preparing the according final review which is scheduled for May 2007. Key 0.99.0 Features ===================== * new object spaces: - Tainting: a 270-line proxy object space tracking and boxing sensitive information within an application. A tainted object is completely barred from crossing an I/O barrier, such as writing to files, databases or sockets. This allows to significantly reduce the effort of e.g. security reviews to the few places where objects are "declassified" in order to send information across I/O barriers. - Transparent proxies: allow to customize both application and builtin objects from application level code. Works as an addition to the Standard Object Space (and is translatable). For details see http://codespeak.net/pypy/dist/pypy/doc/proxy.html * optimizations: - Experimental new optimized implementations for various built in Python types (strings, dicts, lists) - Optimized builtin lookups to not require any dictionary lookups if the builtin is not shadowed by a name in the global dictionary. - Improved inlining (now also working for higher level backends) and malloc removal. - twice the speed of the 0.9 release, overall 2-3 slower than CPython * High level backends: - It is now possible to translate the PyPy interpreter to run on the .NET platform, which gives a very compliant (but somewhat slow) Python interpreter. - the JavaScript backend has evolved to a point where it can be used to write AJAX web applications with it. This is still an experimental technique, though. For demo applications see: http://play1.codespeak.net:8008/ * new configuration system: There is a new comprehensive configuration system that allows fine-grained configuration of the PyPy standard interpreter and the translation process. * new and improved modules: Since the last release, the signal, mmap, bz2 and fcntl standard library modules have been implemented for PyPy. The socket, _sre and os modules have been greatly improved. In addition we added a the pypymagic module that contains PyPy-specific functionality. * improved file implementation: Our file implementation was ported to RPython and is therefore faster (and not based on libc). * The stability of stackless features was greatly improved. For more details see: http://codespeak.net/pypy/dist/pypy/doc/stackless.html * RPython library: The release contains our emerging RPython library that tries to make programming in RPython more pleasant. It contains an experimental parser generator framework. For more details see: http://codespeak.net/pypy/dist/pypy/doc/rlib.html * improved documentation: - extended documentation about stackless features: http://codespeak.net/pypy/dist/pypy/doc/stackless.html - PyPy video documentation: eight hours of talks, interviews and features: http://codespeak.net/pypy/dist/pypy/doc/video-index.html - technical reports about various aspects of PyPy: http://codespeak.net/pypy/dist/pypy/doc/index-report.html The entry point to all our documentation is: http://codespeak.net/pypy/dist/pypy/doc/index.html What about 1.0? ====================== In the last week leading up to the release, we decided to go for tagging the release as 0.99.0, mainly because we have some efforts pending to integrate and complete research and coding work: * the JIT Compiler Generator is ready, but not fully integrated with the PyPy interpreter. As a result, the JIT does not give actual speed improvements yet, so we chose to leave it out of the 0.99 release: the result doesn't meet yet the speed expectations that we set for ourselves - and which some blogs and people have chosen as the main criterium for looking at PyPy. * the extension enabling runtime changes of the Python grammar is not yet integrated. This will be used to provide Aspect-Oriented Programming extensions and Design by Contract facilities in PyPy. * the Logic object space, which provides Logic Variables in PyPy, needs to undergo a bit more testing. A constraint problem solver extension module is ready, and needs to be integrated with the codebase. PyPy 0.99 is the start for getting to 1.0 end of March 2007, which we intend to become a base for a longer (and more relaxed :) time to come. Funding partners and organisations ===================================================== PyPy development and activities happen as an open source project and with the support of a consortium partially funded by a 28 months European Union IST research grant. The full partners of that consortium are: Heinrich-Heine University (Germany), Open End (Sweden) merlinux GmbH (Germany), tismerysoft GmbH (Germany) Logilab Paris (France), DFKI GmbH (Germany) ChangeMaker (Sweden), Impara (Germany) From piet at cs.uu.nl Thu Feb 22 08:19:48 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 22 Feb 2007 14:19:48 +0100 Subject: Local class variables? (mod_python problem) References: Message-ID: >>>>> Rory Campbell-Lange (RC) wrote: >RC> We have a set of classes using static methods to retain reference >RC> variables between operations. The problem is that the static variables >RC> are not reset between operations when used through mod_python. >RC> Although it is possible to reset the class variables between invocations >RC> of the system, this has the potential of 'wiping out' these variables >RC> when another user is using the system. >RC> Is there a way of getting the equivalent of 'local class variables'? In >RC> other words, a way of making 'print a' and 'print b' below provide the >RC> same output? There are several errors in your python code: quite a number of comma's have to be replaced by semicolons (or newlines), and there is a spurious comma. And a and b already print out the same, so it is not clear what you want. Do you mean that the x and y of the a and b object should be independent? In that case you should not use static variables but instance variables. If they have to survive across different HTTP requests you should use sessions. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From gonzlobo at gmail.com Sat Feb 3 14:43:58 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Sat, 3 Feb 2007 12:43:58 -0700 Subject: Decimating Excel files Message-ID: No, I don't want to destroy them (funny how the word 'decimate' has changed definition over the years) :). We have a data acquisition program that saves its output to Excel's .xls format. Unfortunately, the programmer was too stupid to write files the average user can read. I'd like some advice on how to go about: 1. Reading a large Excel file and chop it into many Excel files (with only 65535 lines per file) or 2. Decimate an Excel file & write... say every other line (user selectable)... to a new file. I'm pretty experienced at reading and writing simple text files, but this is my first foray into using COM. I would imagine either choice 1 or 2 is pretty simple once I can get the file open. Thanks in advance. From ryankaskel at gmail.com Wed Feb 28 20:50:06 2007 From: ryankaskel at gmail.com (Ryan K) Date: 28 Feb 2007 17:50:06 -0800 Subject: text wrapping help In-Reply-To: <1172712476.946180.63140@t69g2000cwt.googlegroups.com> References: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> <1172712476.946180.63140@t69g2000cwt.googlegroups.com> Message-ID: <1172713806.477177.207440@s48g2000cws.googlegroups.com> That works great but I need to replace the newlines with 24-(the index of the \n) spaces. On Feb 28, 8:27 pm, attn.steven.... at gmail.com wrote: > On Feb 28, 4:06 pm, "Ryan K" wrote: > > > I'm trying to text wrap a string but not using the textwrap module. I > > have 24x9 "matrix" and the string needs to be text wrapped according > > to those dimensions. Is there a known algorithm for this? Maybe some > > kind of regular expression? I'm having difficulty programming the > > algorithm. > > Try: > > import re > sample_text = """Personal firewall software may warn about the > connection IDLE makes to its subprocess using this computer's internal > loopback interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet.""" > > # assume 24 is sufficiently wide: > > lines = map(lambda x: x.rstrip(), > re.findall(r'.{1,24}(?:(?<=\S)\s|$)', sample_text.replace("\n", " "))) > > print "\n".join(lines) > > -- > Hope this helps, > Steven From giovanni.chiozza at libero.it Fri Feb 16 10:47:04 2007 From: giovanni.chiozza at libero.it (giovanni.chiozza at libero.it) Date: Fri, 16 Feb 2007 16:47:04 +0100 Subject: MS Word mail merge automation Message-ID: Hi Steve M. , Your articole is very interesting to me becouse I'm just tring to do the same thing. Could you please show me the last version of your python code so that I could use it for my purpose. I'm not a programmer but a my friend could help me for this. Thanks so much in advance for your help Giovanni ------------------------------------------------------ Passa a Infostrada. ADSL e Telefono senza limiti e senza canone Telecom http://click.libero.it/infostrada16feb07 From gagsl-py2 at yahoo.com.ar Wed Feb 28 20:04:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Feb 2007 22:04:18 -0300 Subject: Special Characters References: <2adc542f0702271723m4e813d0ckf907227f76992a93@mail.gmail.com> <2adc542f0702271756u51907534x5bdbef7614eab08a@mail.gmail.com> Message-ID: En Tue, 27 Feb 2007 22:56:15 -0300, Sick Monkey escribi?: > I found out that when I was reading the file, there > were additional blank spaces being appended to the value. > > To correct the issue, I just had to dp > varName = msInfo[0].strip() > finName = varName.strip() Only one strip() is enough, the second call does nothing, strip is idempotent. -- Gabriel Genellina From gagsl-py at yahoo.com.ar Mon Feb 12 01:01:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 03:01:55 -0300 Subject: string.replace non-ascii characters References: Message-ID: En Mon, 12 Feb 2007 02:38:29 -0300, Samuel Karl Peterson escribi?: Sorry to steal the thread! This is only related to your signature: > "if programmers were paid to remove code instead of adding it, > software would be much better" -- unknown I just did that last week. Around 250 useless lines removed from a 1000 lines module. I think the original coder didn't read the tutorial past the dictionary examples: *all* functions returned a dictionary or list of dictionaries! Of course using different names for the same thing here and there, ugh... I just throw in a few classes and containers, removed all the nonsensical packing/unpacking of data going back and forth, for a net decrease of 25% in size (and a great increase in robustness, maintainability, etc). If I were paid for the number of lines *written* that would not be a great deal :) -- Gabriel Genellina From exarkun at divmod.com Thu Feb 1 10:01:54 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Feb 2007 10:01:54 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170340916.646800.195670@h3g2000cwc.googlegroups.com> Message-ID: <20070201150154.25807.1117851605.divmod.quotient.6251@ohm> On 1 Feb 2007 06:41:56 -0800, Carl Banks wrote: >On Feb 1, 9:20 am, Jean-Paul Calderone wrote: >> On 1 Feb 2007 06:14:40 -0800, Carl Banks wrote: >> >> >> >> >On Jan 31, 3:37 pm, Jean-Paul Calderone wrote: >> >> On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: >> >> >> >Michele Simionato wrote: >> >> >> On Jan 31, 5:23 pm, "Frank Potter" wrote: >> >> >> > I want to find a multithreaded downloading lib in python, >> >> >> > can someone recommend one for me, please? >> >> >> > Thanks~ >> >> >> >> Why do you want to use threads for that? Twisted is the >> >> >> obvious solution for your problem, >> >> >> >Overkill? Just to download a few web pages? You've got to be >> >> >kidding. >> >> >> Better "overkill" (whatever that is) than wasting time re-implementing >> >> the same boring thing over and over for no reason. >> >> >"I need to download some web pages in parallel." >> >> >"Here's tremendously large and complex framework. Download, install, >> >and learn this large and complex framework. Then you can write your >> >very simple throwaway script with ease." >> >> >Is the twisted solution even shorter? Doing this with threads I'm >> >thinking would be on the order of 20 lines of code. >> >> The /already written/ solution I linked to in my original response was five >> lines shorter than that. > >And I suppose "re-implementing the same boring thing over and over" is >ok if it's 15 lines but is too much to bear if it's 20 (irrespective >of the additional large framework the former requires). > It's written. Copy it and use it. There's no re-implementation to do. And if you don't want to _limit_ the number of concurrent connections, then you don't even need those 15 lines, you need four, half of which are imports. I could complain about what a waste of time it is to always have to import things, but that'd be silly. :) Jean-Paul From jonc at icicled.net Sat Feb 3 11:55:12 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sat, 3 Feb 2007 10:55:12 -0600 Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. In-Reply-To: <1170516285.308948.134410@a34g2000cwb.googlegroups.com> References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170516285.308948.134410@a34g2000cwb.googlegroups.com> Message-ID: <200702031055.12532.jonc@icicled.net> I've been seeing this topic for a day or two so far. Why don't we stick to discussing python on this mailing list? I'm sure there are other mailing lists specifically for discussing chemistry. =\ - Jonathan From news at grauer-online.de Tue Feb 13 09:26:03 2007 From: news at grauer-online.de (Uwe Grauer) Date: Tue, 13 Feb 2007 15:26:03 +0100 Subject: Newbie Question In-Reply-To: <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > bruno.desthuilliers at gmail.com wrote: >> On 9 f?v, 14:06, Stef Mientki wrote: >>>>> will explain the rest >>>> Delphi is a (dying) proprietary, MS-Windows-only[1] software relying >>>> on a low-level language. >>> Well it may be dying, >>> but for the moment it beats Python with a factor of 10, >>> when it comes to user (the majority of PC users) friendly GUI ;-) >> >> Would you mind explaining yourself and backing your above assertion ? >> Like, ie, on which points does Delphi "beats" Python wrt/ GUIs, what >> special magic would make so that GUIs designed with Delphi would be >> more "user-friendly", and where does this "factor 10" comes from ? >> > Maybe I should have written it in quotes "factor of 10" ;-) > But here are a few points > - in Delphi the GUI design itself is done in a graphical environment, > making it much easier and faster > - auto-scaling of components on a form is very easy (so if the user > changes form size ..) > - even making everything on a form movable by the end-user is just 1 > mouse-click > - using the designers style, or the user style is just 1 click > - very good feedback, so creating interactive graphs is very easy, > cross-hair, slopes, region of interest etc. > - a very huge collection of controls is standard available > - print / clipboard / export to almost any graphical file format, just 1 > line of code > > but to be honest ... > ... I never even tried to write a GUI in Python, ... > ... just looked at others examples, > ... and still not seen what I can perform in Delphi ;-) > > cheers, > Stef Mientki > >> Good luck... >> There is dabo which is a tool on top of wxwidgets: http://dabodev.com/ Uwe From steve at holdenweb.com Sun Feb 11 02:05:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 07:05:30 +0000 Subject: Regular Expressions In-Reply-To: References: Message-ID: <45CEC03A.80709@holdenweb.com> Geoff Hill wrote: > What's the way to go about learning Python's regular expressions? I feel > like such an idiot - being so strong in a programming language but knowing > nothing about RE. > > In fact that's a pretty smart stance. A quote attributed variously to Tim Peters and Jamie Zawinski says "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From andrewfelch at gmail.com Tue Feb 27 19:49:31 2007 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 27 Feb 2007 16:49:31 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172620060.412942.212130@a75g2000cwd.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> <1172609437.801573.150900@m58g2000cwm.googlegroups.com> <1172613744.661578.227150@k78g2000cwa.googlegroups.com> <1172615426.752353.25610@8g2000cwh.googlegroups.com> <1172616850.962166.27480@k78g2000cwa.googlegroups.com> <1172618605.121435.247300@t69g2000cwt.googlegroups.com> <1172619395.282157.187030@a75g2000cwd.googlegroups.com> <1172620060.412942.212130@a75g2000cwd.googlegroups.com> Message-ID: <1172623771.171567.16950@a75g2000cwd.googlegroups.com> On Feb 27, 3:47 pm, "Ziga Seilnacht" wrote: > Andrew Felch wrote: > > Thanks for checking. I think I narrowed the problem down to > > inheritance. I inherit from list or some other container first: > > > class PointList( list, AutoReloader ): > > def PrintHi1(self): > > print "Hi2" > > > class MyPrintingClass( AutoReloader ): > > def PrintHi2(self): > > print "Hi2v2" > > > Automatic reloading works for MyPrintingClass but not for PointList. > > Any ideas? > > > -Andrew > > Ah yes, this is the problem of list.__new__ not calling the next > class in MRO. Try to switch the bases, so that AutoReloader's > __new__ method will be called first. > > Ziga That did it! Thanks so much! This really seems to extend Python to be a much better rapid prototyping langauge. It certainly allows me to now use classes where I avoided them like the plague before. Perhaps I'll be able to make programs > 1500 lines now! :-) -Andrew From irmen.NOSPAM at xs4all.nl Thu Feb 1 19:34:56 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 02 Feb 2007 01:34:56 +0100 Subject: Python, readline and OS X In-Reply-To: References: Message-ID: <45c28755$0$322$e4fe514c@news.xs4all.nl> Ron Garret wrote: > I have installed Python 2.5 on my new Intel Mac but I can't for the life > of me get readline to work. I have libreadline installed, I've tried > copying readline.so from my Python 2.3 installation into 2.5, I've > searched the web, and no joy. Could someone please give me a clue? > > rg Does the info in a blog article that I wrote help? http://www.razorvine.net/frog/user/irmen/article/2006-05-08/87 I used this when I compiled my Python 2.5 on my mac, and it seemed to work ;-) I'm now using the python.org binary distribution though and that seems to contain a working readline as well.... ? --Irmen From bmaron2 at hotmail.com Sun Feb 25 16:25:58 2007 From: bmaron2 at hotmail.com (bmaron2 at hotmail.com) Date: 25 Feb 2007 13:25:58 -0800 Subject: Help on object scope? Message-ID: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> Hello everybody, I have a (hopefully) simple question about scoping in python. I have a program written as a package, with two files of interest. The two files are /p.py and /lib/q.py My file p.py looks like this: --- from lib import q def main(): global r r = q.object1() s = q.object2() if __name__ == "__main__": main() --- My file q.py in the subdirectory lib looks like this: class object1: t = 3 class object2: print r.t --- Python gives me an error, saying it can't recognize global name r. However I define r as global in the top-level main definition! Can anyone suggest how I can get around this, if I want to define and bind global names inside of main() which are valid in all sub-modules? Thanks very much for your help! From nogradi at gmail.com Mon Feb 26 15:21:39 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 26 Feb 2007 21:21:39 +0100 Subject: I don't quite understand this error... In-Reply-To: <5c87851f0702260950h5994ab22nccd3d2db2ff5e7d1@mail.gmail.com> References: <5c87851f0702260950h5994ab22nccd3d2db2ff5e7d1@mail.gmail.com> Message-ID: <5f56302b0702261221s10a20d7u28096fdf37f82580@mail.gmail.com> > Thus far, everything works fine unless I'm trying the Deposit or Withdrawal > functions. (I know they're different, but both give roughly the same error.) > Whenever I attempt one of these functions I get the following error message: > > > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "C:\Python24\AEOpaypal.py", line 27, in Deposit > user, passw, balance = accountlist[whichSelected()] > File "C:\Python24\AEOpaypal.py", line 11, in whichSelected > return int(select.curselection()[0]) > IndexError: tuple index out of range "IndexError: tuple index out of range" means that you are trying to access an element of a tuple which does not exist. In your case int(select.curselection()[0]) raises the exception so your tuple select.curselection() doesn't have a 0th entry which means it's empty. HTH, Daniel From tdelaney at avaya.com Mon Feb 26 15:25:48 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 27 Feb 2007 07:25:48 +1100 Subject: a=b change b a==b true?? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ECBD@au3010avexu1.global.avaya.com> rstupplebeen at gmail.com wrote: > All, > It works great now. Thank you for all of your incredibly quick > replies. > Rob You should have a read of these: http://wiki.python.org/moin/BeginnersGuide http://effbot.org/zone/python-objects.htm Cheers, Tim Delaney From could.net at gmail.com Sat Feb 24 02:03:39 2007 From: could.net at gmail.com (Frank Potter) Date: 23 Feb 2007 23:03:39 -0800 Subject: failed to install PIL in fedora core 6 Message-ID: <1172300619.894761.243200@z35g2000cwz.googlegroups.com> I use "python setup.py install" to install PIL in fedora with python 2.4, But I got these errors: running build_ext building '_imaging' extension creating build/temp.linux-i686-2.4 creating build/temp.linux-i686-2.4/libImaging gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,- D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer- size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables - D_GNU_SOURCE -fPIC -fPIC -DHAVE_LIBZ -I/usr/include/freetype2 - IlibImaging -I/usr/include -I/usr/local/include -I/usr/include/ python2.4 -c _imaging.c -o build/temp.linux-i686-2.4/_imaging.o _imaging.c:76:20: error: Python.h: No such file or directory In file included from libImaging/Imaging.h:14, from _imaging.c:78: libImaging/ImPlatform.h:10:20: error: Python.h: No such file or directory libImaging/ImPlatform.h:14:2: error: #error Sorry, this library requires support for ANSI prototypes. libImaging/ImPlatform.h:17:2: error: #error Sorry, this library requires ANSI header files. libImaging/ImPlatform.h:55:2: error: #error Cannot find required 32- bit integer type In file included from _imaging.c:78: libImaging/Imaging.h:90: error: expected specifier-qualifier-list before 'INT32' libImaging/Imaging.h:265: error: expected specifier-qualifier-list before 'INT32' libImaging/Imaging.h:393: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'ImagingCRC32' _imaging.c:123: error: expected specifier-qualifier-list before 'PyObject_HEAD' ......................................................... _imaging.c: At top level: _imaging.c:316: error: expected ')' before '*' token _imaging.c:413: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token _imaging.c:468: error: expected ')' before '*' token _imaging.c:536: error: expected '=', ',', ';', 'asm' or '__attribute__' ............................. before '*' token _imaging.c:773: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'functions' _imaging.c:3138: warning: return type defaults to 'int' _imaging.c: In function 'DL_EXPORT': _imaging.c:3138: error: expected declaration specifiers before 'init_imaging' _imaging.c:3149: error: expected '{' at end of input error: command 'gcc' failed with exit status 1 What should I do if I want to successfully have pil installed? From rattan at cps.cmich.edu Thu Feb 8 09:27:25 2007 From: rattan at cps.cmich.edu (rattan at cps.cmich.edu) Date: 8 Feb 2007 06:27:25 -0800 Subject: help on packet format for tcp/ip programming In-Reply-To: <12sl6tuhkla8ob2@corp.supernews.com> References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> <12sl6tuhkla8ob2@corp.supernews.com> Message-ID: <1170944844.977214.57350@s48g2000cws.googlegroups.com> On Feb 8, 3:40 am, Grant Edwards wrote: > On 2007-02-08, rat... at cps.cmich.edu wrote: > > > struct module pack and unpack will only work for fixed size buffer : > > pack('>1024sIL', buffer, count. offset) but the buffer size can vary > > from one packet to the next :-( > > Oh for Pete's sake... > > struct.pack('>%dsIL' % len(buffer), buffer, count, offset) > > -- > Grant Edwards grante Yow! I want the presidency > at so bad I can already taste > visi.com the hors d'oeuvres. that is great but how does one unpack on the other side? -ishwar From grante at visi.com Sat Feb 17 10:00:12 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 17 Feb 2007 15:00:12 -0000 Subject: WHAT IS THIS? References: Message-ID: <12te63sb4fusb4e@corp.supernews.com> On 2007-02-17, Captain wrote: > Just bought a new PC with Windows XP Media Edition. I have two entries in > the "Add or Remove Programs" section of Control Panel, but there is no > corresponding item in the Start Menu. One entry says: Python 2.2.3 and the > other says: Python 2.2 pywin32 extensions (build203).. The size for each is > 29.28mb. I gather Python is a programming language, but I am wondering why > it was installed on my PC, and is it safe to remove it? Don't ask us, ask whoever installed it. Many of the big PC vendors (e.g. IBM/lenovo, Dell, HP/Compaq) install all sorts of software on PCs they ship. About half of them install programs that are written in Python. > I have no intention of learning the program. It's required to run some of the programs that came on your PC. -- Grant Edwards grante Yow! Hey, I LIKE that at POINT!! visi.com From mccredie at gmail.com Thu Feb 15 17:35:10 2007 From: mccredie at gmail.com (Matimus) Date: 15 Feb 2007 14:35:10 -0800 Subject: output to console and to multiple files In-Reply-To: <1171558306.121792.169430@h3g2000cwc.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171498259.757320.127100@q2g2000cwa.googlegroups.com> <1171554821.510472.313950@s48g2000cws.googlegroups.com> <1171558306.121792.169430@h3g2000cwc.googlegroups.com> Message-ID: <1171578909.944542.188190@a75g2000cwd.googlegroups.com> On Feb 15, 8:51 am, "Matimus" wrote: > On Feb 15, 7:53 am, "nathan.sh... at gmail.com" > wrote: > > > > > On Feb 14, 5:10 pm, "goodwolf" wrote: > > > > like this? > > > > class Writers (object): > > > > def __init__(self, *writers): > > > self.writers = writers > > > > def write(self, string): > > > for w in self.writers: > > > w.write(string) > > > > def flush(self): > > > for w in self.writers: > > > w.flush(): > > > > import sys > > > > logfile = open('log.txt', 'w') > > > sys.stdout = Writers(aya.stdout, file('log.out', 'w'), logfile) > > > sys.stderr = Writers(aya.stdout, file('log.err', 'w'), logfile) > > > i've tried simliar methods to this and to what Matimus wrote. I know > > it works great when using print statements. > > However, I'm looking to find something that will work with the output > > from a subprocess, such as from spawn, os.system, os.popen, etc. > > I think you should be able to use my or goodwolf's solution with the > subprocess module. Something like this (untested): > > [code] > class TeeFile(object): > def __init__(self,*files): > self.files = files > def write(self,txt): > for fp in self.files: > fp.write(txt) > > if __name__ == "__main__": > import sys > from subprocess import Popen > > command = "whatever you want to run" > outf = file("log.out","w") > errf = file("log.err","w") > allf = file("log.txt","w") > Popen( > command, > stdout = TeeFile(sys.__stdout__,outf,allf), > stderr = TeeFile(sys.__stderr__,errf,allf) > ) > [/code] I tried this at lunch and it doesn't work. Some version of this method may work, but Popen tries to call the 'fileno' method of the TeeFile object (at least it did on my setup) and it isn't there. This is just a preemptive warning before someone comes back to let me know my code doesn't work. From paul at boddie.org.uk Sun Feb 4 15:02:21 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Feb 2007 12:02:21 -0800 Subject: Python does not play well with others In-Reply-To: References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170600807.504088.80150@m58g2000cwm.googlegroups.com> Message-ID: <1170619340.985783.134860@s48g2000cws.googlegroups.com> John Nagle wrote: > > The real problems are with integration of modules that > aren't written in Python. Python-only modules don't have the > version compatibility problems which C modules do. Loading > a Python-only module from an external source is usually not > a big deal. Building a C module, especially one with > dependencies on other components, can be a big deal. > So, focus on problems with modules which have C > components. I think that the integration of certain "popular" extensions into the Python distribution has been one of the tools employed to mitigate the version compatibility situation: if the popular stuff gets released with Python, perhaps fewer people will complain about "C modules" whose developers/maintainers haven't updated them for the latest release. I'm not really convinced that this makes for a sustainable approach, however, since this just becomes a process of accretion where the core development community must get larger and become very well-coordinated in order to manage the dependencies within the software, as well as tracking external dependencies. Over the years there have been suggestions which might have made the compatibility situation a bit better: a "Python in a tie" release was an objective of the seemingly dormant Python Business Foundation; Linux Standard Base inclusion of Python has been proposed and discussed. I can't help feeling that without improvements in such other areas, things like "C module" availability for different Python versions (and for different versions of related libraries) is mainly an issue of doing the almost thankless hard work of backporting, testing and managing different build configurations. Still, there may be demand for a backports community in all this. Paul From fuzzyman at gmail.com Mon Feb 5 16:06:06 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Feb 2007 13:06:06 -0800 Subject: [ANN] Python Akismet 0.1.5 Message-ID: <1170709566.451988.34040@h3g2000cwc.googlegroups.com> `Python Akismet 0.1.5 `_ is now available. Fixed a typo/bug in ``submit_ham``. Thanks to Ian Ozsvald for pointing this out. **Python Akismet** is a Python interface to the `Akismet `_, spam blocking web-service. It is aimed at trapping spam comments. * `Quick Download (119k zipfile) `_ The Python interface comes with an `example CGI `_. From grahn+nntp at snipabacken.dyndns.org Tue Feb 13 12:51:00 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Feb 2007 17:51:00 GMT Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: On Mon, 12 Feb 2007 19:10:02 +0100, Ma?l Benjamin Mettler wrote: > Thomas Nelson schrieb: [top posting fixed] >> I realize I'm approaching this backwards from the direction most >> people go, but does anyone know of a good c/c++ introduction for >> python programmers? > Learning C++ is not worth is in my opinion, since you can get the OOP > power from Python and use C if you need speed... Well, C++ is a better language than C in many ways. So, if he needs to learn one of them, why does it have to be C? Another reason some people choose C++ over Python for some tasks is that they feel that larger programs benefit from strong, static type checking. I like both ways, but depending on the task, one or the other is better. And then there's always the "my boss told me" reason, which seems to apply to the OP. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From pete at shinners.org Tue Feb 27 18:09:45 2007 From: pete at shinners.org (shredwheat) Date: 27 Feb 2007 15:09:45 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <1172609807.109748.93170@8g2000cwh.googlegroups.com> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> <1172573562.215310.76760@8g2000cwh.googlegroups.com> <54ih3nF2143jeU2@mid.uni-berlin.de> <1172574041.569357.127440@q2g2000cwa.googlegroups.com> <54ijbdF1urdo2U1@mid.uni-berlin.de> <1172602497.566766.79250@p10g2000cwp.googlegroups.com> <1172609807.109748.93170@8g2000cwh.googlegroups.com> Message-ID: <1172617785.871756.77380@j27g2000cwj.googlegroups.com> When your programs stops with the error, it should also be printing a stack trace. This is a list of all the functions that have been called when Python had the problem. You shouldn't have to do anything extra to get the stack trace. From bernhard.voigt at gmail.com Wed Feb 7 06:14:39 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 7 Feb 2007 03:14:39 -0800 Subject: Graphs, bar charts, etc In-Reply-To: <45c93f14$0$16314$88260bb3@free.teranews.com> References: <45c87a32@griseus.its.uu.se> <45c93f14$0$16314$88260bb3@free.teranews.com> Message-ID: <1170846879.008949.47380@a34g2000cwb.googlegroups.com> On Feb 7, 4:46 am, "Joshua J. Kugler" wrote: > Jan Danielsson wrote: > > Hello all, > > > I have some data in a postgresql table which I view through a web > > interface (the web interface is written in python -- using mod_python > > under apache 2.2). Now I would like to represent this data as graphs, > > bar charts, etc. > > > I know about matplotlib, and it seemed like exactly what I was > > looking for. I tried importing it in my script, but it gave me some > > error about a home directory not being writable. I'm not sure I like the > > idea of it require to be able to write somewhere. Am I using it wrong? Hi! Matplotlib saves some stuff into a configuration dir. Take a look at the __init__.py file in site-packages/matplotlib (or where your installation lives). There are several environment variabels checked where a .matplotlib folder will be created. Try unsetting HOME, than probably TMP will be used and this should be writable in any case. I don't know whether the creation of the configuration folder can be turned off. Hope that helps! Bernhard From http Thu Feb 15 16:14:15 2007 From: http (Paul Rubin) Date: 15 Feb 2007 13:14:15 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> Message-ID: <7xr6srgm3c.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > My original comment was that tuples could be thought of more like > C structs or Pascal records. Should f(*args) receive a list rather than a tuple arg? From google at mrabarnett.plus.com Thu Feb 8 18:28:20 2007 From: google at mrabarnett.plus.com (MRAB) Date: 8 Feb 2007 15:28:20 -0800 Subject: begin to parse a web page not entirely downloaded In-Reply-To: <1170958856.700750.3080@a75g2000cwd.googlegroups.com> References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> <45cb63d4$0$6842$4d3efbfe@news.sover.net> <1170958856.700750.3080@a75g2000cwd.googlegroups.com> Message-ID: <1170977300.419122.230010@s48g2000cws.googlegroups.com> On Feb 8, 6:20 pm, "k0mp" wrote: > On Feb 8, 6:54 pm, Leif K-Brooks wrote: > > > > > k0mp wrote: > > > Is there a way to retrieve a web page and before it is entirely > > > downloaded, begin to test if a specific string is present and if yes > > > stop the download ? > > > I believe that urllib.openurl(url) will retrieve the whole page before > > > the program goes to the next statement. > > > Use urllib.urlopen(), but call .read() with a smallish argument, e.g.: > > > >>> foo = urllib.urlopen('http://google.com') > > >>> foo.read(512) > > ' ... > > > foo.read(512) will return as soon as 512 bytes have been received. You > > can keep caling it until it returns an empty string, indicating that > > there's no more data to be read. > > Thanks for your answer :) > > I'm not sure that read() works as you say. > Here is a test I've done : > > import urllib2 > import re > import time > > CHUNKSIZE = 1024 > > print 'f.read(CHUNK)' > print time.clock() > > for i in range(30) : > f = urllib2.urlopen('http://google.com') > while True: # read the page using a loop > chunk = f.read(CHUNKSIZE) > if not chunk: break > m = re.search('', chunk ) > if m != None : > break > [snip] I'd just like to point out that the above code assumes that the '' is entirely within one chunk; it could in fact be split across chunks. From ophionman at gmail.com Mon Feb 26 13:57:27 2007 From: ophionman at gmail.com (raf) Date: 26 Feb 2007 10:57:27 -0800 Subject: about framework In-Reply-To: References: Message-ID: <1172516247.711812.301390@8g2000cwh.googlegroups.com> On Feb 24, 10:09 pm, memcac... at aol.com wrote: > Python has some web framework.I'm not familiar with all of them. > Do you think which is best popular of them?Thanks. >


**************************************
AOL now offers free > email to everyone. Find out more about what's free from AOL athttp://www.aol.com. take a look at http://djangoproject.org From aleaxit at gmail.com Wed Feb 28 14:48:46 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 28 Feb 2007 11:48:46 -0800 Subject: gmpy moving to code.google.com In-Reply-To: <1172612322.546122.162640@k78g2000cwa.googlegroups.com> References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> <1172612322.546122.162640@k78g2000cwa.googlegroups.com> Message-ID: <1172692126.832159.276190@h3g2000cwc.googlegroups.com> On Feb 27, 1:38 pm, "Ziga Seilnacht" wrote: > Alex Martelli wrote: > > On Feb 27, 2007, at 2:59 AM, Daniel Nogradi wrote: > > > > Hi Alex, > > > > I did another test, this time with python 2.4 on suse and things are > > > worse than in the previous case (which was python 2.5 on fedora 3), > > > ouput of 'python gmp_test.py' follows: > > > Interesting! gmpy interacts with decimal.Decimal by "monkey- > > patching" that class on the fly; clearly the monkey-patching isn't > > working with 2.4 on SuSE, so all the addition attempts are failing > > (all 6 of them). > > > So the issue is finding out why this strategy is failing there, while > > succeeding on other Linux distros, Mac, and Windows. > > This is a bug in Python's decimal module in release 2.4.0. It was > fixed > in release 2.4.1: > > http://svn.python.org/view?rev=38708&view=rev Thanks! This was really helpful and saved me a lot of head- scratching. I'm wondering if I should specifically test for 2.4.0 in the tests, and give a clear error message about decimal interoperability with other types being broken in that release and suggesting an upgrade, rather than producing "mysterious" test breakages... done -- I think this may simplify things in the future. Thanks, Alex From gagsl-py at yahoo.com.ar Wed Feb 7 22:26:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Feb 2007 00:26:46 -0300 Subject: help on packet format for tcp/ip programming References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> Message-ID: En Thu, 08 Feb 2007 00:14:13 -0300, escribi?: > On Feb 8, 1:43 am, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> rat... at cps.cmich.edu wrote: >> > I want a specific packet format for packet exchange between a >> > client server across the network. For example frame format >> > as a python class could be: >> > class Frame: >> > def __init__(self, buffer=None, count=0, offset=0): >> > self.buffer = buffer >> > self.count = count >> > self.offset = offset >> > the question is how to convert it to a byte stream so that format >> > of count and offset also becomes a sequence of bytes. >> >> Try struct. >> > > struct module pack and unpack will only work for fixed size buffer : > pack('>1024sIL', buffer, count. offset) but the buffer size can vary > from one packet to the next :-( Use struct to pack count and offset into a fixed size field (2 or 4 bytes depending on range); send buffer after that. buffer must come *after* you send its size, else it's a lot harder to retrieve at the other end. -- Gabriel Genellina From sturlamolden at yahoo.no Mon Feb 19 06:26:09 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 19 Feb 2007 03:26:09 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <45d624f7$0$10573$426a74cc@news.free.fr> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <45d624f7$0$10573$426a74cc@news.free.fr> Message-ID: <1171884369.349651.308340@p10g2000cwp.googlegroups.com> On Feb 16, 11:12 pm, Bruno Desthuilliers wrote: > "GUI based programming languages" ? What's that ? LabView From lbates at websafe.com Mon Feb 26 17:29:04 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 26 Feb 2007 16:29:04 -0600 Subject: how can I create/set a 'file' reference in a attribute of a class In-Reply-To: <1172528624.153189.218200@8g2000cwh.googlegroups.com> References: <1172528624.153189.218200@8g2000cwh.googlegroups.com> Message-ID: <45E35F30.5040002@websafe.com> ken wrote: > Hi, > i have a class: > > class LogHandler(ContentHandler): > # a reference to a file open by some other function/class > outputFile; > > > def endElement(self, name): > doSomething(self, "GroupResultList", self.text, outputFile) > > > First, I get an error saying 'NameError: global name 'outputFile' is > not defined' , how can I declare outputFile as a 'file reference'? > > Second , how can I set this file reference after I create the object > 'LogHandler'? > > How can I do that? > f = open('dummyFile.txt'); > curHandler = LogHandler() > curHandler.file = f > Normally this is done when you instantiate the class: fp = open('dummyFile.txt') curHandler=LogHander(fp) class LogHandler(ContentHandler): def __init__(self, fp=None): self.fp=fp def endElement(self, name: doSomething(self, "GroupResultList", self.text, self.fp) but you could set it later if you like: fp = open('dummyFile.txt') curHandler=LogHander() curHandler.fp=fp -Larry Bates From http Fri Feb 2 17:18:38 2007 From: http (Paul Rubin) Date: 02 Feb 2007 14:18:38 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <7xejp89pa9.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > database: Sybase, Oracle, MySQL, SQLite, ODBC, Firebird > database versions: who knows? assume two per database > python versions: 2.4, 2.5, 2.6, 3.0? > platforms: windows, pick two linux flavors, solaris > > Those numbers give me 6 * 2 * 4 * 4 == 192 combinations to test. Ignore > Python 2.4. That brings it down to 144. Only test on one linux variant and > skip solaris. Now you're at 72. Leave Firebird and Sybase out of the mix. > Now you're down to 48. That's still a fair sized burden. Why is it that PHP and J2SE manage deal with this problem but Python cannot? From tdelaney at avaya.com Thu Feb 22 17:18:44 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 23 Feb 2007 09:18:44 +1100 Subject: is it possible to remove the ':' symbol in the end of lines startingwith 'if', 'while' etc? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ECB5@au3010avexu1.global.avaya.com> openopt at ukr.net wrote: > I don't know to which forum should I post the message > I hope someone related to the Python kernel development will read & > consider the idea It has been considered and rejected. http://www.python.org/doc/faq/general/#why-are-colons-required-for-the-i f-while-def-class-statements Tim Delaney From usable.thought at gmail.com Fri Feb 16 11:51:54 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 08:51:54 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> <1171642551.277929.233540@l53g2000cwa.googlegroups.com> Message-ID: <1171644713.924096.173940@h3g2000cwc.googlegroups.com> On Feb 16, 11:34 am, Steve Holden wrote: > It sounds like you may have mistakenly added Cygwin binary directories > to your Windows path. This isn't normally necessary, since the Cygwin > shell makes all necessary path adjustments as it starts. I did add c:/cywgin to the path, don't remember why now. For the moment I've moved c:\cygwin to the end of my path, so that it comes after c:\Python25, and reinstalled Python 2.5. That seems to have cured at least this particular problem with Python. When I have a spare moment I will take cygwin out of the path altogether and see if I can remember why I put it in there to begin with ... From steve at REMOVE.THIS.cybersource.com.au Wed Feb 21 06:39:24 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 22:39:24 +1100 Subject: BDFL in wikipedia References: <1172053544.515756.28200@v45g2000cwv.googlegroups.com> Message-ID: On Wed, 21 Feb 2007 02:25:44 -0800, Carl Banks wrote: >> a) that page have an explanation of what BDFL is >> b) shouldn't it mention Linus, Larry Wall, others?[3] > > Since when is Larry Wall benevolent? He should be called the SDFL. > > :) I can't think what the S stands for... if it was M, I'd say Malevolent, but S? -- Steven. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 5 13:41:40 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 05 Feb 2007 19:41:40 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: <52pc34F1oqe5fU1@mid.individual.net> Alexander Schmolck wrote: > Apart from being less to type Cool. Less to type. > and it is superior in that it's > generalizes much better, e.g: > > avg&.^. NB. geomtric mean > avg&.% NB. harmonic mean > avg M NB. column mean of matrix M > avg"1 M NB. row mean of matrix M Is there any regularity in this? If it is, it's not obvious at all. Regards, Bj?rn -- BOFH excuse #78: Yes, yes, its called a design limitation From nagle at animats.com Sun Feb 4 17:45:16 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Feb 2007 22:45:16 GMT Subject: Python does not play well with others In-Reply-To: <1170625204.156763.178460@j27g2000cwj.googlegroups.com> References: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> Message-ID: <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> Graham Dumpleton wrote: > On Feb 4, 1:05 pm, Paul Rubin wrote: > >>"Paul Boddie" writes: >> >>>Probably the biggest inhibitor, as far as I can see, has been the >>>server technology chosen. Many hosting providers have historically >>>offered no better than CGI for Python, whilst PHP runs within Apache >>>itself, and it has previously been stated that mod_python has been >>>undesirable with regard to isolating processes from each other. >>>Consequently, a number of Python people seem to have held out for >>>other "high performance" solutions, which various companies now offer. >> >>Your point that shared hosting with Python isn't so easy because of >>insufficient isolation between apps is valid. Maybe Python 3.0 can do >>something about that and it seems like a valid thing to consider while >>fleshing out the 3.0 design. > > > To clarify some points about mod_python, since these posts do not > properly explain the reality of the situation and I feel people are > getting the wrong impression. > > First off, when using mod_python it is possible to have it create > multiple sub interpreters within each Apache child process. Realistically, mod_python is a dead end for large servers, because Python isn't really multi-threaded. The Global Python Lock means that a multi-core CPU won't help performance. FastCGI, though, can get all the CPUs going. It takes more memory, though, since each instance has a full copy of Python and all the libraries in use. (FastCGI is a straightforward transaction processing engine. Each transaction program is launched in a separate process, and, once done with one transaction, can be used to do another one without reloading. When things are slow, the extra transaction processes are told to exit; when load picks up, more of them are forked. Security is comparable to CGI.) John Nagle From sjmachin at lexicon.net Sun Feb 25 05:47:59 2007 From: sjmachin at lexicon.net (John Machin) Date: 25 Feb 2007 02:47:59 -0800 Subject: RegExp performance? In-Reply-To: <45e145a0$0$90264$14726298@news.sunsite.dk> References: <45e145a0$0$90264$14726298@news.sunsite.dk> Message-ID: <1172400479.486951.300070@v33g2000cwv.googlegroups.com> On Feb 25, 7:21 pm, Christian Sonne wrote: > Long story short, I'm trying to find all ISBN-10 numbers in a multiline > string (approximately 10 pages of a normal book), and as far as I can > tell, the *correct* thing to match would be this: > ".*\D*(\d{10}|\d{9}X)\D*.*" All of those *s are making it work too hard. Starting with your r".*\D*(\d{10}|\d{9}X)\D*.*" [you do have the r"..." not just "....", don't you?] Step 1: Lose the .* off each end -- this is meaningless in the context of a search() or findall() and would slow the re engine down if it doesn't optimise it away. r"\D*(\d{10}|\d{9}X)\D*" Step 2: I presume that the \D* at each (remaining) end is to ensure that you don't pick up a number with 11 or more digits. You only need to test that your presumed ISBN is not preceded/followed by ONE suspect character. Is ABC1234567890DEF OK? I think not; I'd use \b instead of \D r"\b(\d{10}|\d{9}X)\b" Step 3: Now that we have only \b (which matches 0 characters) at each end of the ISBN, we can lose the capturing () r"\b\d{10}|\d{9}X\b" Step 4: In the case of 123456789X, it fails on the X and then scans the 123456789 again -- a tiny waste compared to all the * stuff, but still worth fixing. r"\b\d{9}[0-9X]\b" Give that a whirl and let us know how correct and how fast it is. > > (it should be noted that I've removed all '-'s in the string, because > they have a tendency to be mixed into ISBN's) > > however, on my 3200+ amd64, running the following: > > reISBN10 = re.compile(".*\D*(\d{10}|\d{9}X)\D*.*") You should really get into the habit of using raw strings with re. > isbn10s = reISBN10.findall(contents) > > (where contents is the string) > > this takes about 14 minutes - and there are only one or two matches... How many actual matches and how many expected matches? Note on "and there are only one or two matches": if your data consisted only of valid ISBNs separated by a single space or comma, it would run much faster. It is all the quadratic/exponential mucking about with the in-between bits that slows it down. To demonstrate this, try timing dummy data like "1234567890 " * 1000000 and "123456789X " * 1000000 with your various regexes, and with the step1, step2 etc regexes above. > > if I change this to match ".*[ ]*(\d{10}|\d{9}X)[ ]*.*" instead, I risk > loosing results, but it runs in about 0.3 seconds > > So what's the deal? - why would it take so long to run the correct one? Because you have .*\D* in other words 0 or more occurrences of almost anything followed by 0 or more occurrences of almost anything. Even assuming it ignores the .*, it will find the longest possible sequence of non-digits, then try to match the ISBN stuff. If it fails, it will shorten that sequence of non-digits, try the ISBN stuff again, etc etc until it matches the ISBN stuff or that sequence of non-digits is down to zero length. It will do that for each character position in the file contents. Why is it faster when you change \D to []? Presumably because in your data, sequences of non-digits are longer than sequences of spaces IOW there is less stuff to back-track over. > - especially when a slight modification makes it run as fast as I'd > expect from the beginning... > > I'm sorry I cannot supply test data, in my case, it comes from > copyrighted material - however if it proves needed, I can probably > construct dummy data to illustrate the problem What you call "dummy data", I'd call "test data". You should make a sample of "dummy data" and test that your regex is (a) finding all ISBNs that it should (b) not reporting incorrect matches, *BEFORE* being concerned with speed. > > Any and all guidance would be greatly appreciated, For some light reading :-) borrow a copy of Friedl's book (mentioned in the Python re docs) and read the parts on how backtracking regex engines work. HTH, John From thinker at branda.to Mon Feb 26 12:45:14 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 01:45:14 +0800 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: <45E31CAA.2010409@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 zefciu wrote: > Thinker wrote: > >> You can add some printf() to throw out messages to make sure >> where the program stop at. If you can compile the module with >> debug information and use gdb to backtrace dump file, it would be >> useful. > > Did it. The arguments are parsed, but the coord tuple isn't. But > can PyArg_ParseTuple be used to tuples other than function > arguments? If not, what should I use? Since PyArg_ParseTuple() is supposed to parse arguments, I recommand you to use PyTuple_GetItem() or PyTuple_GET_ITEM(). You can find more functions at http://docs.python.org/api/genindex.html . - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4xyq1LDUVnWfY8gRAilNAKDFTKwahXpuxFImhR57Yw5efAGP1wCfR/qU o774g2YB5gMBLrUa9YltDSQ= =/tWC -----END PGP SIGNATURE----- From hardcoded.software at gmail.com Sun Feb 25 14:06:03 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 25 Feb 2007 11:06:03 -0800 Subject: Nested Parameter Definitions In-Reply-To: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> Message-ID: <1172430363.360956.5300@q2g2000cwa.googlegroups.com> On Feb 25, 1:00 pm, "Paddy" wrote: > I blogged on finding a new-to-me feature of Python, in that you are > allowed to nnest parameter definitions: > > >>> def x ((p0, p1), p2): > > ... return p0,p1,p2 > ...>>> x(('Does', 'this'), 'work') > > ('Does', 'this', 'work') > > > > Ruben commented that there was a poll on this features continued > existence taken at PyCon and it could go. > > Just as I found it, it could go > > I wondered if those of you with some Python experience new of nested > parameters and don't use them; or just forgot/don't know it is > possible? > > - Paddy. > > Oh - the blog entry is athttp://paddy3118.blogspot.com/2007/02/pythons-function-nested-paramet... I didn't know about it either. Without the call example, I would have had a hard time to try to figure out what these extra brackets are for. For this reason, I think that an explicit unpack is more readable, and thus better. From S.Mientki-nospam at mailbox.kun.nl Sat Feb 17 03:11:54 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 17 Feb 2007 09:11:54 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> Message-ID: <1a048$45d6b8b7$d443bb3a$16782@news.speedlinq.nl> Peter Decker wrote: > On 2/16/07, Stef Mientki wrote: > >> In one of the other threads, Dabo was meant as a GUI designer, >> I tried it yesterday, >> and although it looks very promising, >> at the moment this is not a graphical design environment, >> just a complex (compared to Delphi) design environment with graphical >> feedback. >> Just my 2 cents ;-) > > Dabo is indeed a work in progress. They are developing the various > tools now to get people started, but have plans for a full graphical > IDE in the manner of Delphi or Visual Studio. > > You can complain that this free tool developed by volunteers in their > spare time isn't as polished as a commercial tool backed by large > corporations that can afford large paid staffs. Sorry, but I didn't complain !! I just wrote down my observations. I didn't write my observations to dis-encourage people, (if so, my sincere appologies) but to show that their are other (and maybe better) ways. > > Or you could contribute. > Believe me or not, I love free and open software, and I do contribute to the open source community, but let everyone do what he/she is good in. Why do you think I want to replace the use of MatLab and LabView (and a number of others) with Python ;-) cheers, Stef Mientki From dingbat at codesmiths.com Mon Feb 19 11:03:43 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 19 Feb 2007 08:03:43 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <1171901023.751608.280430@a75g2000cwd.googlegroups.com> On 16 Feb, 21:22, ifti_cr... at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language Why? What is causing you to do this, and what do you need to achieve by doing it? > i want to go through with GUI based programming language like VB.net "GUI-based" is fairly unimportant as it's just how you build your programs, not what they do afterwards. VB is GUI-based, Python can be GUI-based but is usually fairly text-based. What's probably more significant here is whether the resulting program runs in a GUI or not. VB obviously does, on the Windows desktop. Java also has a sizable market for cross-platform GUI applications. In many ways Java is more capable than VB, but also far less easy to work with for rapid simple applications (I'd take 10 year old VB over GridBag any time!). GUI programs are less important now than they were a few years ago, owing to the huge importance of the web and HTML. Although HTML can still be seen as GUI, it really needs to be worked with at the raw HTML source level (at least for quality work). This doesn't need any sort of GUI built into the language, so Python (or Ruby or Perl) are ideal. With the rise of AJAX toolkits, we're finally seeing "HTML as a GUI" turn into a workable choice for building sophisticated GUI apps in a sensible amount of time. Finally! The tools used here depend significantly on the toolkits used and it's still early days to pick winners. If I had to write Windows-only desktop GUI apps, then I'd stick with VB6 (which I wrote for years) or whatever M$oft decree to be its moral successor. Actually I'd probably stick with VB6.... If I had to write cross-platform GUI desktop apps, then I'd be looking at whatever the favoured toolkit for Java is this week. Maybe Swing, if I wanted to get a paid job using it. Java Web Start needs looking at too. If I just had to make "a sophisiticated GUI app" appear on a lot of corporate desktops, then it would probably be based on Java Server Faces. For nearly all of the choices above, the "language" part of the task is minor in comparison to tiresome GUI building. That's just the way commerce works, and why we don't all get to write everything in Scheme or Haskell. If I had a free hand in writing better shell scripts, or in writing moderately complex algorithms with no visible UI, then I have chosen Python. It beats the hell out of Perl and is (AFAICS) better than Ruby. For building web reporting apps that generate HTML, then I'm also choosing to use my sparse Python knowledge rather than my substantial Java / JSP knowledge. Seems to be working so far. For web-hosted GUI apps, I don't know enough about Python to say. Doesn't look like it beats JSF though. There's also the question of what "OOP" means. For the "mainstream" languages, then classic statically-typed OO is done best by writing in Java. This has a cleaner OOP language design than C++, the benefit of a decade's hindsight and a clean slate. Dynamically or duck-typed languages like Python and Ruby are quite different from this. It's still OOP, but not how your uncle Bjarne knew it. Quite a culture shock too. From mituller at gmail.com Thu Feb 8 14:38:14 2007 From: mituller at gmail.com (mtuller) Date: 8 Feb 2007 11:38:14 -0800 Subject: Parsing HTML Message-ID: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> I am trying to parse a webpage and extract information. I am trying to use pyparser. Here is what I have: from pyparsing import * import urllib # define basic text pattern spanStart = Literal('') spanEnd = Literal('') printCount = spanStart + SkipTo(spanEnd) + spanEnd # get printer addresses printerURL = "http://printer.mydomain.com/hp/device/this.LCDispatcher? nav=hp.Usage" printerListPage = urllib.urlopen(printerURL) printerListHTML = printerListPage.read() printerListPage.close for srvrtokens,startloc,endloc in printCount.scanString(printerListHTML): print srvrtokens print printCount I have the last print statement to check what is being sent because I am getting nothing back. What it sends is: {"" SkipTo:("") ""} If I pull out the "hpPageText" I get results back, but more than what I want. I know it has something to do with escaping the quotation marks, but I am puzzled as to how to do it. Thanks, Mike From aisaac at american.edu Tue Feb 27 01:40:29 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 27 Feb 2007 06:40:29 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: "Ben Finney" wrote in message news:mailman.4438.1172534289.32031.python-list at python.org... > The Pythonic design is: don't expect to have such control over users > of your code. I know this is a popular response, but the fact of the matter remains that it can be helpful to know when someone tries to set a value for a nonexisting attribute. This is especially true if there have been any interface changes. So my question remains: how best to trap any such attempt subsequent to object initialization? (I am willing to have properties for all data attributes, if that helps.) Thank you, Alan Isaac From usenet200701 at tobyinkster.co.uk Sun Feb 4 15:55:27 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Sun, 4 Feb 2007 20:55:27 +0000 Subject: "Subscribing" to topics? References: <5aoxh.7440$gJ1.6708@newsfe17.lga> <1170618799.354069.327210@h3g2000cwc.googlegroups.com> Message-ID: Mizipzor wrote: > I searhed around a little and it seems that not only do i need a > newsreader, i need a newsserver to. To fetch all the messages from > here. I learned that sometimes the ISP provides one, however, mine do > not. But then I discovered that Google has a free newsserver, so I > joined this group from there. You discovered wrong -- Google does not provide a free newsserver. They no doubt *have* several newsservers, but don't provide direct access to them either free, or for a fee. They only provide a web interface to access the contents of their newsservers, with a fraction of the features that a real newsreader would. You seem to already have a newsreader -- you're using Opera, which includes a fairly good one, hidden away in the Hotlist/Panels/whatever- they're-calling-it-today. Other newsreaders I'd recommend are PAN and Forte Agent. So you just need a server. "pubnews.gradwell.net" still seems to exist -- it's free. Alternatively, "news.individual.net" offers a good service for a fairly low yearly cost. -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From jstroud at mbi.ucla.edu Wed Feb 14 19:21:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 16:21:53 -0800 Subject: anyway to create a table-like object? In-Reply-To: References: Message-ID: Wensui Liu wrote: > Dear all, > > is there a way to create a 2-dimension-table-like object such that I > can reference a whole column directly using something like : > mytable.column1 ? > > by the way, can python be used for database programming to pull large > volume data (hundred M or even several Gs) out of large database and > do data manipulation and reporting ? if yes, how is the speed and > efficiency ? > > thanks. > > wensui I have a table class that works like this: atable['some_col'] ==> list of values atable[some_row_index] ==> list of values atable[slice_start:slice_end] ==> new table atable[('some_col', 'other_col', 'another_col')] ==> 3 col. table atable['some_col', some_row_index] ==> one value atable['some_col', slice_start:slice_end] ==> list of values atable[('some_col', 'other_col'), some_row_index] ==> list of 2 vals atable[('some_col', 'other_col'), slice_start:end]) ==> 2 col. table As you can see, it has a lot of flexibility, but may not be the ultimate in terms of speed (and purists may not like the way __getitem__ returns data based on context). It is for people who care about convenience over speed and do not adhere to some puritanical ideal about how __getitem__ should work. There is little typechecking (in accord with my own brand of puritanical philosophy), so be careful if you have ints as column headers. The datastructure is implemented as a list of lists (by row) and the "keys" (column headings) are a list. So size limitations are limited by memory. Theoretically, the __getitem__ (where all the work and decisions are done) could be factored out and wrapped around dbi for hard-core database usage. This might entail some serious creativity. It also has some other features, such as returning matches, etc. It is not intended, at all, to rival an actual database such as mysql--the model is more based on how Joe Users use excel files. If you are interested, I can send you the module. Beyond actual use in my own and my wife's work, there has been little testing. James From karoly.kiripolszky at gmail.com Mon Feb 5 09:54:25 2007 From: karoly.kiripolszky at gmail.com (=?iso-8859-1?q?K=E1roly_Kiripolszky?=) Date: 5 Feb 2007 06:54:25 -0800 Subject: C parsing fun In-Reply-To: References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> <1170683733.434435.171350@j27g2000cwj.googlegroups.com> Message-ID: <1170687265.764375.96560@p10g2000cwp.googlegroups.com> I've found a brute-force solution. In the preprocessing phase I simply strip out the comments (things inside comments won't appear in the result) and replace curly brackets with these symbols: #::OPEN::# and #::CLOSE::#. After parsing I convert them back. In fact I can disclude commented lines from the analyzis as I only have to cope with production code. Claudio Grondi ?rta: > K?roly Kiripolszky wrote: > > You're right, thank you for the comment! I will look after how to > > avoid this. > And after you have resolved this 'small' ;-) detail you will probably > notice, that some full functional and in wide use being parser have > still trouble with this ... > > Claudio > > > > Marc 'BlackJack' Rintsch ?rta: > >> In <1170679559.272656.145660 at v33g2000cwv.googlegroups.com>, > >> karoly.kiripolszky wrote: > >> > >>> and the great thing is that the algorithm can be used with any > >>> language that structures the code with brackets, like PHP and many > >>> others. > >> But it fails if brackets appear in comments or literal strings. > >> > >> Ciao, > >> Marc 'BlackJack' Rintsch > > From kibleur.christophe at gmail.com Sun Feb 4 09:03:28 2007 From: kibleur.christophe at gmail.com (Tool69) Date: 4 Feb 2007 06:03:28 -0800 Subject: Vim scripting with python In-Reply-To: References: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Message-ID: <1170597808.262801.234260@v45g2000cwv.googlegroups.com> Thanks Stuart, I'll take a look at it. Another thing : Is there any way to made some modification de the python.syntax file to highlight the functions call, i.e : os.popen(...) ---> "popen(...)" will be highlighted. Cheers. From narendra.c.tulpule at motorola.com Thu Feb 1 17:27:03 2007 From: narendra.c.tulpule at motorola.com (Tulpule Naren-MGI2846) Date: Thu, 1 Feb 2007 17:27:03 -0500 Subject: Setting IP TOS fields Message-ID: Hi, I don't see the ToS field that I set, in the generated IP packets captured via Ethereal/WireShark. What step am I missing in the code below? s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((sIntf, sPort)) tos = 64 # I also tried tos = struct.pack("B", 64) s.setsockopt(socket.SOL_IP, socket.IP_TOS, tos) # at this point, s.getsockopt(socket.SOL_IP, socket.IP_TOS,1) returns '@' i.e. chr(64) ... s.sendto(data, 0, dAddr) # 0 here is for 'flags' argument... -- Naren. Narendra C. Tulpule Principal Firmware Engineer, Staff 6450 Sequence Dr +1-858-404-2650 San Diego, CA 92121 narendra.c.tulpule at motorola.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ananthashayana at gmail.com Mon Feb 26 12:50:46 2007 From: ananthashayana at gmail.com (Ananthashayana V) Date: Mon, 26 Feb 2007 23:20:46 +0530 Subject: Reading Excel using xlrd package in python Message-ID: <3d8111e50702260950v11e78925gce81956f2df5cd66@mail.gmail.com> Hi John, With reference to your reply to kath http://mail.python.org/pipermail/python-list/2006-October/407157.html I have a small query, my code is as follows #------- Reading excel---------------------------------- import xlrd book = xlrd.open_workbook("E:/test.xls") print "The number of worksheets is", book.nsheets print "Worksheet name(s):", book.sheet_names() sh = book.sheet_by_index(0) for rx in range(sh.nrows): # print sh.row(rx) val = sh.row(rx) print val #------------------------------------------------------------- Now the results are as follows [text:u'test1\xa0', text:u'text1', xldate:39066.0, number:1234.1] [text:u'test2', text:u'text2', xldate:39066.0, number:1234.2] [text:u'test3\xe9', text:u'text3', xldate:39066.0, number:1234.3] [text:u'test4\xe9', text:u'text4', xldate:39066.0, number:1234.4] --------------------------------------------------------------------------------------------- Now as you can clearly observe, I want to: 1. Remove the additional tags like text, xldate, number. 2. Display date in normal form like dd-mm-yyyy, or dd/mm/yyyy or may be yyyy-mm-dd . 3. Finally would like remove the spaces and some UNICODE characters, here its being represented as \xe9 or \xa0 Can you please help me out on this. I would really appreciate it. Thanks in advance. Cheers shayana -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.schmolck at gmail.com Mon Feb 5 13:13:15 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 18:13:15 +0000 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: Robin Becker writes: > Dennis Lee Bieber wrote: > > On Mon, 05 Feb 2007 17:52:27 +0100, Bjoern Schliessmann > > declaimed the following > > in comp.lang.python: > > > > >> Mh, just looking at some "advanced" J source taken from > >> wikipedia.org makes me feel sick: > >> > >> | Here's a J program to calculate the average of a list of numbers: > >> | avg=: +/ % # > >> | avg 1 2 3 4 > >> | 2.5 > >> > > That looks like some variation of APL > > my colleague informs me that it is indeed associated with some of the same > people if not with Mr Iverson. The late Ken Iverson designed both J and APL (he has also written an number of freely downloadable math books using J, see jsoftware.com). 'as From joshbloom at gmail.com Mon Feb 5 20:44:48 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Mon, 5 Feb 2007 18:44:48 -0700 Subject: Python design project In-Reply-To: <1170673772.977486.172770@a75g2000cwd.googlegroups.com> References: <1170337417.236975.44070@l53g2000cwa.googlegroups.com> <45c313d5$0$8726$ed2619ec@ptn-nntp-reader02.plus.net> <1170673772.977486.172770@a75g2000cwd.googlegroups.com> Message-ID: Hi Solrick, This sounds like some interesting stuff. I'd love to discuss it some more with you and maybe work with you on it. Some things to think about: 1. Rules for Font interactions. What happens when fonts 'hit' each other, or 'live' long enough to reproduce andmutate maybe? 2. What parts of the fonts can change. height, width, scale, kerning, serifs, color, transparency, etc 3. Python may not be the best environment for this application. Flash might be alot faster to get something going in as its designed for animating vectors and has a solid programming language behind it to write in your rules logic. Best, Josh On 5 Feb 2007 03:09:33 -0800, solrick51 at hotmail.com wrote: > > I think I need to explain the things better I think, so I do; > > First answering the questions above; I think i have to explain the > project more. > > With type I mean; typography/fonts/characters.. For my final exam I > created the idea to treath fonts as a living organisms. > There for I want to create with the help of somebody, a little program > were i can import vector based fonts, and when they are imported they > "turn alive" > By turn alive I mean; they move random over the work area, opacity > changing, changing of size/color, merge together ans some more things, > little fonts changing. > > Because my python skills are zero, I'm looking for a partner which can > help me. I'm working On mac, but windows is not a problem. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rmcore at gmail.com Sun Feb 18 05:56:53 2007 From: rmcore at gmail.com (Michael Bentley) Date: Sun, 18 Feb 2007 04:56:53 -0600 Subject: conver string to dictionary In-Reply-To: <849825.29475.qm@web53614.mail.yahoo.com> References: <849825.29475.qm@web53614.mail.yahoo.com> Message-ID: <8BF176F1-1929-40B0-B487-63746C0C59E3@gmail.com> On Feb 18, 2007, at 12:44 AM, mahdieh saeed wrote: > I want to convert string to dictionary .what is the best solution > for this ? > for example string is like this: > > '{"SalutationID":["primarykey",8388607,0,None],"CompanyID": > [0,8388607,0,"index"], > "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]}' > > and I want to convert this string to this dictionary: > > {"SalutationID":["primarykey",8388607,0,None],"CompanyID": > [0,8388607,0,"index"], > "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]} # you're the one building the string? a = eval('{"SalutationID":["primarykey",8388607,0,None],"CompanyID": [0,8388607,0,"index"], "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]}') --- A clever person solves a problem. A wise person avoids it. -Albert Einstein -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sun Feb 11 19:57:07 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 11 Feb 2007 16:57:07 -0800 Subject: compound statement from C "?:" In-Reply-To: <1171232208.939808.33890@j27g2000cwj.googlegroups.com> References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> <1171232208.939808.33890@j27g2000cwj.googlegroups.com> Message-ID: <1171241827.381736.31580@s48g2000cws.googlegroups.com> On Feb 11, 5:16 pm, "Holger" wrote: > Thanks all for good input. > It seems like there's no the-python-way for this one. > > Currently I'm forced to use cygwin - and python in cygwin is still not > 2.5 so I can't use the new inline if-else ternary operator. > > > >> if n == 1: > > >> print "I saw a car" > > >> else: > > >> print "I saw %d cars" % n > > Personally I don't like the if-else approach because of the don't- > repeat-yourself philosophy You shouldn't be worried a repeating few characters from a short, simple print statement. It's not a mortal sin. You don't need any ternary operator to avoid repetition, anyways. You could factor the common parts out like this: if n == 1: what = "a car" else: what = "%d cars" % n print "I saw %s" % what but what's the point? It's just a few repeated characters two lines apart. Peter's version is the most easily read version here, including the one using the official ternary operator. Carl Banks From robert.kern at gmail.com Sun Feb 4 00:38:42 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 03 Feb 2007 23:38:42 -0600 Subject: Decimating Excel files In-Reply-To: References: Message-ID: gonzlobo wrote: > No, I don't want to destroy them (funny how the word 'decimate' has > changed definition over the years) :). > > We have a data acquisition program that saves its output to Excel's > .xls format. Unfortunately, the programmer was too stupid to write > files the average user can read. I've had good luck with xlrd. It does not require using COM, Excel, or even Windows! http://www.lexicon.net/sjmachin/xlrd.htm -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bdesth.quelquechose at free.quelquepart.fr Sun Feb 25 16:15:44 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 25 Feb 2007 22:15:44 +0100 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: <45e1f4c9$0$28027$426a34cc@news.free.fr> Troy Melhase a ?crit : >> Why do people sometimes use one leading underscore? > > > Many folks like to use the single leading underscore to emphasize that > the attribute isn't part of the normal way to use the class or > instance. > > It's bad style in my opinion, but I'm probably in the minority. You are, definitively. While it's not technically part of the language syntax, you can practically consider it as such. From maric at aristote.info Wed Feb 14 07:29:08 2007 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Feb 2007 13:29:08 +0100 Subject: replacing substrings within strings In-Reply-To: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> Message-ID: <200702141329.10064.maric@aristote.info> Le mercredi 14 f?vrier 2007 13:08, amadain a ?crit?: > darr=list("010203040506") > aarr=darr[:2] > barr=darr[4:6] > darr[:2]=barr > darr[4:6]=aarr > result="".join(darr) > > The above code works fine but I was wondering if anybody had another > way of doing this? Why not : In [4]: s="010203040506" In [5]: print s[4:6] + s[2:4] + s[0:2] + s[6:] 030201040506 ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 Mobile: +33 632 77 00 21 From sjdevnull at yahoo.com Sun Feb 18 14:59:11 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 18 Feb 2007 11:59:11 -0800 Subject: function & class In-Reply-To: <45d894ac$0$30651$426a74cc@news.free.fr> References: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> <45d894ac$0$30651$426a74cc@news.free.fr> Message-ID: <1171828751.859866.302410@t69g2000cwt.googlegroups.com> Bruno Desthuilliers wrote: > Classes are used to define and create ('instanciate' in OO jargon) Good info from Bruno, just a quick note that it's spelled "instantiate" (I'm not usually big on spelling corrections but since you were teaching a new word I thought it might be worthwile). From jorge.vargas at gmail.com Tue Feb 20 21:27:54 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Tue, 20 Feb 2007 22:27:54 -0400 Subject: BDFL in wikipedia Message-ID: <32822fe60702201827k36f8bd53k69908869a19f00e6@mail.gmail.com> Hi I just hit this page in wikipedia BDFL[1] and it redirected me to Guido's wikipedia[2] entry now without causing any troubles (read flamewar) shouldn't a) that page have an explanation of what BDFL is b) shouldn't it mention Linus, Larry Wall, others?[3] c) for the ones that have been around longer then me who was the first being call like that? [1] http://en.wikipedia.org/wiki/BDFL [2] http://en.wikipedia.org/wiki/Guido_van_Rossum [3] http://www.answers.com/topic/list-of-benevolent-dictators-for-life From loveline17 at gmail.com Wed Feb 28 01:09:04 2007 From: loveline17 at gmail.com (loveline17 at gmail.com) Date: 27 Feb 2007 22:09:04 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172642834.634337.26040@p10g2000cwp.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172642834.634337.26040@p10g2000cwp.googlegroups.com> Message-ID: <1172642944.212763.264630@k78g2000cwa.googlegroups.com> This is my friend's computer, BTW! From mensanator at aol.com Fri Feb 23 13:34:43 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 23 Feb 2007 10:34:43 -0800 Subject: Rational numbers In-Reply-To: <20070223113911.05dcc555@localhost> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> Message-ID: <1172255683.114085.217310@m58g2000cwm.googlegroups.com> On Feb 23, 10:39 am, Martin Manns wrote: > On Fri, 23 Feb 2007 09:52:06 -0600 > > Larry Bates wrote: > > I quick search of Google turned up: > > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p... > >http://calcrpnpy.sourceforge.net/clnum.html > >http://gmpy.sourceforge.net/ > > Sorry that I did not point these out initially. > > + clnum seems to be slower and for speed may be compiled to wrap gmp so > that it is just an additional layer between python and gmp . > > + gmpy is looking pretty unmaintained (dead) to me (newest update of > cvs 10 months ago). Actually, gmpy is being maitained even if SourceForge isn't up to date. I got my gmpy 1.04a for Python 2.5 Windows binary from I haven't used the rationals all that much, but been very happy with them when I have. > > + boost indeed is a quite nice C++ library. However, I fear that I > would end up writing the python wrappers for operators (+ - * / min > max cmp etc.) myself. I would like to avoid this since these operators > should work correctly for any type (not just int and float) and I have > little experience with verifying such generic code. The problems > encountered in the mxNumber wrapper support this notion. > > Martin From Shawn at Milochik.com Thu Feb 8 10:57:44 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Thu, 8 Feb 2007 10:57:44 -0500 Subject: python linux distro In-Reply-To: References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: <2dc0c81b0702080757vc6ab45fwac20df20c81832c9@mail.gmail.com> On 2/8/07, dimitri pater wrote: > Hi, > the world doesn't need another Linux distro, there are too many already... > (> 100) > I believe it's a better idea to spend your time contributing to an existing > distro (e.g. http://www.ubuntu.com/developers/bounties) > doing Python related stuff. Besides that, all distros I know of (4) already > have a lot of Python packages ready for download. > regards, > Dimitri > > You're right, there are too many. Not just over 100, but over 500. As of this week, DistroWatch reports having 528 in their database. Check out DistroWatch.com for details. To the original poster: You may not be a Linux expert, but if you feel like reading some documentation, you can easily remaster a live CD such as Knoppix or DSL (Damn Small Linux). Just to to the distro's site and check out the documentation. This won't be the creation of a brand-new distro -- it's the same thing as changing the wallpaper and creating your custom re-master just for yourself. Both distros I mentioned (and many others, I'm sure) have a simple, built-in tool for installing additional packages. Do that, then make your re-image from your running live version. Shawn From geoffrey.clementsNO at SPAMbaesystems.com Fri Feb 2 09:35:29 2007 From: geoffrey.clementsNO at SPAMbaesystems.com (Geoffrey Clements) Date: Fri, 2 Feb 2007 14:35:29 -0000 Subject: How do I print out in the standard output coloured lines References: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> <1170419225.989358.311600@h3g2000cwc.googlegroups.com> <1170421768.302283.173170@a34g2000cwb.googlegroups.com> Message-ID: <45c3490a$1_1@glkas0286.greenlnk.net> wrote in message news:1170421768.302283.173170 at a34g2000cwb.googlegroups.com... On Feb 2, 1:38 pm, rzed wrote: > cnihar... at gmail.com wrote > innews:1170419225.989358.311600 at h3g2000cwc.googlegroups.com: > > > > > On Feb 2, 1:16 pm, rzed wrote: > >> cnihar... at gmail.com wrote > >> innews:1170417631.268771.108090 at v45g2000cwv.googlegroups.com: > > >> > Hi, > > >> > I'm interested in printing out coloured lines of my > >> > application and > >> > I don't know what to use. Can anybody give me an idea?? > [snip] > > If you're on Linux, you could use the curses module. There may be > a precompiled Windows version compatible with your Python version, > or maybe not, but the Windows source is available, and you may be > able to get it to work with your Python with some effort. Linux > distros include curses, I think. For Windows curses, take a look > at . You will understand why > the phrase "Windows curses" is used, I expect. > > -- > rzed > > Yes, I'm on a Linux box. I've tried with the curses module, but I > don't how I could fetch the current use of curses of my shell. I don't > know if I'm talking about something impossible. I've made some tests > with the curses module and works fine, but I need to capture the > current window and change the attributes of texts. You may find the following useful, it's from Gentoo's portage: http://sources.gentoo.org/viewcvs.py/portage/main/trunk/pym/portage/output.py?rev=5780&view=markup -- Geoff From thinker at branda.to Mon Feb 26 11:44:55 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 00:44:55 +0800 Subject: Interactive os.environ vs. os.environ in script In-Reply-To: <1172504983.452208.182490@p10g2000cwp.googlegroups.com> References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> Message-ID: <45E30E87.8010805@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 boris.smirnov at gmail.com wrote: > > OK then I have to reformulate my question. :) > > In my script I have a line with > > os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > > but this line didn't work. But when I set this environment variable > in Linux shell it works. Here is a small example. > >> python shrink_bs_070226.py > Traceback (most recent call last): File "shrink_bs_070226.py", line > 25, in ? from qt import * File > "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ qt.py", > line 46, in ? import libsip ImportError: libadamsqt.so: cannot open > shared object file: No such file or directory ld-elf.so reads environment variables when it was loaded. It never reads environment variables again! That you setting environment in the process does not make link-editor to re-read environment variable and take effect. To resolve the problem, you can try to add the path to sys.path. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4w6H1LDUVnWfY8gRAoI0AKCLikYsFU2N6aaOZFDd1L2KY8DjqACg3QQn KsEEcrvpw1CktEkVCKe/ojk= =EQG6 -----END PGP SIGNATURE----- From nagle at animats.com Sun Feb 25 17:07:38 2007 From: nagle at animats.com (John Nagle) Date: Sun, 25 Feb 2007 22:07:38 GMT Subject: Weakref problem: no way to get original object from proxy object? Message-ID: Is there some way to get a strong ref to the original object back from a weakref proxy object? I can't find any Python function to do this. ".ref()" doesn't work on proxy objects. John Nagle From NikitaTheSpider at gmail.com Thu Feb 1 12:55:16 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 01 Feb 2007 12:55:16 -0500 Subject: Marangozov's shmmodule (System V shared memory for Python IPC) Message-ID: Hi all, In the late 90s Vladimir Marangozov wrote a module that provided an interface to System V shared memory on *nix platforms. I found a copy on the Net, dusted it off, compiled it, plugged a couple of memory leaks, intergrated others' changes, etc. Vlad hasn't posted on Usenet since the summer of 2000 and I can't find a working email address for him, so I assume this module is orphaned; this is a last-ditch effort to track him down before I post the module with my changes (retaining his name as the author of 99.9% of the code, of course). Does anyone know where I can contact Vladimir? The email addresses I can find for him don't work. If anyone knows him personally and would be kind enough to forward my email address (NikitaTheSpider at gmail.com) to him, I'd appreciate it. Thanks -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From manstey at csu.edu.au Fri Feb 2 16:53:21 2007 From: manstey at csu.edu.au (manstey) Date: 2 Feb 2007 13:53:21 -0800 Subject: parent-child object design question In-Reply-To: References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> <1170284969.902118.155570@l53g2000cwa.googlegroups.com> Message-ID: <1170453201.616987.65340@k78g2000cwa.googlegroups.com> Hi, There was a mistake above, and then I'll explain what we're doing: >>> insCacheClass = CacheClass(oref) >>> insCacheProperty = CacheProperty(insOref,'Chapter') should have been >>> insCacheClass = CacheClass(oref) >>> insCacheProperty = CacheProperty(insCacheClass ,'Chapter') Now, to answer some questions. 1. Cache refers to Intersystems Cache database, an powerful oo dbase that holds our data. 2. It comes with a pythonbinding, but unfortunatley the API, written in C as a python extension, only provides old-style classes, which is why we wrap the oref (an in-memory instance of a Cache class/table) with CacheClass. This allows us to add attributes and methods to the CacheClass, the most important being CacheProperty, which is a class corresponding to the Cache property/field classes of the dbase. 3. The pythonbind also has a strange behaviour, to our view. It gets and sets values of its properties (which are classes), via the 'parent' oref, i.e. oref.set('Name','Peter'). But we want a pythonic way to interact with Cache, such as, insCacheClass.Name='Peter'. and insOref.Name.Set(). The code above (in post 7) does this, but as I asked, by storing the parent instance (insCacheClass) inside each of its attributes (insCacheProperty1,2, etc). 4. Another reason we want a new-style class wrapped around the oref, is that each oref has many methods on the server-side Cache database, but they are all called the same way, namely, oref.run_obj_method('%METHODNAME',[lisArgs]). We want to call these in python in the much better insCacheClass.METHODNAME(Args). E.g. we prefer insCacheClass.Save() to oref.run_obj_method('%Save',[None]). More importantly, the in-memory version of Cache lists and arrays are Cache lists and arrays, but these are not Python lists and dictionaries, but they can be easily converted into them. So having a class for each dbase property allows us to have Cache on disk (server), get the Cache list/array to python in memory, but still in Cache dataformat (e.g. %ListOfDataTypes) and convert it to a python list. Tweaking the set and get methods then lets us use python lists and dics without ever worrying about cache dataformat. I hope this clarifies what we are doing. We are not experienced programmers, but we want to do it this way. From arkanes at gmail.com Thu Feb 22 13:45:31 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 22 Feb 2007 12:45:31 -0600 Subject: Possible to set cpython heap size? In-Reply-To: <1172166768.967422.225960@p10g2000cwp.googlegroups.com> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <5462tbF1vfhfrU1@mid.uni-berlin.de> <1172166768.967422.225960@p10g2000cwp.googlegroups.com> Message-ID: <4866bea60702221045s586e2cbcu3795cee8ab98090@mail.gmail.com> On 22 Feb 2007 09:52:49 -0800, Andy Watson wrote: > > Why do you want that? And no, it is not possible. And to be honest: > I have > > no idea why e.g. the JVM allows for this. > > > > Diez > > The reason why is simply that I know roughly how much memory I'm going > to need, and cpython seems to be taking a fair amount of time > extending its heap as I read in content incrementally. > To my knowledge, no modern OS actually commits any memory at all to a process until it is written to. Pre-extending the heap would either a) do nothing, because it'd be essentially a noop, or b) would take at least long as doing it incrementally (because Python would need to fill up all that space with objects), without giving you any actual performance gain when you fill the object space "for real". In Java, as I understand it, having a fixed size heap allows some optimizations in the garbage collector. Pythons GC model is different and, as far as I know, is unlikely to benefit from this. From tinaweb at bestemselv.com Fri Feb 9 01:34:59 2007 From: tinaweb at bestemselv.com (Tina I) Date: Fri, 09 Feb 2007 07:34:59 +0100 Subject: Newbie Question In-Reply-To: <1170994729.917461.6460@p10g2000cwp.googlegroups.com> References: <1170980835.761703.163120@j27g2000cwj.googlegroups.com> <1170994729.917461.6460@p10g2000cwp.googlegroups.com> Message-ID: azrael wrote: > but look out for pyqt. there is one thing in the eula i don't like. > there is written that if you use qtWidgets and they like the > aplication, you have to give up all your rights of the aplication. > patent, idea, money everything is gone. i know this is open source, > but maybe one day i will manage to sell an apliction for big money. That is not exactly correct. Both PyQt and Qt it self is available under two different licenses. The GPL versions require that your applications has to be released as free software compatible with the GPL. Development of commercial closed source applications require a commercial license. In reality you are free to sell your application as long as it remain free (as in freedom) and open source (some argues this is impossible and some argue it's no problem. Decide for your self). By nature a GPL'ed application can not be patented or even contain patented code as this violates the freedom part of the License. But you have a point though: Always read the license, terms and conditions for the tools you want to use. It can really save you some serious trouble. From gigs at hi.t-com.hr Thu Feb 15 12:56:10 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 15 Feb 2007 18:56:10 +0100 Subject: TKinter newbie Message-ID: Hi Im new to gui programming from Tkinter import * # get widget classes from tkMessageBox import askokcancel # get canned std dialog class Quitter(Frame): # subclass our GUI def __init__(self, parent=None): # constructor method Frame.__init__(self, parent) self.pack() widget = Button(self, text='Quit', command=self.quit) widget.pack(side=LEFT) def quit(self): ans = askokcancel('Verify exit', "Really quit?") if ans: Frame.quit(self) class Demo(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack() Label(self, text="Basic demos").pack() for (key, value) in demos.items(): func = (lambda key=key: self.printit(key)) Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) Quitter(self).pack() # here def printit(self, name): print name, 'returns =>', demos[name]() My problem is in class Demo. How is the best way to use class Quitter in class Demo? should it be: Quitter(self).pack() Quitter(self) ... From hg at nospam.org Thu Feb 22 12:44:26 2007 From: hg at nospam.org (hg) Date: Thu, 22 Feb 2007 18:44:26 +0100 Subject: What is the best queue implemetation in Python? References: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> Message-ID: hg wrote: > f u "f o" of course From jjl at pobox.com Sat Feb 10 07:31:09 2007 From: jjl at pobox.com (John J. Lee) Date: 10 Feb 2007 12:31:09 +0000 Subject: Create a cookie with cookielib References: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> Message-ID: I'm going to post this if it kills me (this was my first response in this thread, my normal newsfeed has gone bad so can't post reliably...) Alessandro Fachin writes: > Hi, i am trying to forge a new cookie by own with cookielib. But i don't > still have success. This a simply code: > > import cookielib, urllib, urllib2 > login = 'Ia am a cookie!' > cookiejar = cookielib.CookieJar() > urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) > values = {'user':login} > data = urllib.urlencode(values) > request = urllib2.Request("http://localhost/cookie.php", data) > url = urlOpener.open(request) > print url.info() > page = url.read(500000) > print page > print cookiejar > > the output of this is: > > Date: Sat, 03 Feb 2007 10:20:05 GMT > Server: Apache > X-Powered-By: PHP/5.1.6 > Set-Cookie: user=Alex+Porter; expires=Sat, 03-Feb-2007 11:20:05 GMT > Content-Length: 11 > Connection: close > Content-Type: text/html; charset=UTF-8 > > Array > ( > ) > ]> So the server has sent you a cookie back, and cookielib accepted it. Success! What your PHP program prints out is information about cookies that were received *from* the browser (or from your script, in this case). It does not print information about cookies that it is sending *to* the browser. Your PHP program is not a time machine, so it can't print out information about a cookie that was *not there* in the request you sent. And the cookie was not there in the request you sent because the server hadn't sent the cookie yet! Send a second request (either in the same run of your program, or by saving and loading the cookies), and you should see a cookie sent back to the server (and then printed out by your PHP script in the response you get back). Web sites and web applcations sometimes use a trick like a using a redirect or "Refresh" to get the browser to send a second request, so that they get the cookie they set sent back to the server again, without the user needing to perform any second action. Also note that saving and loading cookies with cookielib will by default drop "session cookies", unless you explicitly ask otherwise. John From gagsl-py at yahoo.com.ar Mon Feb 5 19:31:50 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 21:31:50 -0300 Subject: get objects referencing another one References: <45C7545B.7010809@gmail.com> Message-ID: En Mon, 05 Feb 2007 12:59:23 -0300, Olivier Feys escribi?: > I'm working on a tree and I have refcounting problems. > Is it possible from an object, to get the list of objects referencing it > ? Try gc.get_referrers -- Gabriel Genellina From paddy3118 at googlemail.com Sun Feb 25 12:20:46 2007 From: paddy3118 at googlemail.com (Paddy) Date: 25 Feb 2007 09:20:46 -0800 Subject: Referencing Items in a List of Tuples In-Reply-To: References: Message-ID: <1172424046.323933.85250@q2g2000cwa.googlegroups.com> On Feb 25, 2:01 am, rshep... at nospam.appl-ecosys.com wrote: > While working with lists of tuples is probably very common, none of my > five Python books or a Google search tell me how to refer to specific items > in each tuple. I find references to sorting a list of tuples, but not > extracting tuples based on their content. > > In my case, I have a list of 9 tuples. Each tuple has 30 items. The first > two items are 3-character strings, the remaining 28 itmes are floats. > > I want to create a new list from each tuple. But, I want the selection of > tuples, and their assignment to the new list, to be based on the values of > the first two items in each tuple. > > If I try, for example, writing: > > for item in mainlist: > if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': > ec.Append(mainlist[item][2:]) > > python doesn't like a non-numeric index. > > I would really appreciate a pointer so I can learn how to manipulate lists > of tuples by referencing specific items in each tuple (string or float). > > Rich You might also use list comprehensions to accumulate the values you need: ec = [ item[2:] for item in mainlist if item[:2] == ['eco','con'] ] - Paddy. From kavithapython at yahoo.co.in Mon Feb 26 09:55:22 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Mon, 26 Feb 2007 14:55:22 +0000 (GMT) Subject: newbie question(file-delete trailing comma) In-Reply-To: <8783.11481.qm@web31110.mail.mud.yahoo.com> Message-ID: <729614.98659.qm@web7811.mail.in.yahoo.com> the input file what i have is already opened with write mode. say i have a file input.txt which has a,b,c,d, and i need the output also in the same input.txt,,ie., the trailing comma in the input.txt file should be deleted,,,i dont need a file output.txt,,, is there a way?? kavitha Mohammad Tayseer wrote: ok, it should be ---------- import sys in_file = open(sys.argv[1]) out_file = open(sys.argv[2], 'w') for line in in_file: print >> out_file, line.strip().strip(',') ---------- strip(',') will remove the ',' char from the beginning & end of the string, not the middle. empty strip() will remove whitespaces from the beginning & end of the string I hope this solves your problem kavitha thankaian wrote: hi i would like to have the output as follows: a,b,c,d a1,b1,c1,d1 a2,b2,c2,d2 i would like to delete only the comma at the end and not the commas inbetween. thanks,,, --------------------------------- Any questions? Get answers on any topic at Yahoo! Answers. Try it now. --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mark.Geyzer at gmail.com Sun Feb 11 07:39:34 2007 From: Mark.Geyzer at gmail.com (volcano) Date: 11 Feb 2007 04:39:34 -0800 Subject: How to access an absolute address through Python? In-Reply-To: References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> Message-ID: <1171197574.776135.96980@k78g2000cwa.googlegroups.com> On Feb 11, 2:21 pm, Ma?l Benjamin Mettler wrote: > volcano schrieb: > > > Can it be done, and if yes - how? > > Define address. Are you talking about URLs? File paths? Postal > addresses? Memory addresses? Whatever addresses? > I'm afraid the people on this list can't read your thoughts... I presumed that "absolute" address somehow qualifies my question. If it is not - I was talking about physical computer memory, on PC - to be more specific. From aahz at pythoncraft.com Wed Feb 21 13:44:09 2007 From: aahz at pythoncraft.com (Aahz) Date: 21 Feb 2007 10:44:09 -0800 Subject: Python 3.0 unfit for serious work? References: <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> <1172043626.705209.14870@v45g2000cwv.googlegroups.com> Message-ID: In article <1172043626.705209.14870 at v45g2000cwv.googlegroups.com>, Jay Tee wrote: > >If backwards compatibility is not a consideration, then it would be a >miracle if there were no problems. Backwards compatibility is a consideration AND there will be problems. That is, the goal of 3.0 is to lower the priority of backwards compatibility enough to make some incompatible changes, but not to reduce the priority of compatibility to zero. Just for example, "foo" will become a Unicode string. Note that I believe it will be many years, perhaps even a decade, before "python" on a Unix system starts up Python 3.0. Python 2.x will have at least two releases after 3.0 gets released, and I can't imagine that any OS will have "python" refer to 3.0 while 2.x is still under active development or even for a while after. I'd expect any OS to provide a python3. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From steve at holdenweb.com Sun Feb 18 09:33:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 18 Feb 2007 09:33:24 -0500 Subject: Approaches of interprocess communication In-Reply-To: <1171738855.785792@bubbleator.drizzle.com> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <87fy965plq.fsf@benfinney.id.au> <1171738855.785792@bubbleator.drizzle.com> Message-ID: Donn Cave wrote: > Quoth Steve Holden : > | Ben Finney wrote: > ... > | > If a programmer decides on behalf of the user that "localhost" should > | > be treated specially, that programmer is making an error. > | > | Inter-process TCP/IP communication between two processes on the same > | host invariably uses the loopback interface (network 127.0.0.0). > | According to standards, all addresses in that network space refer to the > | local host, though 127.0.0.1 is conventionally used. > | > | The transmit driver for the loopback interface receives a datagram from > | the local network layer and immediately announces its reception back to > | the local network layer. > > Are you saying, in that first paragraph, that if for example I telnet to > my local host's external IP address, to a service that bound explicitly to > the external interface -- I'll actually be going through the loopback > interface anyway, invariably regardless of host network implementation? > I wasn't specifically saying that, no. However on Solaris I have observed local connections to an external interface actually increasing the packet count on the loopback, but I can't confirm whether those connections were to services specifically bound only to the external interface. Certainly on Windows XP there is a host-specific route via 127.0.0.1 to the external interfaces as well as the network route via the external interface. I wouldn't necessarily expect this to extend to other platforms. This is demonstrated by the following output from "route print". I have chopped the metric column to avoid line wrapping. ===================================================================== Active Routes: Network Destination Netmask Gateway Interface 0.0.0.0 0.0.0.0 192.168.123.254 192.168.123.123 127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 192.168.123.0 255.255.255.0 192.168.123.123 192.168.123.123 192.168.123.123 255.255.255.255 127.0.0.1 127.0.0.1 192.168.123.255 255.255.255.255 192.168.123.123 192.168.123.123 192.168.174.0 255.255.255.0 192.168.174.1 192.168.174.1 192.168.174.1 255.255.255.255 127.0.0.1 127.0.0.1 192.168.174.255 255.255.255.255 192.168.174.1 192.168.174.1 224.0.0.0 240.0.0.0 192.168.123.123 192.168.123.123 224.0.0.0 240.0.0.0 192.168.174.1 192.168.174.1 255.255.255.255 255.255.255.255 192.168.123.123 3 255.255.255.255 255.255.255.255 192.168.123.123 192.168.123.123 255.255.255.255 255.255.255.255 192.168.174.1 192.168.174.1 Default Gateway: 192.168.123.254 ===================================================================== regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From wattersmt at gmail.com Tue Feb 6 14:44:52 2007 From: wattersmt at gmail.com (wattersmt at gmail.com) Date: 6 Feb 2007 11:44:52 -0800 Subject: Running long script in the background In-Reply-To: References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170769014.352466.135280@h3g2000cwc.googlegroups.com> <1170776253.027044.253050@q2g2000cwa.googlegroups.com> Message-ID: <1170791092.333254.279680@q2g2000cwa.googlegroups.com> On Feb 6, 2:02 pm, Dennis Lee Bieber wrote: > On 6 Feb 2007 07:37:33 -0800, "watter... at gmail.com" > declaimed the following in comp.lang.python: > > > > > Everything works fine until I call the popen function, then it > > freezes. What I want is to print the output in real time, just like > > it does when I run it from a shell. > > And you want /this/ in a web page? > > I don't think HTTP is designed for that... As I understand it, it > expects to get a complete page back and then the transaction is complete > and forgotten (except for the presence of session cookies). To report > dynamically on a web page tends to either be something like a > timed-redirect (reload) of the same URL with the cookie, and that is a > completely separate transaction starting a new CGI (or equivalent) > process. AJAX techniques may clean up some of this -- by not really > reloading the whole page, instead updating the DOM based upon data > transferred. Web pages can show output as it's sent. For testing I created a script on the server that untars a 600 meg volume, I can see each file name show up in my browser instantly, just like it should. The other script I'm trying to run won't show anything until the entire process is complete and it's just a bunch of echo statements in a for loop, I'm not sure why they behave differently. From bdesth.quelquechose at free.quelquepart.fr Tue Feb 6 14:36:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 20:36:10 +0100 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170780175.118806.11700@k78g2000cwa.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> Message-ID: <45c8d18d$0$418$426a34cc@news.free.fr> jeremito a ?crit : > On Feb 6, 10:59 am, "bruno.desthuilli... at gmail.com" > wrote: > >>On 6 f?v, 16:23, "jeremito" wrote: >> (snip) >>>But I can't even get __setitem__ to run. >> >>of course, since your __new__ method returns a dict instance, not a xs >>instance... >>There are very few cases where you really need to override the __new__ >>method. > > > The reason I create my object with __new__ instead of __init__ is > because when I use __init__ when a value is set it calls __setitem__. > This is what I want to happen, but not inside of __init__. Does this > make sense? It would make sens - if you couldn't call dict.__setitem__ directly. > I'm sure there is a better/more pythonic way to do this, > but I'm unsure of what it is. Can someone show me an example of how > this should work? > > (snip) >>>Is this what the __setitem__ method is for? >> >>Yes. But note that you you need to manually call the superclass's >>overriden method - unless you >>really want to replace it with your own, which is obviously not the >>case here... >> >>Note that if someone manually changes the values of xG, xF, or xS, the >>computed values of xA and/or xT >>won't reflect this change. Is that what you want ? >> > > > Eventually (when I figure out how to use __setitem__) I will change > what happens when xG, xF, or xS are changed so that it also changes xA > and xT. Which is not the best way to go IMHO. Unless the computation is very intensive (which doesn't seem to be the case here) or it's heavily used in big loops *and* the perfs are not good enough, it's better to recompute on the fly at read time. And if one of the above cases arises, then it will be time to use memoization (ie: cache the result of computation, invalidating the cache when needed). > >>Finally, and if I may ask, what is your use-case for subclassing >>dict ? You don't need this to implement a dict-like object, >>and it might be simpler in your case to write an ordinary class, then >>add support for the required subset of the dict interface. > > > Eventually I am going to add other features to my class (as I have > mentioned) so I can't simply use a dict object. I already understood this. My question is : why do you want to *subclass* dict. In Python, inheritence is only about implementation, it's *not* needed for polymorphism to work. So you don't have to subclass dict to have an object behaving (more or less, that's up to you) like a dict. Here's an alternative implementation, so you get the idea. Note that it behaves mostly like a dict (well, not totally, but since we don't know which subset of the dict interface you need...), but also like a 'standard' object, so you can use either cs.['xT'] or cs.xT with the same result. class Xs(dict): """ Xs is a container object to hold information about cross sections. """ _computedkeys = 'xA', 'xT' def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): self.xS = xS self.xF = xF self.xG = xG self.nu = nu # xA and xT as properties (AKA computed attributes) def _get_xA(self): return self.xG + self.xF def _set_xA(self, dummy): raise AttributeError( "%s.xA is read-only" % self.__class__.__name__ ) xA = property(fset=_set_xA, fget=_get_xA) def _get_xT(self): return self.xA + self.xS def _set_xT(self, dummy): raise AttributeError( "%s.xT is read-only" % self.__class__.__name__ ) xT = property(fset=_set_xT, fget=_get_xT) # dict interface support, to be extended if needed def __setitem__(self, key, value): setattr(self, key, value) def __getitem__(self, key): return getattr(self, key) def keys(self): return self.__dict__.keys() + list(self._computedkeys) def values(self): return self.__dict__.values() \ + [getattr(self, key) for key in self._computedkeys] def items(self): return zip(self.keys(), self.values()) def __iter__(self): for k in self.keys(): yield k raise StopIteration def __contains__(self, key): return key in self.keys() def __repr__(self): return repr(dict(self.items())) From simon at brunningonline.net Mon Feb 5 06:36:52 2007 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 5 Feb 2007 11:36:52 +0000 Subject: Question In-Reply-To: <743068.47814.qm@web37312.mail.mud.yahoo.com> References: <743068.47814.qm@web37312.mail.mud.yahoo.com> Message-ID: <8c7f10c60702050336m68f703b7ta54113347e65d1c3@mail.gmail.com> On 2/4/07, Magdy Sanad wrote: > I have certain data in the default file format ( GADGET ) . > > I Will be appreciated if you guide me to read these data > > under Python ? You'd probably get more help if you told people what GADGET is. ;-) Are you talking about this - ? If so, then a quick Google doesn't reveal anything pre-built. But then, "gadget" is a pretty appalling product name to Google for - *so* many hits for that word! There's a run-down on the file format here, though - , so you might be able to write your own using the struct module. Good luck! -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From nagle at animats.com Tue Feb 20 20:59:36 2007 From: nagle at animats.com (John Nagle) Date: Wed, 21 Feb 2007 01:59:36 GMT Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> Message-ID: Steven Bethard wrote: > So as a Python programmer, the path is clear. As soon as possible, you > should make your code compatible with Python 3.0. There's always the possiblity that Python 3 won't happen. Look at what happened with Perl 6. That's been talked about for seven years now. The user base just wasn't interested. Perl 5 was good enough, and users migrated to PHP for the little stuff and other languages for the bigger stuff. As Wikipedia says, "As of 2007, Perl 6 was still under development, with no planned completion date." John Nagle From mizipzor at gmail.com Sun Feb 4 17:47:54 2007 From: mizipzor at gmail.com (Mizipzor) Date: 4 Feb 2007 14:47:54 -0800 Subject: Unicode problem in BeautifulSoup; worked in Python 2.4, fails in Python 2.5. In-Reply-To: References: <5aoxh.7440$gJ1.6708@newsfe17.lga> <1170618799.354069.327210@h3g2000cwc.googlegroups.com> Message-ID: <1170629274.707445.143350@p10g2000cwp.googlegroups.com> On Feb 4, 11:39 pm, John Nagle wrote: > I'm running a website page through BeautifulSoup. It parses OK > with Python 2.4, but Python 2.5 fails with an exception: > > Traceback (most recent call last): > File "./sitetruth/InfoSitePage.py", line 268, in httpfetch > self.pagetree = BeautifulSoup.BeautifulSoup(sitetext) # parse into tree form > File "./sitetruth/BeautifulSoup.py", line 1326, in __init__ > BeautifulStoneSoup.__init__(self, *args, **kwargs) > File "./sitetruth/BeautifulSoup.py", line 973, in __init__ > self._feed() > File "./sitetruth/BeautifulSoup.py", line 998, in _feed > SGMLParser.feed(self, markup or "") > File "/usr/lib/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib/python2.5/sgmllib.py", line 291, in parse_starttag > self.finish_starttag(tag, attrs) > File "/usr/lib/python2.5/sgmllib.py", line 340, in finish_starttag > self.handle_starttag(tag, method, attrs) > File "/usr/lib/python2.5/sgmllib.py", line 376, in handle_starttag > method(attrs) > File "./sitetruth/BeautifulSoup.py", line 1416, in start_meta > self._feed(self.declaredHTMLEncoding) > File "./sitetruth/BeautifulSoup.py", line 998, in _feed > SGMLParser.feed(self, markup or "") > File "/usr/lib/python2.5/sgmllib.py", line 99, in feed > self.goahead(0) > File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead > k = self.parse_starttag(i) > File "/usr/lib/python2.5/sgmllib.py", line 285, in parse_starttag > self._convert_ref, attrvalue) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: ordinal > not in range(128) > > The code that's failing is in "_convert_ref", which is new in Python 2.5. > That function wasn't present in 2.4. I think the code is trying to > handle single quotes inside of double quotes, or something like that. > > To replicate, run > > http://www.bankofamerica.com > or > http://www.gm.com > > through BeautifulSoup. > > Something about this code doesn't like big companies. Web sites of smaller > companies are going through OK. > > Also reported as a bug: > > [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 > > John Nagle I think this post got rather missplaced, hehe. From bblais at bryant.edu Thu Feb 22 21:55:35 2007 From: bblais at bryant.edu (Brian Blais) Date: Thu, 22 Feb 2007 21:55:35 -0500 Subject: CherryPy/Turbogears on server not controlled by me In-Reply-To: <32822fe60702211458u15b0e9a6r6217d8b55c0260f5@mail.gmail.com> References: <45DAF7F0.1080503@bryant.edu> <32822fe60702211458u15b0e9a6r6217d8b55c0260f5@mail.gmail.com> Message-ID: <45DE57A7.7000607@bryant.edu> Jorge Vargas wrote: > On 2/20/07, Brian Blais wrote: >> I was wondering if there is a way to run CherryPy/Turbogears on a >> server that I don't >> have root access to. > > I have never run ANY webapp as root. you should follow that advice. in > fact don't run any server as root. > Oh, I didn't mean to imply that! But, at the same time, I can't update the apache server to include python_mod, or apache forwarding to the cherry py server without root access. Is there a standard port to use, when you have to specify the port on the url? bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From bdesth.quelquechose at free.quelquepart.fr Sun Feb 4 16:32:44 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Feb 2007 22:32:44 +0100 Subject: How can I access data from MS Access? In-Reply-To: References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> <45c4bee4$0$453$426a74cc@news.free.fr> <1170522973.012926.252510@k78g2000cwa.googlegroups.com> Message-ID: <45c649ed$0$5159$426a34cc@news.free.fr> Peter Otten a ?crit : > Finger.Octopus at gmail.com wrote: > > >>On Feb 3, 10:27 pm, Bruno Desthuilliers > > >>>"doesn't work" is the worst possible description of a problem. Did it >>>print out some insults in a foreign language ? wipe out your HD ? Else ? > > > >>I havn't said "doesn't work", I rather doesn't seem to work. > > > Bruno, admit that you were wrong. Finger.Octopus is able to give a > description that is even worse than what you deemed possible :-) Peter, I sadly admit that I was wrong. "Doesn't seem to work" is effectivly even more useless than "doesn't work". I give up. From kylotan at gmail.com Tue Feb 6 07:45:35 2007 From: kylotan at gmail.com (Ben Sizer) Date: 6 Feb 2007 04:45:35 -0800 Subject: when will python 2.5 take in mainstream? In-Reply-To: References: Message-ID: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> On Feb 5, 4:15 pm, Jean-Paul Calderone wrote: > It's very easy to maintain compatibility in the C API. I'm much more > interested in compatibility at the Python layer, which is changed > incompatibly much, much more frequently than is the C layer. Really? In all cases I've found, pure-Python extensions written for 2.4 work with 2.5. The same was true for 2.3 to 2.4 as well. And even if I found one that didn't, it's highly likely I could fix it myself. The same doesn't apply to any C compiled extensions. Updating Python breaks these, every time, and users typically have to wait months for the library developer to compile a new version, every time. Or maybe they can wade through the morass of "how do I compile this library on Windows" threads here. Perhaps the C API remains the same but the real issue is the binary API between extensions and Python changes every couple of years or so. That's why I run 2.4 anywhere that needs extensions. It would be great if someone could invest some time in trying to fix this problem. I don't think I know of any other languages that require recompilation of libraries for every minor version increase. -- Ben Sizer From piet at cs.uu.nl Tue Feb 20 06:40:09 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 20 Feb 2007 12:40:09 +0100 Subject: Django, one more newbie question References: Message-ID: >>>>> Boris Ozegovic (BO) wrote: >BO> Umm, can somebody tell me which language is this one: >BO> {% if latest_poll_list %} >BO>
    >BO> {% for poll in latest_poll_list %} >BO>
  • {{ poll.question }}
  • >BO> {% endfor %} >BO>
>BO> {% else %} >BO>

No polls are available.

>BO> {% endif %} >BO> Whole tutorial is on this page: >BO> http://www.djangoproject.com/documentation/tutorial3/ >BO> endfor, endif, {{? :) It is the Django template language. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From http Wed Feb 14 22:04:08 2007 From: http (Paul Rubin) Date: 14 Feb 2007 19:04:08 -0800 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> <7xr6ssqis8.fsf@ruckus.brouhaha.com> <7x4ppo6s59.fsf@ruckus.brouhaha.com> Message-ID: <7xzm7g5dg7.fsf@ruckus.brouhaha.com> Paul Rubin writes: > Re your other post: yes, PEP 363 explains how the "with" statement Whoops, 343. From webraviteja at gmail.com Thu Feb 1 11:53:55 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 1 Feb 2007 08:53:55 -0800 Subject: Help me with this!!! In-Reply-To: <1170337596.369951.12310@m58g2000cwm.googlegroups.com> References: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> <1170337596.369951.12310@m58g2000cwm.googlegroups.com> Message-ID: <1170348835.689256.184420@k78g2000cwa.googlegroups.com> > > > It search a text inside that hex value. > > > It works perfecly on a txt file but if I open a binary file (.exe,.bin > > > ecc...) with the same value it wont work, why? > > > Please help! > > > Because the pattern isn't in the file, perhaps. > > This pattern IS in the file (I made it and I double check with an hex > editor). > It display the file correcltly (print line) but... No! Peter is right. Regular expressions match ASCII representation of data, not hex. In simple terms, do you see your pattern when you open the file in notepad (or other text editor)? You do not use regex to search binary files. Ravi Teja. From steve at holdenweb.com Sun Feb 18 09:55:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 18 Feb 2007 09:55:15 -0500 Subject: Dlls In-Reply-To: <1ea031080702180356p2c1a8167jd5470832b5c6315f@mail.gmail.com> References: <1ea031080702180356p2c1a8167jd5470832b5c6315f@mail.gmail.com> Message-ID: Jason Ward wrote: > Hi. I am interested to know why python can't access DLL files directly. > It seems to me that because python can't access DLL's directly we have to > waste our time and write wrappers around libraries that have already > been written. > > So if the python developers were to implement say this. > > import MYDLL.dll > > Then we would be able to do everything with that library that we can do > in other languages. > > For eg. I want to use PyOpenGL. But the problem is the library hasn't > got all the opengl functions implemented. > So I can either develop quickly with an incomplete library or develop > slowly in assembler. > I mean really, in asm we just call the dll function directly. > > Why must python be different? > That's a bit like asking why you can't put the engine from a BMW into an Audi. The answer is, of course, that you can - it just required a lot of work to adapt the engine to a foreign environment. You might be interested in the ctypes module - see http://docs.python.org/lib/module-ctypes.html That does more or less what you are asking for, but you can't expect to be able to call arbitrary functions written in one language from another - there's just too much variability in the way that data are represented in different languages. There are, of course, systems like mono (.NET) that provide compilers for multiple languages with the specific goal of interoperability, but in general there will be an "impedance mismatch" that you will need to code around. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From paul at boddie.org.uk Tue Feb 27 05:45:56 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Feb 2007 02:45:56 -0800 Subject: JasperServer In-Reply-To: <1172568932.016387.270820@q2g2000cwa.googlegroups.com> References: <1172168543.975485.238770@a75g2000cwd.googlegroups.com> <1172568932.016387.270820@q2g2000cwa.googlegroups.com> Message-ID: <1172573156.314871.61840@8g2000cwh.googlegroups.com> On 27 Feb, 10:35, "copermine" wrote: > On Feb 22, 8:22 pm, "batok" wrote: > > > JasperServeris a report engine ( java based ). It has asoap > > interface. Does anybody has usedJasperserverviaSoap? > > > An example would be appreciated. > > What do you need exactly? I guess the inquirer is looking for some recommendations for a Python SOAP library that can communicate successfully with JasperServer. I'd certainly be interested in hearing people's SOAP library recommendations (for both clients and servers), and it would be even nicer if someone wrote those recommendations up on the Python Wiki: http://wiki.python.org/moin/WebServices Paul From bdesth.quelquechose at free.quelquepart.fr Sun Feb 18 08:56:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 18 Feb 2007 14:56:18 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: <45d85388$0$29060$426a74cc@news.free.fr> Stef Mientki a ?crit : (snip) > I'm not an (educated) programmer, so I don't always use the right terms :-( > If I look at a well established program like DIA, > and see that it still can't repaint it's screen always correctly, ... I suppose you're talking about the Diagram drawing program Dia. If so, I don't see how it is relevant to Python GUI programming since Dia is written in C with the GTK toolkit. The stability problems you experience have probably more to do with the status of the Windows port of GTK (which is originally a X toolkit). > I've been using Python for just 2 months, and didn't try any graphical > design, So how can you comment on GUI programming with Python ? From jimhill at swcp.com Sat Feb 10 02:01:25 2007 From: jimhill at swcp.com (Jim Hill) Date: Sat, 10 Feb 2007 07:01:25 +0000 (UTC) Subject: Embedding, "import site", PYTHONHOME, and an old, old issue References: Message-ID: Jim Hill (that'd be me) wrote: I forgot one more key thing: the compiled code is being run via mpirun (LAM/MPI). Might that have something to do with my pain and heartache? Jim (original post reproduced below in shocking breach of etiquette on the off chance someone's interested in this post and didn't bother reading the first.) >Well, I've found about a hundred thousand web pages where people have >had the same problem I have but nary a page with a solution that works >for me. > >I want to do a simple embed, so I've followed the example in the >Extending and Embedding documentation: > >In the .c file, > >#include > >int routine() { > Py_Initialize(); > PyRun_SimpleString("from time import time,ctime\n" > "print 'Today is',ctime(time())\n"); > Py_Finalize(); > return 0; > } > >The code compiles just fine, but when I execute it the call to >Py_Initialize() comes back with: > >'import site' failed; use -v for traceback >Traceback (most recent call last): > File "", line 1, in >ImportError: No module named time > > > >I found a lot of websites that say to set PYTHONHOME to the the path to >the directory where site.py lives. I did that but I get the same error. > >Here are a few bits o' additional information: > >'python -v' tells me it was built with gcc 3.4.4 (and has no trouble at >all finding site.py whether PYTHONHOME is defined or not). The >following code snippet: > > >>> import distutils.sysconfig > >>> distutils.sysconfig.get_config_var('LINKFORSHARED') > >comes back with '-Xlinker -export-dynamic'. > >My own code needs to use Portland Group's pgi. I did some googling for >various permutations of nouns from the preceding few paragraphs and >found Pythonic mention of using "-Wl,-export-dynamic" as a flag for the >PG linker. OK, try that, builds fine, same error. > >I cannot recompile Python on this machine and I don't really understand >exactly what is happening with the Py_* function calls in the C snippet >above, or whether I can get more detailed traceback info. This is the >first time I've tried embedding and it's rather obvious that I've run >into a problem that everyone but Messrs. van Rossum and Lundh has hit. >Somebody, somewhere must have an honest-to-glub solution. If you are >that somebody, please let me know what to do because I'm about to throw >in the towel and embed That Other Language. > >Oh, one more thing: if I launch python from the shell and type in the >strings from the C snippet it works fine. -- It's not "pretexting", it's "lying." From kent at kentsjohnson.com Mon Feb 5 06:00:50 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 05 Feb 2007 11:00:50 GMT Subject: in place-ness of list.append In-Reply-To: References: Message-ID: Bart Van Loon wrote: > Hi all, > > I would like to find out of a good way to append an element to a list > without chaing that list in place, like the builtin list.append() does. > > currently, I am using the following (for a list of integers, but it > could be anything, really) > > #-------------------------------------------------- > def addnumber(alist, num): > """ work around the inplace-ness of .append """ > mylist = alist[:] > mylist.append(num) > return mylist > #-------------------------------------------------- Use + : In [1]: a=[1,2] In [2]: b=a+[3] In [3]: a Out[3]: [1, 2] In [4]: b Out[4]: [1, 2, 3] Kent From larry.bates at websafe.com Mon Feb 12 10:59:49 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Feb 2007 09:59:49 -0600 Subject: New Pythin user looking foe some good examples to study In-Reply-To: References: Message-ID: Johnny Garcia wrote: > I have just discovered Python and am familiarizing myself with the syntax > but I have always found that code examples where the best way for me to > learn. > > > > Can anyone point me to a site with some good open source functioning python > applications? > > > > I would appreciate any help. > > > > Also, does anyone know of any good Linux or python user groups in the orange > county, California area? > > Pick up a copy of "Python Cookbook" from O'Reilly. -Larry From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 5 11:52:27 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 05 Feb 2007 17:52:27 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: <52p5mbF1p0r0cU2@mid.individual.net> Gosi wrote: > J is in many ways similar to Python. The only one I see at the moment is that they're both some kind of programming languages. > J has very many advanced operations. Sure. Mh, just looking at some "advanced" J source taken from wikipedia.org makes me feel sick: | Here's a J program to calculate the average of a list of numbers: | avg=: +/ % # | avg 1 2 3 4 | 2.5 In the meantime, do you now have an answer to why we should care? Regards, Bj?rn -- BOFH excuse #314: You need to upgrade your VESA local bus to a MasterCard local bus. From pete at shinners.org Sun Feb 25 11:00:31 2007 From: pete at shinners.org (shredwheat) Date: 25 Feb 2007 08:00:31 -0800 Subject: Are weak refs slower than strong refs? In-Reply-To: References: Message-ID: <1172419231.513397.123470@m58g2000cwm.googlegroups.com> On Feb 24, 10:17 pm, John Nagle wrote: > Are weak refs slower than strong refs? I've been considering making the > "parent" links in BeautifulSoup into weak refs, so the trees will release > immediately when they're no longer needed. In general, all links back > towards the root of a tree should be weak refs; this breaks the loops > that give reference counting trouble. I've never really benchmarked their overhead. Thinking about how they work, I wouldn't expect a measurable difference in the time for dereferencing the weakrefs. But internally objects must track who all their weak reference holders are, so that will add some cost. I am guessing if the hierarchy is built once and remains fairly static you won't see the cost of this management. If the hierarchy is very dynamic there will be more weakref overhead. On the other hand, you will be freeing up the work done by the cyclic testing in the garbage collector. After doing similar work with weakrefs in hierarchies, I'd say it is worth doing. If you do the work, it would be interesting to see what the performance looks like. Be sure there is a gc.collect() in the timing for the original strong-ref version. :-) From gagsl-py at yahoo.com.ar Sat Feb 10 18:56:01 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 20:56:01 -0300 Subject: HTML Parsing References: <1171148863.807386.310960@h3g2000cwc.googlegroups.com> Message-ID: En Sat, 10 Feb 2007 20:07:43 -0300, mtuller escribi?: > > > LETTER > > 33,699 > > 1.0 > > > > I want to extract the 33,699 (which is dynamic) and set the value to a > variable so that I can insert it into a database. I have tried parsing > [...] > I have also tried Beautiful Soup, but had trouble understanding the > documentation, and HTMLParser doesn't seem to do what I want. Can[...] Just try harder with BeautifulSoup, should work OK for your use case. Unfortunately I can't give you an example right now. -- Gabriel Genellina From steveo at syslang.net Sun Feb 18 10:36:49 2007 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 18 Feb 2007 10:36:49 -0500 (EST) Subject: How do I create an array of functions? Message-ID: I have a table of integers and each time I look up a value from the table I want to call a function using the table entry as an index into an array whose values are the different functions. I haven't seen anything on how to do this in python. TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From from_tl at hotmail.com Thu Feb 22 18:47:18 2007 From: from_tl at hotmail.com (TONY) Date: 22 Feb 2007 15:47:18 -0800 Subject: Europe Tests Established Chemicals on Millions of Animals Message-ID: <1172188038.680999.181740@a75g2000cwd.googlegroups.com> Tony Nottingham England 22 February 2007 TO: All People Who Care I am a private individual posting this message to help Laboratory Animals and us all. I apologize if this seems out of place in this group but I think you need to know this. A new European Chemical Testing Policy called REACH has now been finalised by the European Union. Under these proposals Chemicals of every kind - from those used in industrial processes to the ingredients of consumer products - will be tested on Millions of animals from mice to fish to dogs, causing untold suffering. Still worse, because of this reliance on outdated animal techniques, reliable and relevant information will not be provided and our safety will not be assured. If you believe that REACH should make more use of Alternative Testing to test 1000s of Chemicals that have been in general use since before 1985 then please take action now. If you are a European citizen please contact your local papers and own MEP asking them to promote the development of humane non-animal testing methods under the REACH legislation, which is the best hope we have for sparing animals the misery of a testing laboratory. A sample letter can be found at the BUAV (British Union for the Abolition of Vivisection) website at www.BUAV.org (Select Campaigns, Chemical Testing, Get Active then Writing to the local press). For all Non-European members, you can still help. Please tell all your colleagues and friends in the UK and Europe about REACH. Write to your own local papers to try and inform others about what is going on in Europe. The website for the European Parliament is http://www.europarl.europa.eu. Information on REACH, the New European Chemical Testing Policy can be found here. Everyone can help and you can make a difference. Thank You From sjmachin at lexicon.net Tue Feb 20 10:08:02 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 07:08:02 -0800 Subject: file io (lagged values) newbie question In-Reply-To: References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> Message-ID: <1171984082.488529.76040@p10g2000cwp.googlegroups.com> On Feb 21, 12:22 am, Steven D'Aprano wrote: > On Mon, 19 Feb 2007 22:17:42 -0800, hiro wrote: > > Hey there, I'm currently doing data preprocessing (generating lagged > > values for a time series) and I'm having some difficulties trying to > > write a file to disk. A friend of mine, wrote this quick example for > > me: > > If that's a quick example (well over 100 lines), I'd hate to see your > idea of a long example. > > Can you cut out all the irrelevant cruft and just show: > > (1) the actual error you are getting > (2) the SMALLEST amount of code that demonstrates the error > > Try to isolate if the problem is in *writing* the file or *generating* > the time series. > > Hint: instead of one great big lump of code doing everything, write AT > LEAST two functions: one to read values from a file and generate a time > series, and a second to write it to a file. > > That exercise will probably help you discover what the problem is, and > even if it doesn't, you'll have narrowed it down from one great big lump > of code to a small function. > > To get you started, here's my idea for the second function: > (warning: untested) > > def write_series(data, f): > """Write a time series data to file f. > > data should be a list of integers. > f should be an already opened file-like object. > """ > # Convert data into a string for writing. > s = str(data) > s = s[1:-1] # strip the leading and trailing [] delimiters > s = s.replace(',', '') # delete the commas > # Now write it to the file object > f.write(s) > f.write('\n') And that's not cruft? Try this: f.write(' '.join(str(x) for x in data) + '\n') > And this is how you would use it: > > f = file('myfile.txt', 'w') > # get some time series data somehow... > data = [1, 2, 3, 4, 5] # or something else > write_series(data, f) > # get some more data > data = [2, 3, 4, 5, 6] > write_series(data, f) > # and now we're done > f.close() > Or for a more general solution, use the csv module: C:\junk>\python25\python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> wtr = csv.writer(open('fubar.txt', 'wb'), delimiter=' ') >>> data = [0, 1, 42, 666] >>> wtr.writerow(data) >>> wtr.writerow([9, 8, 7, 6]) >>> ^Z C:\junk>type fubar.txt 0 1 42 666 9 8 7 6 HTH, John From gigs at hi.t-com.hr Wed Feb 14 07:32:39 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 14 Feb 2007 13:32:39 +0100 Subject: Tkinter: how; newbie In-Reply-To: References: Message-ID: jim-on-linux wrote: > On Tuesday 13 February 2007 18:02, Gigs_ wrote: >> can someone explain me this code? >> >> from Tkinter import * >> >> root = Tk() >> >> def callback(event): >> print "clicked at", event.x, event.y >> >> frame = Frame(root, width=100, height=100) >> frame.bind("", callback) >> frame.pack() >> >> root.mainloop() >> > if you live on longititude 32, wrere is that? > If you live on latitude 40 and longitiude 32 I can > find that location. > > Your mouse is pointing to x, and y, which is > simply a location on the screen. > I know that, Matimus has explained what I didn't get but thx anyway > >> well, my problem is at frame.bind(",Button-1>", >> callback) callback function prints event.x and >> event.y. How the callback function get this two >> number when it has only one argument (event) >> Why its not: def callback(x, y): print x, y >> >> Im new to gui programming >> >> Sorry for bad eng! >> >> Thanks for replay! From a.schmolck at gmail.com Mon Feb 5 15:00:35 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 20:00:35 +0000 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> <52pc34F1oqe5fU1@mid.individual.net> Message-ID: Bjoern Schliessmann writes: > Alexander Schmolck wrote: > > > Apart from being less to type > > Cool. Less to type. Yes. Readability is more important in many context, but for something designed for interactive experimentation and exploration little typing is absolutely essential. Would you use a calculator that would require Java-style boilerplate to add two numbers? I'd also venture that readability and typing ease are typically closely positively correlated (compare python to C++) and although I would not claim that J is particularly readable I'm also not an expert user (I doubt I would even then, but I'm sure it *does* make a difference). > > and it is superior in that it's > > generalizes much better, e.g: > > > > avg&.^. NB. geomtric mean > > avg&.% NB. harmonic mean > > avg M NB. column mean of matrix M > > avg"1 M NB. row mean of matrix M > > Is there any regularity in this? If it is, it's not obvious at all. Sure. ``f&.g`` is like ``(f o g) o g^-1`` in common mathemetical notation. ``^.`` is log and ``%`` is inversion/division. Making ``&.`` (it's called "under") available as a convenient abstraction is IMO one really useful innovation of J. As for the remaing two: it's similar to numpy in that one and the same function can normally operate on arrays of different dimensions (including scalars). In numpy you'd also write stuff like ``mean(M, axis=1)``, it's not exactly the same, although the axis abstraction comes from APL (another cool idea), J introduces a slightly different approach. The ``"1`` means "operate on cells of rank 1" (i.e. vectors), rather than "operate along a certain axis". For dyadic (2-argument) functions you can also specify different left and right rank, so you could write the outerproduct v'w thus: ``v *"0 1 w`` (multiply each 0-cell (i.e scalar) of v with each 1-cell (i.e. vector, there is only one) of w). Unlike the linear algebra notation this readily generalizes to more than 1 dimensional objects. BTW I don't think J is an ideal language, not even for numerical computing -- there are plenty of things I'd do differently and that includes measures that would IMO greatly aid readability (like getting rid of "ambivalence"[1]). But I have little doubt that, no matter what its flaws may be, APL (and J is really just an updated, ASCII-based APL) is one of the most innovative and important programming languages ever conceived. Anyone interested in the design of programming language for scientific computing ought to take a look at at least a look at it or one of its descendants. 'as Footnotes: [1] Basically almost every J function has a completely different meaning depending on whether you use it as a unary or binary function (just as conventionally "-" is abusively used for both substraction and negation). From skip at pobox.com Thu Feb 8 23:24:32 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 8 Feb 2007 22:24:32 -0600 Subject: Looking for a MoinMoin guru - MoinMoin+SpamBayes == no wiki spam? In-Reply-To: <1170981347.050263.181360@j27g2000cwj.googlegroups.com> References: <1170981347.050263.181360@j27g2000cwj.googlegroups.com> Message-ID: <17867.63360.22506.593168@montanaro.dyndns.org> fuzzyman> You could also try akismet which is designed for finding spam fuzzyman> 'comments' in blogs, a similar problem area. Thanks. It appears that Akismet is a non-free tool, so doesn't fit in real well with the open source nature of MoinMoin and SpamBayes. I think I'll leave it to someone else to implement a security policy using that. It does seem like it would be trivial to write such a policy. The revision/reversion mechanism in MoinMoin is what's giving me fits. Akismet clearly sidesteps that problem altogether. Skip From ziga.seilnacht at gmail.com Tue Feb 20 02:18:02 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 19 Feb 2007 23:18:02 -0800 Subject: Bypassing __setattr__ for changing special attributes In-Reply-To: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> Message-ID: <1171955882.929647.86700@v33g2000cwv.googlegroups.com> George Sakkis wrote: > I was kinda surprised that setting __class__ or __dict__ goes through > the __setattr__ mechanism, like a normal attribute: > > class Foo(object): > def __setattr__(self, attr, value): > pass > > class Bar(object): > pass > > >>> f = Foo() > >>> f.__class__ = Bar > >>> print f.__class__ is Foo > True > > Is there a way (even hackish) to bypass this, or at least achieve > somehow the same goal (change f's class) ? > > George >>> object.__setattr__(f, '__class__', Bar) >>> f.__class__ is Bar True Ziga From http Mon Feb 5 18:15:43 2007 From: http (Paul Rubin) Date: 05 Feb 2007 15:15:43 -0800 Subject: Python does not play well with others References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> Message-ID: <7xzm7sryao.fsf@ruckus.brouhaha.com> "Graham Dumpleton" writes: > The first is whether it would be possible for code to be run with > elevated privileges given that the main Apache process usually is > started as root. I'm not sure at what point it switches to the special > user Apache generally runs as and whether in the main process the way > this switch is done is enough to prevent code getting back root > privileges in some way, so would need to be looked into. It switches very early, I think. It starts as root so it can listen on port 80. > There is also much more possibility for code, if it runs up extra > threads, to interfere with the operation of the Apache parent process. Certainly launching any new threads should be postponed til after the fork. From facundo at taniquetil.com.ar Tue Feb 27 07:09:43 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Tue, 27 Feb 2007 12:09:43 +0000 (UTC) Subject: Odd import behavior References: <312cfe2b0702011433t17e7e3e0nbcd0a210980dd022@mail.gmail.com> Message-ID: Gregory Pi?ero wrote: > I didn't realize Python behaved like this. Is there an FAQ I can read on this? I'll explain step by step: > FILE module1.py: > VAR1='HI' > > FILE MAIN.py: > from module1 import * > import module1 Here you have, in your module scope, a name 'VAR1' that points to "HI" and a name 'module1' that points to a module where you have a name 'VAR1' that points to "HI" (and that's why you have to use two names "import.VAR1") > print VAR1 > print module1.VAR1 This prints "HI" (VAR1 pointed to it), and "HI" (VAR1, inside module1, pointed to it). > VAR1='bye' This rebinds the name "VAR1" in this module scope. Now it points to "bye", not pointing anymore to the (still living) string "HI". Take note that you're not changing the value in memory, you're pointing to another place. > print VAR1 > print module1.VAR1 This prints "bye" (VAR1 now is pointing to it), and "HI" (VAR1, inside module1, still is pointing to it). > It seems to use module1.VAR1 for VAR1 until I assign something to VAR1 > in which case they become seperate. You do not assign something to VAR1, you rebind the name to point a new object in memory. For further detail in the explanation, you can check this very, *very* good paper (it's small and fun): http://starship.python.net/crew/mwh/hacks/objectthink.html Regards. -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From sjdevnull at yahoo.com Wed Feb 14 16:24:27 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 14 Feb 2007 13:24:27 -0800 Subject: threading and multicores, pros and cons In-Reply-To: <7x7iulqlvx.fsf@ruckus.brouhaha.com> References: <7xodnx2vir.fsf@ruckus.brouhaha.com> <7x7iulqlvx.fsf@ruckus.brouhaha.com> Message-ID: <1171488267.433565.228110@a75g2000cwd.googlegroups.com> On Feb 14, 1:44 am, Paul Rubin wrote: > > When a customer comes with his new beautiful dual-core server and > > get a basic plone install up and running, he will immediately > > compare it to J2EE and wonder why he should pay a consultant to make > > it work properly. At this time, it 's not easy to explain him that > > python is not flawed compared to Java, and that he will not regret > > his choice in the future. First impression may be decisive. > > That is true, parallelism is an area where Java is ahead of us. Java's traditionally been ahead in one case, but well behind in general. Java has historically had no support at all for real multiple process solutions (akin to fork() or ZwCreateProcess() with NULL SectionHandle), which should make up the vast majority of parallel programs (basically all of those except where you don't want memory protection). Has this changed in recent Java releases? Is there a way to use efficient copy-on-write multiprocess architectures? From aisaac at american.edu Mon Feb 26 16:48:52 2007 From: aisaac at american.edu (Alan Isaac) Date: Mon, 26 Feb 2007 21:48:52 GMT Subject: design question: no new attributes Message-ID: <8BIEh.1349$QI4.489@trnddc01> I have a class whose instances should only receive attribute assignments for attributes that were created at inititialization. If slots are not appropriate, what is the Pythonic design for this? Thanks, Alan Isaac From Thomas.Ploch at gmx.net Thu Feb 15 13:05:17 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 15 Feb 2007 19:05:17 +0100 Subject: Which Object Database would you recommend for cross platform application? Message-ID: <45D4A0DD.5080701@gmx.net> Hello folks, I am currently developing an open source Event Managment software (events in real-life, like concerts, exhibitions etc. :-) ) using wx for the GUI, and I need an Object database. Since this is the first time I actually need doing this, I wondered if anybody here could recommend one. It can be fairly simple. It doesn't need threading support and will only host one client (the application, but I am thinking about making this database accessible via the web, but this is still far in the future), although the database might get big (around 1GiB). It should be available for linux, mac os and windows. I looked into ZODB, but thats totally overloaded for my purpose. I looked into Durus (a re-implementation of ZODB, but without this overloaded stuff, but the documentation is very thin). Both of them don't really appeal. So I wondered if any of you could recommend one that (more or less) best fits the described conditions. Thanks in advance, Thomas From gigs at hi.t-com.hr Fri Feb 2 06:38:49 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 02 Feb 2007 12:38:49 +0100 Subject: coping directories In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ escribi?: > >> class CVisitor(FileVisitor): >> def __init__(self, fromdir, todir): >> self.fromdirLen = len(fromdir) + 1 # here is my problem >> self.todir = todir >> FileVisitor.__init__(self, fromdir) >> def visitdir(self, dirpath): >> topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) >> os.mkdir(topath) >> def visitfile(self, filepath): >> topath = os.path.join(self.todir, filepath[self.fromdirLen:]) >> cpfile(filepath, topath) #copy contents from filepath to >> topath[/code] >> >> >> When I copy contents from C:\IronPython to C:\temp >> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this >> self.fromdirLen = len(fromdir) + 1 >> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen >> = len(fromdir) i get contents copied to C:\ (actually to parent dir) > > Instead of actually doing os.mkdir and cpfile, use a print statement to > output the involved variables, and try with and without +1. You'll see > yourself what happens. > > --Gabriel Genellina > but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen = len(fromdir) i get contents copied to C:\ (actually to parent dir) instead to C:\temp From nowhere at nowhere.com Sun Feb 4 19:19:50 2007 From: nowhere at nowhere.com (Bob Kolker) Date: Sun, 04 Feb 2007 19:19:50 -0500 Subject: It is good to blow up a marketplace full of people buying and selling food In-Reply-To: <_Jqxh.46014$jA.34196@bignews1.bellsouth.net> References: <1170611125.519656.144410@m58g2000cwm.googlegroups.com> <_Jqxh.46014$jA.34196@bignews1.bellsouth.net> Message-ID: <52nbh6F1p56s2U5@mid.individual.net> Frank Arthur wrote: > > Suicide truck bomber kills at least 130 in Baghdad > By Tina Susman, Times Staff Writer > 11:23 AM PST, February 3, 2007 The sound of the exploding bomb is the Muslim Call to Prayer. Allah hu'Akbar. Bob Kolker From NikitaTheSpider at gmail.com Wed Feb 14 15:29:48 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Wed, 14 Feb 2007 15:29:48 -0500 Subject: threading and multicores, pros and cons References: Message-ID: In article , Maric Michaud wrote: > This is a recurrent problem I encounter when I try to sell python solutions > to > my customers. I'm aware that this problem is sometimes overlooked, but here > is the market's law. > > I've heard of a bunch of arguments to defend python's choice of GIL, but I'm > not quite sure of their technical background, nor what is really important > and what is not. These discussions often end in a prudent "python has made a > choice among others"... which is not really convincing. > > If some guru has made a good recipe, or want to resume the main points it > would be really appreciated. When designing a new Python application I read a fair amount about the implications of multiple cores for using threads versus processes, and decided that using multiple processes was the way to go for me. On that note, there a (sort of) new module available that allows interprocess communication via shared memory and semaphores with Python. You can find it here: http://NikitaTheSpider.com/python/shm/ Hope this helps -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From rbuck at xmission.com Wed Feb 28 15:33:45 2007 From: rbuck at xmission.com (Ray Buck) Date: Wed, 28 Feb 2007 13:33:45 -0700 Subject: Python installation problem Message-ID: <7.0.1.0.2.20070228133039.037dca60@xmission.com> I've been trying to install Mailman, which requires a newer version of the Python language compiler (p-code generator?) than the one I currently have on my linux webserver/gateway box. It's running a ClarkConnect 2.01 package based on Red Hat 7.2 linux. I downloaded the zipped tarball (Python-2.4.4.tgz), ran gunzip, then un-tarred it in /usr/local. Then (logged in as root) from /usr/local/Python-2.4.4 I ran the configure script which appeared to run properly. At least there were no error messages that I saw. Then I attempted to run "make install" and ended up with an error "make *** Error 1". It was right at the "libinstall" section of the make, so I did some googling and came up with the following command: [root at gateway Python-2.4.4]# make libinstall inclinstall After thrashing for about 5 minutes, I got basically the same message: Compiling /usr/local/lib/python2.4/zipfile.py ... make: *** [libinstall] Error 1 I dunno if this is relevant, but I have Python 2.2.2 in the /usr/Python-2.2.2 directory. Do I have to blow this away in order to install the newer distro? Or do I need to install the new one in/usr instead of /usr/local? Although I'm a retired programmer (mainframes), I'm still learning this linux stuff. I guess that makes me a noob...I hope you'll take that into consideration. Thanks, Ray -------------- next part -------------- An HTML attachment was scrubbed... URL: From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 16:33:05 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 22:33:05 +0100 Subject: Add images together In-Reply-To: <1172524574.348556.216270@z35g2000cwz.googlegroups.com> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> <54gtc3F214sakU1@mid.uni-berlin.de> <1172521836.797866.96220@z35g2000cwz.googlegroups.com> <1172523536.033424.122230@a75g2000cwd.googlegroups.com> <1172524574.348556.216270@z35g2000cwz.googlegroups.com> Message-ID: iceman wrote: > a)Yes, I am using PIL. > b)The color of each pixel over a sequence of frames > If you want to add numerical values of each pixel's colour then itereate through the pixels using nested for loops. But I (and I thing the rest of people here) can't be sure, what in fact you are trying to do. Please provide us with further info - what are you working at? zefciu From larry.bates at websafe.com Mon Feb 5 12:51:54 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 05 Feb 2007 11:51:54 -0600 Subject: Calling J from Python In-Reply-To: <52p5mbF1p0r0cU2@mid.individual.net> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Gosi wrote: > >> J is in many ways similar to Python. > > The only one I see at the moment is that they're both some kind of > programming languages. > >> J has very many advanced operations. > > Sure. > > Mh, just looking at some "advanced" J source taken from > wikipedia.org makes me feel sick: > > | Here's a J program to calculate the average of a list of numbers: > | avg=: +/ % # > | avg 1 2 3 4 > | 2.5 > > In the meantime, do you now have an answer to why we should care? > > Regards, > > > Bj?rn > And why is that superior to this: def avg(l): return float(sum(l))/len(l) >>>avg([1,2,3,4]) 2.5 Which can actually be read and debugged in the future! -Larry From aboudouvas at panafonet.gr Fri Feb 2 17:51:44 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 2 Feb 2007 14:51:44 -0800 Subject: "Correct" db adapter In-Reply-To: References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> <1170262532.590048.247580@a75g2000cwd.googlegroups.com> <52c4fdF1o9fd9U1@mid.uni-berlin.de> <1170324781.762209.115060@p10g2000cwp.googlegroups.com> Message-ID: <1170456704.433240.63420@l53g2000cwa.googlegroups.com> Thank you all! From grante at visi.com Sun Feb 11 11:14:15 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 11 Feb 2007 16:14:15 -0000 Subject: How to access an absolute address through Python? References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> Message-ID: <12sug6nib9qhtb9@corp.supernews.com> On 2007-02-11, volcano wrote: > Can it be done, Yes. > and if yes - how? /proc/kmem -- Grant Edwards grante Yow! Nipples, dimples, at knuckles, NICKLES, visi.com wrinkles, pimples!! From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 15:27:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 21:27:23 +0100 Subject: Calling J from Python In-Reply-To: <52p7h2F1pg9igU1@mid.uni-berlin.de> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p7h2F1pg9igU1@mid.uni-berlin.de> Message-ID: <45c78c14$0$29725$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Gosi wrote: > > >>On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: >> >>>Gosi wrote: >>> >>>>It is quite easy to call J from Python >>> >>>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... >>> >>>What is J, and why should we care? >>> >>>Diez >> >>J is in many ways similar to Python. >> >>J has very many advanced operations. > > > What exactly do you call "similar to python" when the following is a program > written in it? Compared to that, even Perl is a wonder of readability... > > m =: >@(0&{) > v =: >@(1&{) > h =: >@(2&{) > qu =: >@(3&{) > z =: i. at 0: > ret =: |.@}: > init =: z;z;z;i. > f1m =: (m,{. at qu);v;h;}. at qu > f5m =: (z;(v,{:@m);h;qu,ret at m) @ (f1m^:5) > f1h =: (z;z;(h,{:@v);(qu,ret at v)) @ (f5m^:12) > f12h =: (z;z;z;qu,ret at h,{:@h) @ (f1h^:12) > perm =: qu @ f12h @ init > ord =: *./ @ (#&>"_) @ C. > days =: -: @ ord @ perm Yuck. I'd rather program in b**k. From rzantow at gmail.com Sun Feb 4 12:20:35 2007 From: rzantow at gmail.com (rzed) Date: Sun, 04 Feb 2007 12:20:35 -0500 Subject: Parameter lists References: Message-ID: Mizipzor wrote in news:mailman.3533.1170607508.32031.python-list at python.org: > Consider the following snippet of code: > > ========================== > > class Stats: > def __init__(self, speed, maxHp, armor, strength, > attackSpeed, imagePath): > self.speed = speed > self.maxHp = maxHp > self.armor = armor > self.strength = strength > self.attackSpeed = attackSpeed > self.originalImage = loadTexture(imagePath) > > ========================== > > I little container for holding the stats for some rpg character > or something. Now, I dont like the looks of that code, there are > many function parameters to be sent in and if I were to add an > attribute, i would need to add it in three places. Add it to the > function parameters, add it to the class and assign it. > > Is there a smoother way to do this? There usually is in python, > hehe. I recall when reading python tutorials that you could do > something like this: > > foo(*list_of_parameters): > > To send many parameters as a list or a tuple. Then I could > assign them like this: > > class Stats: > def __init__(self, *li): > self.speed = li[0] > self.maxHp = li[1] > (...) > > Or maybe there is an even niftier way that lets me iterate > through them? Hmm... but that may lead to that I need to store > them in a way that makes it cumbersome to access them later. > > Any comments and/or suggestions are welcome! :) > I often use something like this, based on a Martellibot posting: >>> class Stats(dict): ... def __init__(self, *args, **kwds): ... self.update(*args) ... self.update(kwds) ... def __setitem__(self, key, value): ... return super(Stats, self).__setitem__(key, value) ... def __getitem__(self, name): ... try: ... return super(Stats, self).__getitem__(name) ... except KeyError: ... return None ... __getattr__ = __getitem__ ... __setattr__ = __setitem__ ... >>> m = dict(a=1,b=22,c=(1,2,3)) >>> p = Stats(m,x=4,y=[5,9,11]) >>> p.y [5, 9, 11] >>> p['y'] [5, 9, 11] -- rzed From beej at beej.us Wed Feb 14 15:06:51 2007 From: beej at beej.us (Beej) Date: 14 Feb 2007 12:06:51 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: <1171472657.567241.302690@h3g2000cwc.googlegroups.com> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <1171472657.567241.302690@h3g2000cwc.googlegroups.com> Message-ID: <1171483611.930377.141080@l53g2000cwa.googlegroups.com> On Feb 14, 9:04 am, "Andy Dingley" wrote: > I still don't understand what a lambda is _for_ in Python. Python supports functional programming to a certain extent, and lambdas are part of this. http://linuxgazette.net/109/pramode.html > I know what > they are, I know what the alternatives are, but I still haven't found > an instance where it permits something novel to be done that couldn't > be done otherwise (if maybe not so neatly). Strictly speaking, you can live your whole life without using them. There's always a procedural way of doing things, as well. -Beej From duncan.booth at invalid.invalid Wed Feb 28 08:00:51 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Feb 2007 13:00:51 GMT Subject: Creating arrays (builtin) in C Extensions References: <1172665143.602420.185920@q2g2000cwa.googlegroups.com> Message-ID: "iwl" wrote: > there is an builtin documented array module in phyton, > but no documentation how such an array can be > created in C-Extension functions. I would guess you create an array from C the same way you create any other Python objects. So call PyImport_ImportModule to get the array module, get its 'array' attribute with PyObject_GetAttrString then call PyObject_New to create your array. There is documentation on how to set the data in the array. See http://docs.python.org/api/bufferObjects.html From researchbase at gmail.com Thu Feb 8 16:40:39 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 9 Feb 2007 03:10:39 +0530 Subject: strange problem using modules from my own package. Message-ID: hello all, I found a very strange kind of behaviour in python with my own package. I created a package in which there were 4 modules and one __init__.py file I created the entire project in eclipse (pydev). it works fine there with the ide. but now when I try running the code without eclipse, that is when I run the individual .py file from a command promt it gives me error. for example I have mainwindow.py, customer.py, stock.py and of course __init__p.py in my package the app is in wxpython which is not important in the context of this problem. never the less I go in the directory called pbcf which is the name of my package there I have all the above mentioned files and the mainwindow.py file is the one I run for testing all the menus. but here the moment I run the file, it starts giving me an error saying pbcf is not a module. I find that the same code runs without any problem in eclipse. in mainwindow.py I have from pbcf import * and in __init__.py I have of course included MySQLdb and wx and in __init__.py I have a connection object called CONCSS. now when I have all the imports in mainwindow, it does work in eclipse but does not on a normal command prompt. why is this? regards. Krishnakant. From beej at beej.us Wed Feb 14 21:04:13 2007 From: beej at beej.us (Beej) Date: 14 Feb 2007 18:04:13 -0800 Subject: ANN: Python Call Graph 0.3.0 In-Reply-To: <1171494173.943088.161660@v33g2000cwv.googlegroups.com> References: <1171494173.943088.161660@v33g2000cwv.googlegroups.com> Message-ID: <1171505053.474154.314060@l53g2000cwa.googlegroups.com> On Feb 14, 3:02 pm, "Gerald Kaszuba" wrote: > I just released pycallgraph 0.3.0. There are many examples on the web > site and linked from the web site including a 16188 x 4187 sized call > graph! That's pretty cool, all right. -Beej From kevinliu23 at gmail.com Wed Feb 28 19:30:56 2007 From: kevinliu23 at gmail.com (kevinliu23) Date: 28 Feb 2007 16:30:56 -0800 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> <45E5F12C.4030200@timgolden.me.uk> Message-ID: <1172709056.823373.207030@q2g2000cwa.googlegroups.com> Hmmmm, right now...I'm doing multiplication on the index values returned by GetDiskFreeSpace. According to the documentation... tuple[0]: sectors per cluster tuple[1]: number of bytes per sector tuple[2]: total number of free clusters tuple[3]: total number of clusters on the disk So I'm multiplying together indices 0, 1 and 2 together to get the amount of free space left on my hard drive in bytes. The product of the first three indices is over 10 gigabytes and is correct according to my calculations. Why would the documentation say it does not return data over 2 gigabytes then? Or do you mean not over 2 gigabytes returned for tuple[2]? I believe my tuple[2] returned a value of 2778727 bytes, which is well below the 2 gigabyte capacity. Anyway, thanks for letting me know about GetDiskFreeSpaceEx. I will look into this function as well. Thanks guys! On Feb 28, 5:08 pm, "Jerry Hill" wrote: > On 2/28/07, Tim Golden wrote: > > > Well it's not often someone beats me to a WMI > > solution :) Just to be different, you can also > > look at the GetDiskFreeSpace function in the > > win32api module of the pywin32 extensions. > > The MSDN page for that function warns: > "The GetDiskFreeSpace function cannot report volume sizes that are > greater than 2 gigabytes (GB). To ensure that your application works > with large capacity hard drives, use the GetDiskFreeSpaceEx function." > > Make sure to keep that in mind if you're recording free disk space > someplace, rather than just checking for enough space to do an install > or something. > > -- > Jerry From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 19 13:08:20 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 19 Feb 2007 19:08:20 +0100 Subject: function & class References: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> <53s2hsF1tr4fuU1@mid.individual.net> <1171864485.501767.307420@v33g2000cwv.googlegroups.com> Message-ID: <53u7ckF1tibtgU2@mid.individual.net> jupiter wrote: > I am getting this error when I am using sql command within > class.function accessing from another class > > how can I create seperate instance for sqlite objects ??????? Trying to help you gets boring. I suggest reading the material that's being offered. Regards, Bj?rn -- BOFH excuse #241: _Rosin_ core solder? But... From bignose+hates-spam at benfinney.id.au Wed Feb 14 15:39:24 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Feb 2007 07:39:24 +1100 Subject: reference data in a dictionary References: <1115a2b00702141226i4f23dc17x1360d87ed253dd3e@mail.gmail.com> Message-ID: <87ps8c79tv.fsf@benfinney.id.au> "Wensui Liu" writes: > i am new to python and have a question about referencing data in a > dict. is there anyway that allows me to do something like: > dict[['row1', 'row2', .....'row100']] What behaviour would you expect from that statement? If we know what you're trying to do, perhaps we can suggest a solution. -- \ "Like the creators of sitcoms or junk food or package tours, | `\ Java's designers were consciously designing a product for | _o__) people not as smart as them." -- Paul Graham | Ben Finney From nagle at animats.com Thu Feb 15 00:51:53 2007 From: nagle at animats.com (John Nagle) Date: Thu, 15 Feb 2007 05:51:53 GMT Subject: threading and multicores, pros and cons In-Reply-To: <7xzm7gt2sg.fsf@ruckus.brouhaha.com> References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> <7xzm7gt2sg.fsf@ruckus.brouhaha.com> Message-ID: If locking is expensive on x86, it's implemented wrong. It's done right in QNX, with inline code for the non-blocking case. Not sure about the current libraries for Linux, but by now, somebody should have gotten this right. John Nagle Paul Rubin wrote: > Maric Michaud writes: > >>>"Some time back, a group did remove the GIL from the python core, and >>>implemented locks on the core code to make it threadsafe. Well, the >>>problem was that while it worked, the necessary locks it made single >>>threaded code take significantly longer to execute." From tdelaney at avaya.com Mon Feb 26 15:23:44 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 27 Feb 2007 07:23:44 +1100 Subject: [OT] python notation in new NVIDIA architecture Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ECBC@au3010avexu1.global.avaya.com> Daniel Nogradi wrote: >>> Something funny: >>> >>> The new programming model of NVIDIA GPU's is called CUDA and I've >>> noticed that they use the same __special__ notation for certain >>> things as does python. For instance their modified C language has >>> identifiers such as __device__, __global__, __shared__, etc. Is it >>> a coincidence? Probably it is. :) >> >> Cuda is usually taken as short for "barracuda", a fish. Fish have >> been known to slither under the right circumstances. Perhaps this is >> the link? > > Wow! How is it that I didn't think about this before?! Thanks a > million! Actually, I think it's more likely to be a direct link to the Fish Slapping Dance ... Tim Delaney From B.Ogryczak at gmail.com Fri Feb 2 09:50:53 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 2 Feb 2007 06:50:53 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: <1170427852.983951.194890@p10g2000cwp.googlegroups.com> On Feb 2, 2:55 pm, "ardief" wrote: > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] your_list = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] d = {} for k,v in your_list: d.setdefault(k,[]).append(v) result = [list(x) for x in d.items()] # if you really need it as list of lists # if list of tuples is ok, then it?d be just: # result = d.items() result.sort() # if you need this list sorted by keys From sam.schelfhout at gmail.com Thu Feb 22 08:53:40 2007 From: sam.schelfhout at gmail.com (beeswax) Date: 22 Feb 2007 05:53:40 -0800 Subject: Reading mails from Outlook Message-ID: <1172152420.295840.133600@t69g2000cwt.googlegroups.com> Hi, Does anyone knows how to read e-mails from a specific folders in outlook? I only found out how to read the mails from the inbox folder and how to list all available folder. I just don't found a way to access my mails from the other folders. Can anyone help me? Regards, Sam From laurent.pointal at limsi.fr Mon Feb 12 08:06:46 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 12 Feb 2007 14:06:46 +0100 Subject: Formatting milliseconds to certain String In-Reply-To: References: Message-ID: Deniz Dogan a ?crit : > Hello. > I need help with a small problem I'm having. > > I want to make a function which takes an integer representing some time > in milliseconds and returns the same time but formatted as > "hours:minutes:seconds,milliseconds" with leading zeros whenever possible. > > E.g. I input 185804 to the function and it returns 00:03:05,804. The > function I'm using now is defined as: > > def millisToFormat(millis): > try: > hours = millis / 3600000 > mins = (millis - hours * 3600000) / 60000 > secs = (millis - hours * 3600000 - mins * 60000) / 1000 > millis = millis - hours * 3600000 - mins * 60000 - secs * 1000 > hours = str(hours) > mins = str(mins) > secs = str(secs) > millis = str(millis) > if len(hours) == 1: > hours = "0"+hours > if len(mins) == 1: > mins = "0"+mins > if len(secs) == 1: > secs = "0"+secs > if len(millis) < 3: > millis = (len(millis) - 3) * "0" + millis > return str(hours) + ":" + str(mins) + ":" + str(secs) + "," + > str(millis) > except ValueError: > return -1 > > Note that I am very new to Python and the language I have been using > most prior to this is Java. A shorter solution using % operator in Python: >>> def millisToFormat(millis): ... hours = millis / 3600000 ... mins = (millis - hours * 3600000) / 60000 ... secs = (millis - hours * 3600000 - mins * 60000) / 1000 ... millis = millis - hours * 3600000 - mins * 60000 - secs * 1000 ... return "%(hours)02d:%(mins)02d:%(secs)02d,%(millis)03d"%locals() ... >>> millisToFormat(185804 ) '00:03:05,804' See chapter "3.6.2 String Formatting Operations" in the Python Library Reference. http://docs.python.org/lib/typesseq-strings.html A+ Laurent. From http Mon Feb 5 17:22:05 2007 From: http (Paul Rubin) Date: 05 Feb 2007 14:22:05 -0800 Subject: lambda functions ? References: Message-ID: <7xy7nc6y9e.fsf@ruckus.brouhaha.com> "Maxim Veksler" writes: > >>> def make_incrementor(n): > ... return lambda x: x + n Is the same as: def make_incrementor(n): def inner(x): return x + n return inner When you enter make_incrementor, it allocates a memory slot (normally we'd think of this as a stack slot since it's a function argument, but it's really in the heap) and copies its argument there. Then you create the function "inner" which refers to that memory slot because of the reference to "n". Then make_incrementor returns, but since the returned object still contains the reference to that memory slot, the memory slot is not freed (this is the part where it becomes important that the slot is really not on the stack). So when you call the returned function, it still can get at that slot. This style is very common in Scheme programming so you might read a Scheme book if you want to understand it. The classic: http://mitpress.mit.edu/sicp/ > Could some please try (if even possible) to implement the above code > without using "lambda" I believe it would help me grasp this a bit > faster then. Does the above help? From gagsl-py at yahoo.com.ar Sun Feb 18 17:19:16 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Feb 2007 19:19:16 -0300 Subject: search cursor in pythonwin 2.1 References: <1171815140.829723.87940@a75g2000cwd.googlegroups.com> Message-ID: En Sun, 18 Feb 2007 13:12:20 -0300, GISDude escribi?: > I am a GIS(geographic information systems) Analyst and in our > software(ESRI ARCGIS 9.1) ESRI has implemented Python 2.1 as the > scripting language of choice. > > In my script I'm going thru a dbf file and extracting NON-NULL values > in a field. What I need to do with that is create a new dbf table with > the values I found in it. I think you should either read the ArcGis documentation, or post your question in a specilized forum. Your problem is not about Python itself, but on how to use the esriGeoprocessing object. > GP.Select_Analysis("neighborhoods.shp", "neighborhoods_names.shp", ' > "Names" <> \ "null\" ') > > #at this point I'm stuck. how do I query out a NON- > NULL value? > #or a value in the Names field? As a side note, on a standard SQL database, the condition would read "Names IS NOT NULL", but I don't know if this is applicable or not. -- Gabriel Genellina From claird at lairds.us Mon Feb 19 20:37:40 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 20 Feb 2007 01:37:40 +0000 Subject: Newbie help looping/reducing code References: <7x1wkl8xb7.fsf@ruckus.brouhaha.com> Message-ID: <400qa4-r1i.ln1@lairds.us> In article <7x1wkl8xb7.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >Lance Hoffmeyer writes: >> def even_odd_round(num): >> if(round(num,2) + .5 == int(round(num,2)) + 1): >> if num > .5: >> if(int(num) % 2): >> num = round(num,2) + .1 #an odd number >> else: >> num = round(num,2) - .1 #an even number >> else: >> num = 1 >> rounded_num = int(round(num,0)) >> return rounded_num > >I would also rewrite this function. It's quite hard to figure out >what it's intended to do. At minimum it should be carefully . . . >def even_odd_round(num): > assert num >= 0 > > # separate the number's integer and fractional parts > intpart, fracpart = int(num), num % 1.0 > > # decide what to do based on the fractional part > if fracpart < 0.495: > return intpart # round downward > elif fracpart > 0.505 or intpart==0: > return intpart+1 # round upward > else: > return intpart + intpart % 2 # round to even I have even less idea than Paul what the true intent of even_odd_round() is. I offer, though, the general observation that it's VERY often possible to do what people want in this sort of regard with a simple use of formatting--something like "%.3f" % num If one comes from C or Java, it can be hard to appreciate immediately how useful this is. It's also likely to be more robust than anything naively written "by hand". From deets at nospam.web.de Mon Feb 26 04:47:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Feb 2007 10:47:16 +0100 Subject: help regarding python and jsp References: <1172472092.215780.250560@t69g2000cwt.googlegroups.com> Message-ID: <54fol4F20m2fmU1@mid.uni-berlin.de> chandrapsg at gmail.com wrote: > Hi, > i am working with jsp .. > i wanna help regarding how to import or how to call python modules to > jsp > > if a piece of code is availabe will be very helpful for me jsp is Java. Python is ... Python. There is Jython available, a python-interpreter running in a Java JVM. Go visit http://jython.org/ to learn more about it. Diez From siona at chiark.greenend.org.uk Wed Feb 14 07:45:35 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 14 Feb 2007 12:45:35 +0000 (GMT) Subject: replacing substrings within strings References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> Message-ID: amadain wrote: >I was wondering if there was a nicer way to swap the first 2 >characters in a string with the 4th and 5th characters other than: > >darr=list("010203040506") >aarr=darr[:2] >barr=darr[4:6] >darr[:2]=barr >darr[4:6]=aarr >result="".join(darr) darr=list("010203040506") darr[:2], darr[4:6] = darr[4:6], darr[:2] result = "".join(darr) -- \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 Jstone at 3web.com Sat Feb 3 07:20:59 2007 From: Jstone at 3web.com (JoJo) Date: Sat, 3 Feb 2007 20:20:59 +0800 Subject: web programming with Python Message-ID: <1170505259.45c47e2b5362b@webmail.3web.com> Hello, Is there a Quick Reference for Python web programming? Thank you. --Jojo ----------------------------------------------------------------------- 3webXS High Speed Cable or DSL Internet...surf at speeds up to 3.0 Mbps for as low as $24.95/mo...visit www.get3web.com for details From sean_mcilroy at yahoo.com Sun Feb 18 21:31:53 2007 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 18 Feb 2007 18:31:53 -0800 Subject: Need an identity operator because lambda is too slow In-Reply-To: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> Message-ID: <1171852313.254660.44190@s48g2000cws.googlegroups.com> On Feb 17, 9:59 pm, "Deron Meranda" wrote: [snip] this may be really dense, but i'm curious what's wrong with the "multiplexer" idiom: for item in some_sequence: item2 = (not some_rare_condition and item) or \ (some_rare_condition and some_transform_function(item)) ..... # more stuff peace stm From deets at nospam.web.de Thu Feb 1 06:48:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Feb 2007 12:48:12 +0100 Subject: SWIG overhead References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> <1170328902.611668.271550@k78g2000cwa.googlegroups.com> Message-ID: <52e2bsF1nlgutU1@mid.uni-berlin.de> > Yeah, found that one googling around. But I haven?t fund anything more > up to date. I imagine, that the performance of all of these wrappers > has been improved since then. But the performance of Python/C API > would too? > Anyways, it?s not about exact number, it?s more about taking decision > if doing rewrite is worth it?s time. The wrappers essentially create the boilerplate-code that invokes the Python C-API. So whatever improvements the latter has been developed, the wrappers will benefit from it. I doubt that there are major performance penalties associated with any of them. More important for a wrapper-decision is the question how easy they are to use. Diez From buffinator at mymail.com Sat Feb 24 11:49:07 2007 From: buffinator at mymail.com (buffinator) Date: Sat, 24 Feb 2007 17:49:07 +0100 Subject: Recreating a char array from a pointer In-Reply-To: References: <45e05fb2$0$486$cc7c7865@news.luth.se> Message-ID: <45e068a6$0$488$cc7c7865@news.luth.se> Oh, nice Im running 2.4 but im gonna download it and give it a try then Thanks! Thomas Heller wrote: > buffinator schrieb: >> I have an application that has to send a string as a pointer to memory, >> and then another one that has to retriece it and fetch the string. >> Converting the string to an array and sending the pointer was easy >> >> import array >> a=array.array("c","mytextgoeshere") >> my_pointer = a.buffer_info()[0] >> >> >> But then I tried to get the data back... and I just can't find out how. >> I ended up writing a C module for this that works fine in linux, but >> this application is meant for windows and I just can't get C-modules to >> compiler there correctly since I suck at windows. >> >> The relevant code from the module is >> >> static PyObject * >> pointrtostr_casttostr(PyObject *self, PyObject *args) >> { >> char *mystr; >> long int p; >> >> if (!PyArg_ParseTuple(args, "l", &p)) >> return NULL; >> >> mystr = (char*)p; >> return Py_BuildValue("s", mystr); >> } >> >> My question is... can I do the above code in python without involving C >> since it is quite a big hassle to have to go through the module building >> in windows? :/ > > You can use the ctypes package for this. It is in the standard library in Python 2.5, > for older versions it is a separate download. > > Thomas > From http Sat Feb 10 20:27:25 2007 From: http (Paul Rubin) Date: 10 Feb 2007 17:27:25 -0800 Subject: Regular Expressions References: <1171156418.267223.318460@v45g2000cwv.googlegroups.com> Message-ID: <7xlkj55vr6.fsf@ruckus.brouhaha.com> "John Machin" writes: > > What's the way to go about learning Python's regular expressions? I feel > > like such an idiot - being so strong in a programming language but knowing > > nothing about RE. > > I suggest that you work through the re HOWTO > http://www.amk.ca/python/howto/regex/ Also remember Zawinski's law: http://fishbowl.pastiche.org/2003/08/18/beware_regular_expressions From bignose+hates-spam at benfinney.id.au Mon Feb 5 21:01:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 06 Feb 2007 13:01:51 +1100 Subject: Taint (like in Perl) as a Python module: taint.py References: <1170713584.199237.22210@v33g2000cwv.googlegroups.com> Message-ID: <87iregcacw.fsf@benfinney.id.au> "Gabriel Genellina" writes: > I suppose you don't intend to publish the SafeString class - but if > anyone can get a SafeString instance in any way or another, he can > convert *anything* into a SafeString trivially. The point (in Perl) of detecting taint isn't to prevent a programmer from deliberately removing the taint. It's to help the programmer find places in the code where taint accidentally remains. > And tainted() returns False by default????? > Sorry but in general, this won't work :( I'm inclined to agree that the default should be to flag an object as tainted unless known otherwise. -- \ "On the other hand, you have different fingers." -- Steven | `\ Wright | _o__) | Ben Finney From python at hope.cz Sat Feb 17 03:38:06 2007 From: python at hope.cz (Johny) Date: 17 Feb 2007 00:38:06 -0800 Subject: HTTP_REFERER value Message-ID: <1171701486.540940.151990@h3g2000cwc.googlegroups.com> Is HTTP_REFERER value transfered between different domains? For example if I come to a website , say, www.python.org, from website www.microsoft.com will www.python.org finds that I came there from www.microsoft.com? Thank you for help L. From jairodsl at gmail.com Tue Feb 13 07:24:47 2007 From: jairodsl at gmail.com (jairodsl) Date: 13 Feb 2007 04:24:47 -0800 Subject: how to compare... In-Reply-To: <1171359024.422165.70250@j27g2000cwj.googlegroups.com> References: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> <1171359024.422165.70250@j27g2000cwj.googlegroups.com> Message-ID: <1171369487.008757.148760@p10g2000cwp.googlegroups.com> On Feb 13, 4:30 am, "Gerard Flanagan" wrote: > On Feb 13, 5:03 am, "jairodsl" wrote: > > > > > Hello everybody ! > > > I have two list, they are, S1=['A','B','C','D','E'], and > > S2=['F','G','H','I','J'], but i have to compare both in this way: > > > A vs J > > A vs I, B vs J > > A vs H, B vs I, C vs J > > A vs G, B vs H, C vs I, D vs J > > A vs F, B vs G, C vs H, D vs I, E vs J > > B vs F, C vs G, D vs H, E vs I > > C vs F, D vs G, E vs H > > D vs F, E vs G > > E vs F > > Could someone give me any idea how to compare(or print) both list in > > this way ??? Thanks a lot !!! > > > jDSL > > def interleave( X, Y ): > for i in range(1, len(Y)+1): > yield zip(X, Y[-i:]) > for j in range(1, len(X)): > yield zip(X[j:], Y) > > x = ['A', 'B', 'C', 'D', 'E'] > y = ['F', 'G', 'H', 'I', 'J'] > > for seq in interleave(x, y): > print seq > > [('A', 'J')] > [('A', 'I'), ('B', 'J')] > [('A', 'H'), ('B', 'I'), ('C', 'J')] > [('A', 'G'), ('B', 'H'), ('C', 'I'), ('D', 'J')] > [('A', 'F'), ('B', 'G'), ('C', 'H'), ('D', 'I'), ('E', 'J')] > [('B', 'F'), ('C', 'G'), ('D', 'H'), ('E', 'I')] > [('C', 'F'), ('D', 'G'), ('E', 'H')] > [('D', 'F'), ('E', 'G')] > [('E', 'F')] > > Regards > > Gerard Thank you very much for all your answers. jDSL From http Wed Feb 14 16:59:15 2007 From: http (Paul Rubin) Date: 14 Feb 2007 13:59:15 -0800 Subject: rot13 in a more Pythonic style? References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: <7xps8cjt8s.fsf@ruckus.brouhaha.com> "Andy Dingley" writes: > I'm trying to write rot13, but to do it in a better and more Pythonic > style than I'm currrently using. What would you reckon to the > following pretty ugly thing? How would you improve it? In > particular, I don't like the way a three-way selection is done by > nesting two binary selections. Also I dislike stating the same > algorithm twice, but can't see how to parameterise them neatly. I'm having a hard time understanding what you're getting at. Why don't you describe the actual problem instead of the rot13 analogy. From cyberco at gmail.com Tue Feb 20 15:01:02 2007 From: cyberco at gmail.com (cyberco) Date: 20 Feb 2007 12:01:02 -0800 Subject: wxPython: non-GUI thread launching new frame? Delegates? In-Reply-To: References: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> <5405fnF1upuuoU1@mid.uni-berlin.de> Message-ID: <1172001661.882918.193600@l53g2000cwa.googlegroups.com> Ah! Great tip, thanks! Now instead of calling: parent.onRequest(param) I call: wx.CallAfter(lambda x: parent.onRequest(x), param) Way cool. 2B > This is rather out of date. wxPython provides a wx.CallAfter function, > which will call the passed callable on the next spin through the event > loop. It's essentially a wrapper around the custom event mechanism > described above. > > > Diez From gagsl-py at yahoo.com.ar Sun Feb 18 23:38:48 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 01:38:48 -0300 Subject: Python Threads References: <2adc542f0702181516g7bbfb08ga721b568cb528404@mail.gmail.com> <2adc542f0702181837g3c433742ha0fedd775d8cc0fa@mail.gmail.com> Message-ID: En Sun, 18 Feb 2007 23:37:02 -0300, Sick Monkey escribi?: > Well if this cannot be done, can a thread call a function in the main > method? > I have been trying and have not been successive. Perhaps I am using > thread > incorrectly. The safe way to pass information between threads is to use Queue. From inside the working thread, you put() an item with enough state information. On the main (GUI) thread, you use after() to check for any data in the queue, and then update the interfase accordingly. I think there is a recipe in the Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python -- Gabriel Genellina From harry.g.george at boeing.com Wed Feb 14 00:57:10 2007 From: harry.g.george at boeing.com (Harry George) Date: Wed, 14 Feb 2007 05:57:10 GMT Subject: Scripting Visio using Python References: <53ec6aF1rdistU1@mid.individual.net> Message-ID: Paul Watson writes: > I would like to create some additional shapes in Microsoft Visio using > the Python language. It would appear that Visio can use any CLR > language. Has anyone done this? Can I use the Python package from > python.org, or must I use IronPython? An alternative might be to work (cross-platform) wit the vxd (XML) file format. A good reader/writer for that would be handy. -- Harry George PLM Engineering Architecture From mizipzor at gmail.com Sun Feb 4 17:45:29 2007 From: mizipzor at gmail.com (Mizipzor) Date: 4 Feb 2007 14:45:29 -0800 Subject: Missing member Message-ID: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> I have some troubles with a member variable that seems to be missing in a class. In short, heres what I do; class A is the parent class, B inherits from A and C inherits from B (hope I used the right words there). Now, I create an instance of C, which calls A's __init__ which in turn creates all the member variables. Then I call C.move() (a function defined in A), but then, one of the variables seems to have become 'NoneType'. The code can be found here (Ive taken away unnecessery stuff): http://pastebin.com/875394 The exact error is (which occur on line 15 in the pasted code): TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' Any comments are welcome. :) From exarkun at divmod.com Wed Feb 14 14:48:57 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 14 Feb 2007 14:48:57 -0500 Subject: try...except...finally problem in Python 2.5 In-Reply-To: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> Message-ID: <20070214194857.25807.801693041.divmod.quotient.21530@ohm> On 14 Feb 2007 11:41:29 -0800, redawgts wrote: >I keep getting this error "local variable 'f' referenced before >assignment" in the finally block when I run the following code. > > try: > f = file(self.filename, 'rb') > f.seek(DATA_OFFSET) > self.__data = f.read(DATA_SIZE) > self.isDataLoaded = True > except: > self.isDataLoaded = False > finally: > f.close() > >Can someone tell me what's wrong with the code? Am I doing something >wrong? I'm somewhat new to python but this makes sense to me. > f is not bound until the first line of the try suite has completely successfully executed. If it fails to do this, for example because self.filename is an attribute error, or the filename given by that attribute does not exist, then the finally suite will execute before f has been bound, and the UnboundLocalError will mask the real error. Jean-Paul From larry.bates at websafe.com Fri Feb 9 17:35:32 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 09 Feb 2007 16:35:32 -0600 Subject: A little more advanced for loop In-Reply-To: <1171019473.527988.206610@l53g2000cwa.googlegroups.com> References: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> <1171019473.527988.206610@l53g2000cwa.googlegroups.com> Message-ID: <45CCF734.3080306@websafe.com> Horta wrote: > On Feb 9, 9:00 am, Stephan Diehl wrote: >> Horta wrote: >>> Hi folks, >>> Suppose I have to loop over 3 lists being the same size at the same >>> time and order. How can I do that without using the range() function >>> or whatever indexing? >>> Example using range: >>> a = ['aaa', 'aaaa'] >>> b = ['bb', 'bbbb'] >>> c = ['c', 'cccc'] >>> for i in range(len(a)): >>> # using a[i], b[i], and c[i] >>> I'm sure there's a elegant way to do that... >>> Thanks in advance. >> Sure, there is: >> >> for a_item, b_item , c_item in zip(a,b,c): >> # do something > > Thanks guys! > Note: if lists are long take a look at itertools izip. zip creates a list of lists which could take lots of memory/time if they are VERY large. itertools izip iterates over them in place. from itertools import izip for a_item, b_item, c_item in izip(a,b,c): # do something -Larry From subscriber123 at gmail.com Mon Feb 26 13:58:48 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Mon, 26 Feb 2007 13:58:48 -0500 Subject: jsString class Message-ID: <4c0048df0702261058s638f5f7co50655f46f6e2a129@mail.gmail.com> Hi all, Some of you may find this useful. It is a class I wrote that acts like the way strings do in JavaScript. It is a little buggy, and not complete, but could be useful. class jsString: def __init__(self,string): if string.__class__ is list: print "list:",string self.list=string else: print "string:",string self.list=[string] def __add__(self,other): try: r=self.list[:-1]+[self.list[-1]+other] except: r=self.list+[other] return jsString(r) def __mul__(self,other): try: r=self.list[:-1]+[self.list[-1]*other] except: r=self.list*other return jsString(r) def __len__(self): return len(str(self)) def __str__(self): r="" for obj in self.list: r+=str(obj) return r def __repr__(self): return str(self.list) -------------- next part -------------- An HTML attachment was scrubbed... URL: From thn at mail.utexas.edu Mon Feb 12 17:11:32 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 12 Feb 2007 14:11:32 -0800 Subject: c++ for python programmers In-Reply-To: References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <1171318292.493867.181860@a34g2000cwb.googlegroups.com> On Feb 12, 1:35 pm, andrew clarke wrote: > Thomas, I sent you a message off-list but it bounced due to your mailbox > being full. > > Short answer: Subscribe to the c-prog at yahoogroups.com mailing list and > ask your C/C++ questions there. > > Regards > Andrew I have to edit a large C++ project written by someone else. My email address above is incorrect; replace mail with cs. Thanks for the help. Thomas From kibleur.christophe at gmail.com Tue Feb 20 14:04:33 2007 From: kibleur.christophe at gmail.com (Tool69) Date: 20 Feb 2007 11:04:33 -0800 Subject: question with inspect module Message-ID: <1171998273.748507.14070@h3g2000cwc.googlegroups.com> Hi, I would like to retrieve all the classes, methods and functions of a module. I've used the inspect module for this, but inside a given class (subclass of some other one), I wanted to retrieve only the methods I've written, not the inherited one. How can I do ? Thanks. From mikael at isy.liu.se Fri Feb 23 03:48:52 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Fri, 23 Feb 2007 09:48:52 +0100 Subject: Convert to binary and convert back to strings In-Reply-To: References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172105179.708565.201600@v33g2000cwv.googlegroups.com> Message-ID: <45DEAA74.6060205@isy.liu.se> Neil Cerutti wrote: > Woah! You better quadruple it instead. > How about Double Pig Latin? > No, wait! Use the feared UDPLUD code. > You go Ubbi Dubbi to Pig Latin, and then Ubbi Dubbi again. > Let's see here... Ubububythubububonubpubay > That's what I call ubububeautubububifubububulbubay. That looks slightly like the toy language that Swedish kids refer to as the robbers language: You double each consonant, and place an o between each such double consonant. So, applying that to Python, you would get popytothohonon. Actually, one of the largest Swedish telecom companies has used this toy language in one of their commercials. /MiO From nike.is.nospam at home.se Sun Feb 25 16:43:00 2007 From: nike.is.nospam at home.se (Niclas) Date: Sun, 25 Feb 2007 22:43:00 +0100 Subject: convert strings to utf-8 In-Reply-To: <54doljF20aq9hU1@mid.uni-berlin.de> References: <54doljF20aq9hU1@mid.uni-berlin.de> Message-ID: Thank you! solved it with this: unicode( data.decode('latin_1') ) and when I write it to the file... f = codecs.open(path, encoding='utf-8', mode='w+') f.write(self.__rssDoc.toxml()) Diez B. Roggisch skrev: > Niclas schrieb: >> Hi >> >> I'm having trouble to work with the special charcters in swedish (? ? >> ? ? ? ?). The script is parsing and extracting information from a >> webpage. This works fine and I get all the data correctly. The >> information is then added to a rss file (using >> xml.dom.minidom.Document() to create the file), this is where it goes >> wrong. Letters like ? ? ? get messed up and the rss file does not >> validate. How can I convert the data to UTF-8 without loosing the >> special letters? > > Show us code, and example text (albeit I know it is difficult to get > that right using news/mail) > > The basic idea is this: > > scrapped_byte_string = scrap_the_website() > > output = scrappend_byte_string.decode('website-encoding').encode('utf-8') > > > > Diez From okahashi at gmail.com Thu Feb 22 08:47:56 2007 From: okahashi at gmail.com (okahashi at gmail.com) Date: 22 Feb 2007 05:47:56 -0800 Subject: Creating a daemon process in Python In-Reply-To: References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Message-ID: <1172152076.728838.187810@v33g2000cwv.googlegroups.com> Thanks all, I understood there is no shortcut function like BSD daemon(). I'll do it manually using examples from cookbook... On 2?22?, ??1:41, Benjamin Niemann wrote: > Hello, > > Sakagami Hiroki wrote: > > What is the easiest way to create a daemon process in Python? Google > > says I should call fork() and other system calls manually, but is > > there no os.daemon() and the like? > > You could try > > > HTH > > -- > Benjamin Niemann > Email: pink at odahoda dot de > WWW:http://pink.odahoda.de/ From steve at holdenweb.com Thu Feb 1 09:00:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Feb 2007 14:00:51 +0000 Subject: The reliability of python threads In-Reply-To: <45BF9A4C.3070002@mvista.com> References: <45B90118.5010408@mvista.com> <45BF9A4C.3070002@mvista.com> Message-ID: Carl J. Van Arsdall wrote: > Steve Holden wrote: >> [snip] >> >> Are you using memory with built-in error detection and correction? >> >> > You mean in the hardware? I'm not really sure, I'd assume so but is > there any way I can check on this? If the hardware isn't doing that, is > there anything I can do with my software to offer more stability? > You might be able to check using the OS features (have you said what OS you are using?) - alternatively Google for information from the system supplier. If you don't have that feature in hardware you are up sh*t creek without a paddle, as it can't be emulated. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From olsongt at verizon.net Sun Feb 18 21:01:19 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 18 Feb 2007 18:01:19 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <1171850479.140864.210400@j27g2000cwj.googlegroups.com> On Feb 16, 4:22 pm, ifti_cr... at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language but i > am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net > > so will you please guide me which GUI based language has worth with > complete OOPS Characteristics > > will wait for the answer > > hope to have a right direction from you Programmer > > Regards > Iftikhar > itzon... at yahoo.com Despite what "real programmers" and various apologists might say, there isn't much out there that comes close to the ease-of-use and functionality of VB when it comes to designing a GUI. I say this not to discourage you, but to let you know that if a GUI designer is your sole criteria for a new language, you're going to be disappointed with everything you see. I'd suggest that with whatever new language you go with, you either write apps that aren't gui-based, or write a web application with a web-based GUI. Another alternative would be to write the "business logic" in the new language, and have a shell VB app implementing the GUI call it. You can do this easily in python by creating python based COM components (not sure how easy it is in ruby, and it's a comparitive pain-in-the-ass in C++) Good luck, Grant From grante at visi.com Thu Feb 15 10:53:07 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Feb 2007 15:53:07 -0000 Subject: Method overloading? References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <12t7qehj9jm0a21@corp.supernews.com> <1171516359.202035.35020@q2g2000cwa.googlegroups.com> Message-ID: <12t90f399653m11@corp.supernews.com> On 2007-02-15, placid wrote: >> > Is it possible to be able to do the following in Python? >> >> > class Test: >> > def __init__(self): >> > pass >> >> > def puts(self, str): >> > print str >> >> > def puts(self, str,str2): >> > print str,str2 >> >> > if __name__ == "__main__": >> > t = Test() >> > t.puts("hi") >> > t.puts("hi","hello") >> >> You tell us: what happened when you tried it? > > Well, when i run it i get this error "puts() takes exactly 3 arguments > (2 given)" which means that the second a time i try to define the > puts() method "overwrites" the first one Correct. That means it's not possible to do what you wrote. >> And then what happens when you do this? >> >> class Test: >> def __init__(self): >> pass >> >> def puts(self, *args): >> print ' '.join(args) >> >> if __name__ == "__main__": >> t = Test() >> t.puts("hi") >> t.puts("hi","hello") > > but this isn't overloading. No, it isn't. [You can't overload methods in Python. Was that your question?] It is, however, the way one does what you appear to be trying to do. -- Grant Edwards grante Yow! If I am elected no at one will ever have to do visi.com their laundry again! From rw at smsnet.pl Tue Feb 20 10:27:10 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 20 Feb 2007 07:27:10 -0800 Subject: Sorting directory contents In-Reply-To: References: Message-ID: <1171985230.592470.246030@m58g2000cwm.googlegroups.com> Wolfgang Draxinger wrote: > However this code works (tested) and behaves just like listdir, > only that it sorts files chronologically, then alphabetically. > > def listdir_chrono(dirpath): > import os > files_dict = dict() > for fname in os.listdir(dirpath): > mtime = os.stat(dirpath+os.sep+fname).st_mtime > if not mtime in files_dict: > files_dict[mtime] = list() > files_dict[mtime].append(fname) > > mtimes = files_dict.keys() > mtimes.sort() > filenames = list() > for mtime in mtimes: > fnames = files_dict[mtime] > fnames.sort() > for fname in fnames: > filenames.append(fname) > return filenames Using the builtin functions `sorted`, `filter` and the `setdefault` method of dictionary could a little shorten your code: def listdir_chrono(dirpath): import os files_dict = {} for fname in filter(os.path.isfile, os.listdir(dirpath)): mtime = os.stat(os.path.join(dirpath, fname)).st_mtime files_dict.setdefault(mtime, []).append(fname) filenames = [] for mtime in sorted(files_dict): for fname in sorted(files_dict[mtime]): filenames.append(fname) return filenames -- HTH, Rob From rune.strand at gmail.com Wed Feb 14 07:27:15 2007 From: rune.strand at gmail.com (Rune Strand) Date: 14 Feb 2007 04:27:15 -0800 Subject: replacing substrings within strings In-Reply-To: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> Message-ID: <1171456035.101434.232440@q2g2000cwa.googlegroups.com> On Feb 14, 1:08 pm, "amadain" wrote: > I was wondering if there was a nicer way to swap the first 2 > characters in a string with the 4th and 5th characters other than: > > darr=list("010203040506") > aarr=darr[:2] > barr=darr[4:6] > darr[:2]=barr > darr[4:6]=aarr > result="".join(darr) > > The above code works fine but I was wondering if anybody had another > way of doing this? Assuming the string length is always at least 5: def swap(s): return '%s%s%s%s' % (s[3:6], s[2:3], s[:2], s[6:]) From http Wed Feb 14 01:44:02 2007 From: http (Paul Rubin) Date: 13 Feb 2007 22:44:02 -0800 Subject: threading and multicores, pros and cons References: <7xodnx2vir.fsf@ruckus.brouhaha.com> Message-ID: <7x7iulqlvx.fsf@ruckus.brouhaha.com> Maric Michaud writes: > Le mercredi 14 f?vrier 2007 05:49, Paul Rubin a ?crit?: > > Basically Python applications are usually not too CPU-intensive; there > > are some ways you can get parallelism with reasonable extra effort; > Basically, while not CPU intensive, application server needs to get > benefit of all resources of the hardware. But this is impossible--if the application is not CPU intensive, by definition it leaves a lot of the available CPU cycles unused. > When a customer comes with his new beautiful dual-core server and > get a basic plone install up and running, he will immediately > compare it to J2EE and wonder why he should pay a consultant to make > it work properly. At this time, it 's not easy to explain him that > python is not flawed compared to Java, and that he will not regret > his choice in the future. First impression may be decisive. That is true, parallelism is an area where Java is ahead of us. > The historical explanation should be inefficient here, I'm > afraid. What about the argument that said that multi threading is > not so good for parallelism ? Is it strong enough ? It's not much good for parallelism in the typical application that spends most of its time blocked waiting for I/O. That is many applications. It might even even be most applications. But there are still such things as CPU-intensive applications which can benefit from parallelism, and Python has a weak spot there. From gherron at digipen.edu Tue Feb 27 02:13:25 2007 From: gherron at digipen.edu (Gary Herron) Date: Mon, 26 Feb 2007 23:13:25 -0800 Subject: How can I disable a device in windows using python In-Reply-To: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> References: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> Message-ID: <45E3DA15.6090802@digipen.edu> Phoe6 wrote: > Hi all, > I am trying to disable the NIC card (and other cards) enabled in my > machine to test diagnostics on that card. > I am trying to disable it programmatic using python. I checked python > wmi and i could not find ways to disable/enable, (listing is however, > possible). > > Where should I look for to enable/disable devices in python. > > Thanks, > Senthil > > You didn't even tell us what operating system you are using, but even so, I'm going to say you probably won't find a Python function to do this. However, if you tell us how you would disable a card from outside of Python, we'll see if we can find a way to do it from within Python. Things you might want to tell us: What OS. What device(s) Exactly what "disable" means for each. How the OS allows you to enable/disable each. Anything else that might help us. Gary Herron From Robert.Katic at gmail.com Fri Feb 23 19:09:59 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 23 Feb 2007 16:09:59 -0800 Subject: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: <1172275799.822034.213500@t69g2000cwt.googlegroups.com> On Feb 23, 5:12 pm, "Steven W. Orr" wrote: > I understand that two leading underscores in a class attribute make the > attribute private. But I often see things that are coded up with one > underscore. Unless I'm missing something, there's a idiom going on here. > > Why do people sometimes use one leading underscore? > > TIA > > -- > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > happened but none stranger than this. Does your driver's license say Organ ..0 > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > individuals! What if this weren't a hypothetical question? > steveo at syslang.net One underscore stay for 'protected'. Protected in OOP means that the attribute is hidden outside the class but visible for subclasses. In python one undersore is only a good convention for say that the attribute is protected. So users will ignore attributes with initial undersocre. Users who subclass must know of that attributes existence for prevent unwonted overriding. Sory for my english. From john.pye at gmail.com Sat Feb 17 19:07:31 2007 From: john.pye at gmail.com (John Pye) Date: 17 Feb 2007 16:07:31 -0800 Subject: 'import dl' on AMD64 platform Message-ID: <1171757251.224765.171800@s48g2000cws.googlegroups.com> Hi all I have a tricky situation that's preventing my Python/SWIG/C application from running on the Debian Etch AMD64 platform. It seems that the 'dl' module is not available on that platform. The only reason I need the 'dl' module, however, is for the values of RTLD_LAZY etc, which I use with sys.setdlopenflags() in order to make my imported SWIG module share its symbols correctly with more deeply- nested plugin modiles in my C-code layer. I wonder if there is a workaround for this -- perhaps another way to access the values of those RTLD flags? Cheers JP From zefirek at Speacock.Pau.Apoznan.Mpl Mon Feb 26 10:36:46 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Mon, 26 Feb 2007 16:36:46 +0100 Subject: SystemError: new style getargs format but argument is not a tuple Message-ID: I am trying to embed a c function in my python script for a first time. When I try to call it I get an error SystemError: new style getargs format but argument is not a tuple Guido said on some mailing list, that it is probably an effect of the lack of METH_VARARGS in the functions' array, but it's ok in my source code. Here is the full code: #include static PyObject * mandelpixel(PyObject *self, PyObject *args) { double z_real = 0, z_imag = 0, z_real2 = 0, z_imag2 = 0, c_real, c_imag, bailoutsquare; int iteration_number; register int i; PyObject coord; if (!PyArg_ParseTuple(args, "Oid", &coord, &iteration_number, &bailoutsquare)) return NULL; if (!PyArg_ParseTuple(&coord, "dd", &c_real, &c_imag)) return NULL; for(i = 1; i <= iteration_number; i++) { z_imag = 2 * z_real * z_imag + c_imag; z_real = z_real2 - z_imag2 + c_real; z_real2 = z_real * z_real; z_imag2 = z_imag * z_imag; if (z_real2 + z_imag2 > bailoutsquare) return Py_BuildValue("i", i); } return Py_BuildValue("i", 0); } static PyMethodDef MandelcMethods[] = { { "mandelpixel", mandelpixel, METH_VARARGS, "check the pixel for Mandelbrot set" }, { NULL, NULL, 0, NULL } }; PyMODINIT_FUNC initmandelc(void) { (void) Py_InitModule ("mandelc", MandelcMethods); } int main(int argc, char **argv) { Py_SetProgramName(argv[0]); Py_Initialize(); initmandelc(); return 0; } Greets zefciu From mizipzor at gmail.com Fri Feb 2 06:20:46 2007 From: mizipzor at gmail.com (Mizipzor) Date: Fri, 2 Feb 2007 12:20:46 +0100 Subject: Writing "pythonish" code Message-ID: Hi, this is my first mail to the list (and any list for that matter) so any pointers on errors from my part would be appreciated. Im more used to forums. To start off, Ive read some python documents and done some small apps so I think I can say I know it semi-well, and I know c++ very well. But I want learn python even better, since I know that a company I aim to be employed by make heavy use of python, knowing python myself would give me an extra edge. The problem isnt in pythons syntax, its in the architecture/design, the concept of writing "pythonish code" if you like. One thing is that in c++ im used to have private members in classes and no member is altered except through the public functions of the class. In python everything is, as far as I know, public. Im confused by this, should I still have members in the python class that I simply dont edit directly and let the class do its internal stuff? Or should I see the python classes like c++ structs with functions? I guess the ultimate is somewhere in between but I would like a nudge or two to get there. Now, the thing that bothers me the most. When I write python modules I write one class per file, and the file and the class has a common name. Maybe this is due to c++ habits. The problem is when I import the module, make an instance of its class and store it in a variable: foo.py ========= class foo: def bar(self): print "bar" ========= main.py ========= import foo localFoo = foo.foo() localFoo.bar() ========= To me, the main.py code above looks very ugly. So, assuming Im never gonna have more than one instance of the foo class, can I write something like this: foo.py ========= def bar(self): print "bar" ========= main.py ========= import foo foo.bar() ========= Thats much more cleaner if you ask me, and kinda a good way to make sure that you dont have more than one "instance" of the foo class (which no longer is a class at all). But is it "pythonish"? Gonna stop now, this mail got a little longer than i first thought. Any input will be greatly appreciated. :) From johnjsal at NOSPAMgmail.com Thu Feb 1 14:58:34 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Feb 2007 14:58:34 -0500 Subject: Sorting a list In-Reply-To: <45c245e1$0$31965$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> Message-ID: <45c246eb$0$31965$c3e8da3@news.astraweb.com> John Salerno wrote: > Bruno Desthuilliers wrote: >> John Salerno a ?crit : >>> Hi everyone. If I have a list of tuples, and each tuple is in the form: >>> >>> (year, text) as in ('1995', 'This is a citation.') >>> >>> How can I sort the list so that they are in chronological order based >>> on the year? >> >> Calling sort() on the list should just work. > > Amazing, it was that easy. :) One more thing. What if I want them in reverse chronological order? I tried reverse() but that seemed to put them in reverse alphabetical order based on the second element of the tuple (not the year). From nogradi at gmail.com Wed Feb 28 15:22:03 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 28 Feb 2007 21:22:03 +0100 Subject: gmpy moving to code.google.com In-Reply-To: <1172691395.635962.90050@j27g2000cwj.googlegroups.com> References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> <1172691395.635962.90050@j27g2000cwj.googlegroups.com> Message-ID: <5f56302b0702281222ped0834aqe19481907bf96b61@mail.gmail.com> > Could you please tell me, on that 64-bit build, what happens with: > > >>> import gmpy, sys, operator > >>> sys.maxint > ??? > >>> gmpy.mpz(sys.maxint) > ??? > >>> operator.index(gmpy.mpz(sys.maxint)) > ??? > >>> sys.maxint+1 > ??? > >>> gmpy.mpz(sys.maxint+1) > ??? > >>> operator.index(gmpy.mpz(sys.maxint)+1) > ??? > > i.e., what are the values correspondiing to the ??? occurrences when > you actually do that...? Here it goes (python 2.5 - 64bit): >>> import gmpy, sys, operator >>> sys.maxint 9223372036854775807 >>> gmpy.mpz(sys.maxint) mpz(-1) >>> operator.index(gmpy.mpz(sys.maxint)) -1 >>> sys.maxint+1 9223372036854775808L >>> gmpy.mpz(sys.maxint+1) mpz(9223372036854775808L) >>> operator.index(gmpy.mpz(sys.maxint)+1) 0 I don't pretent to fully understand what's going on, but gmpy.mpz(sys.maxint)==gmpy.mpz(-1) is more than suspicious :) From 3174965380 at vmobl.com Wed Feb 14 05:15:02 2007 From: 3174965380 at vmobl.com (3174965380 at vmobl.com) Date: Wed, 14 Feb 2007 02:15:02 -0800 (PST) Subject: No subject Message-ID: <4264952.1171448102891.JavaMail.umobile@vscsmtp> (dancing stripper on your dekstop free!!!!!!!!) From sickcodemonkey at gmail.com Tue Feb 27 10:28:32 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 27 Feb 2007 10:28:32 -0500 Subject: book for a starter In-Reply-To: <1115a2b00702270709i4363557etbbc6bb424af71561@mail.gmail.com> References: <1115a2b00702270709i4363557etbbc6bb424af71561@mail.gmail.com> Message-ID: <2adc542f0702270728s182945afs99c96eae620ba0f3@mail.gmail.com> I personally would get "Programming Python, Third Edition " http://www.oreilly.com/catalog/python3/ On 2/27/07, Wensui Liu wrote: > > Good morning, all, > > I just start learning python and have a question regarding books for a > newbie like me. > If you are only allowed to buy 1 python book, which one will you pick? > ^_^. > > Thank you so much! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cyberco at gmail.com Tue Feb 13 15:00:32 2007 From: cyberco at gmail.com (cyberco) Date: 13 Feb 2007 12:00:32 -0800 Subject: New Pythin user looking foe some good examples to study In-Reply-To: References: Message-ID: <1171396824.445595.116210@q2g2000cwa.googlegroups.com> http://www.daniweb.com/code/python.html http://www.pythonchallenge.com/ From google at orcon.net.nz Fri Feb 16 19:44:00 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 16 Feb 2007 16:44:00 -0800 Subject: Output to a text window In-Reply-To: <45d63efd$0$16342$88260bb3@free.teranews.com> References: <1171671545.951006.160420@k78g2000cwa.googlegroups.com> <45d63efd$0$16342$88260bb3@free.teranews.com> Message-ID: <1171673040.477518.91860@t69g2000cwt.googlegroups.com> On Feb 17, 1:25 pm, "Joshua J. Kugler" wrote: > goo... at orcon.net.nz wrote: > > Hi, > > > I'm going around in circles so I'm asking for help. I want to read a > > simple text file and output the contents to a GUI window when I click > > on a button. I have written a small python program to read the > > contents of a file when a button is clicked but can only output this > > to a console window. I'm using the pygtk binding with glade for the > > gui. > > > I know it must be quiet simple but a mental block has rapidly > > descended. > > > Any help would be appreciated. > > What does your code look like? What are you using to print? Are you > writing to the GUI or using the 'print statement?' > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmerhttp://www.eeinternet.com > PGP Key:http://pgp.mit.edu/ ID 0xDB26D7CE > > -- > Posted via a free Usenet account fromhttp://www.teranews.com This is the code, it was adapted from code I found on the net. Code as follows, #!/usr/bin/python import pygtk import gtk import gtk.glade import string import os import gobject class gui: def __init__(self): self.wTree=gtk.glade.XML('dansgui.glade') dic = { "on_Read_File": self.on_Read_File, "on_cancel": (gtk.main_quit)} self.wTree.signal_autoconnect(dic) self.count = 0 self.win = self.wTree.get_widget("window1") self.win.connect("delete_event", self.on_delete_event) self.win.show() def on_Read_File(self, widget): print "Opening Dansguardian bannedsitelist file for reading..." print; print lineoftext = open('/etc/dansguardian/lists/bannedsitelist', 'r') myarray = [] lnum = 0 for line in lineoftext: line = line.rstrip('\n') line = line.rstrip( ) lnum = lnum + 1 print lnum , line myarray.append(line); lineoftext.close( ) def on_delete_event(self, widget, event): self.win.set_sensitive(False) dialog = gtk.MessageDialog(self.win, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, None) dialog.set_markup('Are you sure you want to quit?') dialog.connect("destroy", lambda w: self.win.set_sensitive(True)) answer = dialog.run() if answer == -8: dialog.destroy() return False if answer == -9: dialog.destroy() return True app = gui() gtk.main() From kylotan at gmail.com Sat Feb 10 17:36:14 2007 From: kylotan at gmail.com (Ben Sizer) Date: 10 Feb 2007 14:36:14 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <17868.46349.59089.178486@montanaro.dyndns.org> <013b01c74cd8$8d913860$03000080@hendrik> Message-ID: <1171146974.180146.292500@l53g2000cwa.googlegroups.com> On Feb 10, 8:42 am, Steve Holden wrote: > Hendrik van Rooyen wrote: > > wrote: > > "Ben Sizer" wrote: > > >> Ben> Python extensions written in C require recompilation for each new > >> Ben> version of Python, due to Python limitations. > > >> Can you propose a means to eliminate this limitation? > > > Yes. - Instead of calling something, send it a message... > > I suppose you are proposing to use the ISO 19999.333 generic > message-passing interface for this? The one that doesn't actually call a > function to pass a message? I'm assuming you're being facetious here..? Of course, functions get called at the ends of the message passing process, but those functions can stay the same across versions while the messages themselves change. The important part is reducing the binary interface between the two sides to a level where it's trivial to guarantee that part of the equation is safe. eg. Instead of having PySomeType_FromLong(long value) exposed to the API, you could have a PyAnyObject_FromLong(long value, char* object_type_name). That function can return NULL and set up an exception if it doesn't understand the object you asked for, so Python versions earlier than the one that implement the type you want will just raise an exception gracefully rather than not linking. The other issue comes with interfaces that are fragile by definition - eg. instead of returning a FILE* from Python to the extension, return the file descriptor and create the FILE* on the extension side with fdopen. -- Ben Sizer From mccredie at gmail.com Fri Feb 23 14:16:36 2007 From: mccredie at gmail.com (Matimus) Date: 23 Feb 2007 11:16:36 -0800 Subject: With PIL... paste image on top of other with dropshadow In-Reply-To: <1172243347.246211.317600@8g2000cwh.googlegroups.com> References: <1172243347.246211.317600@8g2000cwh.googlegroups.com> Message-ID: <1172258196.048933.7750@v33g2000cwv.googlegroups.com> two things, change the following line: [code] back = Image.new(image.mode, (totalWidth, totalHeight), background) [/code] To: [code] back = Image.new("RGBA", (totalWidth, totalHeight), background) [/code] and then do something like this: [code] import sys bg = Image.open(sys.argv[1]) image = Image.open(sys.argv[2]) image = dropShadow(image,shadow=(0x00,0x00,0x00,0xff)) bg.paste( image, (50,50), image ) bg.show() [/code] Where the shadow color specifies an alpha transparency value. From mail at microcorp.co.za Sat Feb 10 00:58:55 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 10 Feb 2007 07:58:55 +0200 Subject: pygame and python 2.5 References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <17868.46349.59089.178486@montanaro.dyndns.org> Message-ID: <013b01c74cd8$8d913860$03000080@hendrik> wrote: "Ben Sizer" wrote: > Ben> Python extensions written in C require recompilation for each new > Ben> version of Python, due to Python limitations. > > Can you propose a means to eliminate this limitation? > Yes. - Instead of calling something, send it a message... - Hendrik From donn at drizzle.com Sat Feb 17 13:48:27 2007 From: donn at drizzle.com (Donn Cave) Date: 17 Feb 2007 18:48:27 GMT Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> <7xfy956gq8.fsf@ruckus.brouhaha.com> <7xk5yhbqb1.fsf@ruckus.brouhaha.com> Message-ID: <1171738107.112419@bubbleator.drizzle.com> Quoth Paul Rubin : | Donn Cave writes: | > What this proves is that you can implement | > an argument list at run time, but it by no means changes the | > nature of the argument list as a sequence. | | Right, it's treated as a sequence rather than a record structure. | So is that consistent with the "tuples are record structures" view, | as opposed to the "tuples are immutable lists" view? A struct is a sequence, and your stdargs example is a pretty good case in point. When I said the function implemented with stdarg (...) support needs information about its parameters to simulate a normal function, that applies not only to the order of parameters but also their type. Because -- as with structs, but unlike arrays -- the parameter list has variable alignment to accommodate different sized types. So the C parameter list really has every property of a struct -- naturally contains mixed types, has variable alignment, normally accessed by name -- but it does have a defined order, and stdarg is a gimmick that uses it. Order IS the struct property that you get from a tuple, so it is of course important that the tuple is a sequence. The point is not whether it's a sequence or not, but what kind of order it represents. What I'm saying with the evidently overly abstract discussion in previous posts, is that in a struct-like application, a tuple's order is of a different nature than a list. Because in such application, that order is absolute and in a sense atomic. Like a struct. Like an argument list. That's why tuple has different applications than list, that's why it lacks some of the sequential access features that lists have. This must be more obvious in other languages that have a tuple type. None that I know of support so many list or array sequence operations on tuples, and in at least some the struct/record type is implemented by adding names to a tuple but can still be treated as one (like Python's mtime and stat types.) Donn Cave, donn at drizzle.com From eisenhau at nb.sympatico.ca Thu Feb 8 22:06:49 2007 From: eisenhau at nb.sympatico.ca (Reid) Date: Fri, 09 Feb 2007 03:06:49 GMT Subject: Thanks for the help Message-ID: Hello All Thanks for taking the time to answer my question. I do not need 3d stuff. Just a couple of buttons and menu's. The reason I am looking at python is it is free to download. I cannot afford VB or other commercial languages. Reid From shanekwon at gmail.com Sun Feb 11 19:27:22 2007 From: shanekwon at gmail.com (agent-s) Date: 11 Feb 2007 16:27:22 -0800 Subject: searching a list of lists as a two-dimensional array? Message-ID: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Basically I'm programming a board game and I have to use a list of lists to represent the board (a list of 8 lists with 8 elements each). I have to search the adjacent cells for existing pieces and I was wondering how I would go about doing this efficiently. Thanks From kevinliu23 at gmail.com Wed Feb 28 16:54:53 2007 From: kevinliu23 at gmail.com (kevinliu23) Date: 28 Feb 2007 13:54:53 -0800 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: <1172697850.946627.196420@a75g2000cwd.googlegroups.com> References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> <1172697850.946627.196420@a75g2000cwd.googlegroups.com> Message-ID: <1172699693.411268.153760@j27g2000cwj.googlegroups.com> Just tried your solution Tim, worked like a charm. :) It's great because I don't even have to worry about the computer name. A question regarding the rootPath parameter...how would I be passing it? Would I be passing it as... tuple = win32api.GetDiskFreeSpace(r'C:') or just leave it blank and the function will automatically use the rootPath of where the .py file resides? Both have returned the correct result. Kevin On Feb 28, 4:24 pm, "kevinliu23" wrote: > Thanks so much for the help guys. I got the code Sick Monkey provided > to work on my computer. Now I"m more confused than ever though. :) I > thought the only standard modules provided by Python are listed here: > > http://docs.python.org/modindex.html > > But it appears that there are other modules available to me without > having to download third party code. Could someone point me to the > documentation of these other modules such as win32com.client? Thanks > everyone for your help. :) > > Also, how could I get the computer name? I would be running this code > on another machine and don't want to change the computer name in the > code every time I port it to another computer. Thanks! > > Kevin > > On Feb 28, 4:16 pm, Tim Golden wrote: > > > [... re getting free disk space ...] > > > Sick Monkey wrote: > > > Here you are: > > > > >>> from win32com.client import GetObject > > >>>> wmiObj = GetObject("winmgmts:\\\\MGW01641\\root\\cimv2") > > >>>> diskinfo = wmiObj.ExecQuery("Select * from Win32_LogicalDisk") > > >>>> for disk in diskinfo: > > > ... print disk.Name, disk.FreeSpace > > > ... > > > A: None > > > C: 16978259968 > > > D: None > > > Well it's not often someone beats me to a WMI > > solution :) Just to be different, you can also > > look at the GetDiskFreeSpace function in the > > win32api module of the pywin32 extensions. > > > The doc says: """ > > tuple = GetDiskFreeSpace(rootPath) > > > Retrieves information about the specified disk, including the amount of > > free space available. > > > Parameters > > > rootPath : string > > > Specifies the root directory of the disk to return information about. If > > rootPath is None, the method uses the root of the current directory. > > > Win32 API References > > > Search for GetDiskFreeSpace at msdn, google or google groups. > > > Return Value > > The return value is a tuple of 4 integers, containing the number of > > sectors per cluster, the number of bytes per sector, the total number of > > free clusters on the disk and the total number of clusters on the disk. > > If the function fails, an error is returned. > > """ > > > TJG From deets at nospam.web.de Fri Feb 9 05:57:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 09 Feb 2007 11:57:53 +0100 Subject: A little more advanced for loop References: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> Message-ID: <5332dhF1qhht1U1@mid.uni-berlin.de> Horta wrote: > Hi folks, > > Suppose I have to loop over 3 lists being the same size at the same > time and order. How can I do that without using the range() function > or whatever indexing? > > Example using range: > > a = ['aaa', 'aaaa'] > b = ['bb', 'bbbb'] > c = ['c', 'cccc'] > > for i in range(len(a)): > # using a[i], b[i], and c[i] > > I'm sure there's a elegant way to do that... Use zip: for av, bv, cv in zip(a, b, c): print av, bv, cv Diez From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 17:14:47 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 23:14:47 +0100 Subject: Sorting a list In-Reply-To: <45c25d9a$0$27590$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> <45c254a2$0$674$426a34cc@news.free.fr> <45c25d9a$0$27590$c3e8da3@news.astraweb.com> Message-ID: <45c25f5f$0$29465$426a34cc@news.free.fr> John Salerno a ?crit : (snip) > Oh I didn't sort then reverse, I just replaced sort with reverse. Maybe > that's why! Hmmm... Probably, yes... !-) From mathiasDOTfranzius at webDELETEME.de Wed Feb 14 06:01:09 2007 From: mathiasDOTfranzius at webDELETEME.de (Mathias) Date: Wed, 14 Feb 2007 12:01:09 +0100 Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: > > What module are you using for SSH? > > What's in your program that isn't pure Python? > The problem is probably in some non-Python component; you shouldn't > be able to force a memory protection error from within Python code. > It looks like the error could be in scipy/Numeric, when a large array's type is changed, like this: >>> from scipy import * >>> a=zeros(100000000,'b') #100 MiB >>> b=a.copy().astype('d') #800 MiB, ok >>> a=zeros(1000000000,'b') #1GiB >>> b=a.copy().astype('d') #8GiB, fails with sf Segmentation fault if I use zeros directly for allocation of the doubles it works as expected: >>> from scipy import * >>> a=zeros(1000000000,'d') #8GiB, fails with python exception Traceback (most recent call last): File "", line 1, in ? MemoryError: can't allocate memory for array >>> I use python 2.4, but my scipy and Numeric aren't quite up-to-date: scipy version 0.3.2, Numeric v 24.2 From gagsl-py2 at yahoo.com.ar Fri Feb 23 21:28:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Feb 2007 23:28:52 -0300 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) Message-ID: At Friday 23/2/2007 22:12, Charles D Hixson wrote: > This is going to take a bit of work (I've gone over the example 5 times, > and it's still not quite making > sense), but this looks like just what I was hoping to find. Just remember that: obj.name = value is the same as: setattr(obj, "name", value) (notice the quoted name), and likewise: x = obj.name is the same as: x = getattr(obj, "name") They are described in http://docs.python.org/lib/built-in-funcs.html -- Gabriel Genellina From gagsl-py at yahoo.com.ar Fri Feb 23 18:43:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Feb 2007 20:43:43 -0300 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) References: <45DF5467.6000803@earthlink.net> Message-ID: En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson escribi?: > I'm sure I've read before about how to construct prototypes in Python, > but I haven't been able to track it down (or figure it out). > > What I basically want is a kind of class that has both class and > instance level dict variables, such that descendant classes > automatically create their own class and instance level dict variables. > The idea is that if a member of this hierarchy looks up something in > it's local dict, and doesn't find it, it then looks in the class dict, > and if not there it looks in its ancestral dict's. This is rather like > what Python does at compile time, but I want to do it at run time. Well, the only thing on this regard that Python does at compile time, is to determine whether a variable is local or not. Actual name lookup is done at runtime. You can use instances and classes as dictionaries they way you describe. Use getattr/setattr/hasattr/delattr: py> class A: ... x = 0 ... y = 1 ... py> class B(A): ... y = 2 ... py> a = A() py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable py> print 'a=',vars(a) a= {'y': 3} py> py> b = B() py> print 'b=',vars(b) b= {} py> setattr(b,'z',1000) py> print 'b=',vars(b) b= {'z': 1000} py> print 'x?', hasattr(b,'x') x? True py> print 'w?', hasattr(b,'w') w? False -- Gabriel Genellina From gigs at hi.t-com.hr Tue Feb 13 18:02:46 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 14 Feb 2007 00:02:46 +0100 Subject: Tkinter: how; newbie Message-ID: can someone explain me this code? from Tkinter import * root = Tk() def callback(event): print "clicked at", event.x, event.y frame = Frame(root, width=100, height=100) frame.bind("", callback) frame.pack() root.mainloop() well, my problem is at frame.bind(",Button-1>", callback) callback function prints event.x and event.y. How the callback function get this two number when it has only one argument (event) Why its not: def callback(x, y): print x, y Im new to gui programming Sorry for bad eng! Thanks for replay! From jljames at gmail.com Thu Feb 1 12:50:23 2007 From: jljames at gmail.com (Jeff) Date: Thu, 1 Feb 2007 10:50:23 -0700 Subject: Suggestions ? Message-ID: <8c95e8b30702010950l500b3ba0v9300a71d1c529093@mail.gmail.com> Greetings, I am new to programming and have heard so much about Python. I have a couple of books on Python and have been to python.org many times. I am faced with a project at work where I need to develop a "searchable" database to include training materials for new hires. This will include descriptions of the apps we support along with information on which group supports them and will also include links within the descriptions to allow users to navigate to other pertinent information. I would like to lay the master directory out in an index format and would like to include a search window within the master index to provide a quick search to relative documents. I believe this is where Python will come in very handy as opposed to MS Access for example. I realize I may have to lay out the master index in an HTML format. I guess I have something else to learn now as well. Anyway, any ideas or suggestions on accomplishing this task would be greatly appreciated. Thank You in advance, Jeff James -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Thu Feb 15 12:09:06 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Feb 2007 18:09:06 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171558552.557623.274040@l53g2000cwa.googlegroups.com> Message-ID: On 2007-02-15, Michele Simionato wrote: > On Feb 13, 9:14 am, Peter Otten <__pete... at web.de> wrote: >> "Avoid inheritance" would be almost as justified :-) > > In other words, if you are inheriting just two or three methods > it may works, but when you start having dozens of methods > inherited from different sources, your code will become to look > as spaghetti code. This is why in general I (as many people > here) suggest delegation over inheritance. I consider inheritance in Python when I see that the class I'm implementing contains some sort of status code that controls behavior. For example: class Stream(object): def __init__(self, readable, writable): if readable and writable: self.io_type = 'inout' elif readable: self.io_type = 'out' else: self.io_type = 'in' That code sets me to thinking I'll get good mileage from: class Stream(object): ... class InStream(object): ... class OutStream(object): ... class InOutStream(object): ... I always get myself into trouble when I try to design a class hierarchy *before* I see something like that. -- Neil Cerutti From mark.m.mcmahon at gmail.com Sun Feb 4 07:26:44 2007 From: mark.m.mcmahon at gmail.com (Mark) Date: 4 Feb 2007 04:26:44 -0800 Subject: CTypes In-Reply-To: <1170544958.865802.120010@s48g2000cws.googlegroups.com> References: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> <1170544958.865802.120010@s48g2000cws.googlegroups.com> Message-ID: <1170592004.632364.65340@v33g2000cwv.googlegroups.com> Hi, On Feb 3, 6:22 pm, "SoutoJ... at gmail.com" wrote: > I forgot to mention I am running Windows 98SE. Hmm - pywinauto is not supported on Windows 98 - it relies competely on Unicode. You could try renaming all the functions ending in W to ending in A e.g. change GetModuleFileNameExW to GetModuleFileNameExA - but I am fairly sure that this would NOT solve all the problems you would have trying to run on W98. As far as I know (not 100% sure) but ctypes should have no problem on W98 - it is a pywinauto requirement for Unicode. Another thing to look into might be Unicows.dll (which gives some Unicode functions to W98) Mark From duncan.booth at invalid.invalid Mon Feb 12 13:08:07 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Feb 2007 18:08:07 GMT Subject: About getattr() References: <45cff433$0$6823$4d3efbfe@news.sover.net> Message-ID: Leif K-Brooks wrote: >> Why do I still need the getattr() func as below? >> >>>>> print getattr(os.path,"isdir").__doc__ >> Test whether a path is a directory > > You don't. Correct > getattr() is only useful when the attribute name is > determined at runtime. > getattr() is useful in at least 2 other situations: maybe you know the attribute name in advance, but don't know whether the object has that particular attribute, then the 3 argument form of getattr could be appropriate: print getattr(x, 'attr', 'some default') or if the attribute name isn't a valid Python identifier: print getattr(x, 'class') From gagsl-py at yahoo.com.ar Wed Feb 14 01:27:28 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 03:27:28 -0300 Subject: How can this Perl regular expression be expressed in Python? References: <8WvAh.14675$O02.10228@newssvr11.news.prodigy.net> Message-ID: En Wed, 14 Feb 2007 01:07:33 -0300, John Nagle escribi?: > Here's a large Perl regular expression, from a Perl address parser in > CPAN: > > use re 'eval'; > $Addr_Match{street} = qr/ > (?: > # special case for addresses like 100 South Street > (?:($Addr_Match{direct})\W+ (?{ $_{street} = $^N }) > ($Addr_Match{type})\b (?{ $_{type} = $^N })) > | > (?:($Addr_Match{direct})\W+ (?{ $_{prefix} = $^N }))? > (?: > ([^,]+) (?{ $_{street} = $^N }) > (?:[^\w,]+($Addr_Match{type})\b (?{ $_{type} = $^N })) > (?:[^\w,]+($Addr_Match{direct})\b (?{ $_{suffix} = $^N }))? > | > ([^,]*\d) (?{ $_{street} = $^N }) > ($Addr_Match{direct})\b (?{ $_{suffix} = $^N }) > | > ([^,]+?) (?{ $_{street} = $^N }) > (?:[^\w,]+($Addr_Match{type})\b (?{ $_{type} = $^N }))? > (?:[^\w,]+($Addr_Match{direct})\b (?{ $_{suffix} = $^N }))? > ) > ) > /ix; > > I'm trying to convert this to Python. > > Those entries like "$(Addr_Match{direct}) are other regular expressions, > being used here as subexpressions. Those have already been converted > to forms like "Addr_Match.direct" in Python. But how to call them? > Is that possible in Python, and if so, where is it documented? That would be string interpolation, like this: Addr_Match = {"direct": "some_re_string", "type": "other_re" } regexp = "%(direct)s %(type)s" % Addr_Match -- Gabriel Genellina From solrick51 at hotmail.com Mon Feb 5 06:09:33 2007 From: solrick51 at hotmail.com (solrick51 at hotmail.com) Date: 5 Feb 2007 03:09:33 -0800 Subject: Python design project In-Reply-To: <45c313d5$0$8726$ed2619ec@ptn-nntp-reader02.plus.net> References: <1170337417.236975.44070@l53g2000cwa.googlegroups.com> <45c313d5$0$8726$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1170673772.977486.172770@a75g2000cwd.googlegroups.com> I think I need to explain the things better I think, so I do; First answering the questions above; I think i have to explain the project more. With type I mean; typography/fonts/characters.. For my final exam I created the idea to treath fonts as a living organisms. There for I want to create with the help of somebody, a little program were i can import vector based fonts, and when they are imported they "turn alive" By turn alive I mean; they move random over the work area, opacity changing, changing of size/color, merge together ans some more things, little fonts changing. Because my python skills are zero, I'm looking for a partner which can help me. I'm working On mac, but windows is not a problem. From tjreedy at udel.edu Thu Feb 8 17:10:04 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Feb 2007 17:10:04 -0500 Subject: def obj() References: Message-ID: "Gert Cuykens" wrote in message news:ef60af090702081349t41fbf8d5h118b4851a4b5b460 at mail.gmail.com... | def obj(): | return {'data':'hello', | 'add':add(v)} v is undefined | def add(v): | data=data+v data is undefined | if __name__ == '__main__': | test=obj() | test.add('world') test.add is undefined | print test.data test.data is undefined | I don't know why but i have one of does none class c programing style | moods again. I was wondering if the following was possible without | using a class ? I presume you meant 'foregoing' instead of 'following'. You can do something similar with nested functions. Terry Jan Reedy From berb.web at gmail.com Mon Feb 12 13:43:42 2007 From: berb.web at gmail.com (berb.web at gmail.com) Date: 12 Feb 2007 10:43:42 -0800 Subject: MIME-Version in interpart, Python MIMEMultipart Message-ID: <1171305822.243190.9360@v45g2000cwv.googlegroups.com> list - using python's MIMEMultipart() object I've noticed that it interjects a 'MIME-Version' in the interpart header, like so... --some_MIME_Boundry Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit some_test Now, RFC1521, section 3 reads: Note that the MIME-Version header field is required at the top level of a message. It is not required for each body part of a multipart entity. It is required for the embedded headers of a body of type "message" if and only if the embedded message is itself claimed to be MIME-conformant. What I'm wondering is if anyone knows if the inclusion of the MIME- Version in the interpart header is invalid. It does not look like it to me, byt I'm looking for your opinions. Regards, berb From jeffrey at fro.man Sun Feb 4 13:46:55 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 04 Feb 2007 10:46:55 -0800 Subject: Parameter lists References: Message-ID: <12scaghamvvdb55@corp.supernews.com> Mizipzor wrote: > class Stats: > def __init__(self, *li): > self.speed = li[0] > self.maxHp = li[1] > (...) > > Or maybe there is an even niftier way that lets me iterate through > them? Using keyword arguments instead of positional parameters makes this easy: >>> class Stats: ... def __init__(self, **kw): ... self.__dict__.update(kw) ... >>> stats = Stats(speed=10, maxHp=100, armor='plate mail') >>> stats.speed 10 >>> stats.maxHp 100 >>> stats.armor 'plate mail' Jeffrey From deets at nospam.web.de Tue Feb 27 09:00:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Feb 2007 15:00:15 +0100 Subject: Calling Python Web Services from C# References: <1172583873.292450.200490@p10g2000cwp.googlegroups.com> Message-ID: <54irrgF20cd66U1@mid.uni-berlin.de> jvframework at gmail.com wrote: > I have a C# .NET cliente calling a Python web services. I pass two > string values to web service and I wanna receive a string from the > method. > > But, the server side receive my string values and the client side only > display a empty string (""). > > I generate a C# Proxy class from the python web services WSDL with > wsdl.exe tool. > > Any idea about this problem? Not until you provide some more detail. Read this on how to do so properly: http://www.catb.org/~esr/faqs/smart-questions.html Diez From http Mon Feb 26 16:26:26 2007 From: http (Paul Rubin) Date: 26 Feb 2007 13:26:26 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: <7xy7mk3919.fsf@ruckus.brouhaha.com> Tech HR writes: > No, it doesn't mean that. In fact, there is a significant faction in > the technical staff (including the CTO) who would like nothing better > than to be able to use Lisp instead of Python. But we have some pretty > compelling reasons to stick with Python, not least of which is that it > is turning out to be very hard to find Lisp programmers. (Actually, > it's turning out to be hard to find Python programmers too, but it's > easier to train a Java programmer or a Perler on Python than Lisp. We > also have fair bit of infrastructure built up in Python at this point.) There's a lot of Python users around these days, and moving from Lisp to Python is very easy. The other way around is maybe a little harder but shouldn't be too bad. You know about http://lispjobs.wordpress.com I presume. Also: http://lemonodor.com and lambda-the-ultimate.org may have more pointers to such things. > But we're a very young company (barely six months old at this point) so > we're willing to listen to most anything at this point. (We're using > Darcs for revision control. Haskell, anyone?) Haskell is really a lot different and I think the implementations aren't as mature as Lisp or Python implementations. Maybe you want to think about SML or OCaml. From jm.suresh at gmail.com Sun Feb 11 09:23:04 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 11 Feb 2007 06:23:04 -0800 Subject: gvim: doc string editing In-Reply-To: References: <1171201896.897644.60000@p10g2000cwp.googlegroups.com> Message-ID: <1171203784.325232.25980@h3g2000cwc.googlegroups.com> On Feb 11, 7:01 pm, Neil Cerutti wrote: > On 2007-02-11, jm.sur... at no.spam.gmail.com wrote: > > > Hi, I am using gvim, and am looking for a way to tell gvim to > > automatically wrap long lines into multiple lines ( by > > automatically inserting the newline character) when I edit doc > > strings. I am sure somebody must have done this. > > If tw (textwidth) is set to some apposite number, then it should > just work (unfortunately, this will also cause your code to wrap > unless you set up the comment strings properly for Python). > Alternatively, you can use the gq formatting command to wrap the > comment after it is composed. > > Do :h format_comments for the full dope. > > -- > Neil Cerutti gq works great. Thanks. - Suresh From mintern at cse.ohio-state.edu Thu Feb 22 11:13:46 2007 From: mintern at cse.ohio-state.edu (Brandon Mintern) Date: Thu, 22 Feb 2007 11:13:46 -0500 Subject: paths in modules Message-ID: I am developing a project in Python which uses several external utilities. For convenience, I am wrapping these accesses in a module. The problem is that I cannot be sure where these modules are imported from, so I am trying to figure out how to reliably execute e.g. a popen call. Example layout: toplevel_dir +-main script +-wrapper_dir +-some_wrapper +-utility_dir +-some_external_utility So in my main script, I might say: from wrapper_dir import some_wrapper some_wrapper.use_external_utility() And then in some_wrapper, I would have code like: import os def use_external_utility(): f = os.popen('utility_dir/some_external_utility') lines = f.readlines() f.close() return lines Of course, the problem with that approach is that it fails because there is no utility_dir in the CWD, which is actually top_level_dir. So my question is whether there is any way to specify that specified paths are relative to the module's directory rather than the importing file's directory. I would really like to avoid kludging together some solution that involves passing variables or having knowledge of where my module is being imported from. I am hoping that there is some simple solution to this problem that I simply haven't found in my searches so far. If so, I will humbly accept any ridicule that comes along with said simple solution :-). Thanks in advance, Brandon From bj_666 at gmx.net Fri Feb 9 01:43:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 09 Feb 2007 07:43:36 +0100 Subject: Is Python for me? References: Message-ID: In , jiddu wrote: > I'm planning to create a poker calculator, I learned some basic in > highschool years ago and I was told for beginners Python is a good > language to start. There's a recipe in the Cookbook that might be interesting for you: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415504 And a library called `poker-eval` with Python bindings: http://pokersource.org/ Ciao, Marc 'BlackJack' Rintsch From pierre.imbaud at laposte.net Thu Feb 8 04:45:00 2007 From: pierre.imbaud at laposte.net (Imbaud Pierre) Date: Thu, 08 Feb 2007 10:45:00 +0100 Subject: iso 8601, quality criteria Message-ID: <45caf119$0$25912$426a74cc@news.free.fr> for each library/module or even application, a note in [0:10] in front of every quality criterium. criteria?: completeness robustness how well tested? simplicity documentation maintenance team responsiveness usage: how many developpers picked it up and still use it? how many picked it up but gave it up? The list is an obvious oversimplification, each criterium could be discussed for hours. robustness, for instance, means: how well does it behave when illegal data is fed? A LOT of actual modules (comprising mine (:-) raise obscure exceptions. the iso8601 module is simple enough, easy to install, but fails on legal data. I guess the fix would be useful, but is it maintained? Is it in use? I used xml.dom.minidom, recently. Works fine, but I found the interface awfully complicated. Right or wrong, when I had to write some xml, I wrote my own code: better be simple, although untested, undocumented, etc, than using a module so complicated U never finished the learning curve... So, my questions would be: - how do You, other developpers, cope with this question? - is there such a base, helping to pick up existing modules? - if no, dont U think such an initiative might be useful? - Those who have to deal with iso8601 dates, how do U proceed? Ill have a look to mxdatetime, but is it the right answer? From nogradi at gmail.com Sat Feb 17 06:24:13 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 17 Feb 2007 12:24:13 +0100 Subject: Reg Google Web Toolkit and Python In-Reply-To: References: Message-ID: <5f56302b0702170324j783a0a47i5d851c8a47d11328@mail.gmail.com> > > Hi , > > We have a project where I need to read files store > > them in database in the backend.We have done this in > > python.Now we decided to use Ajax technique for user > > interface.For that we found that GWT is one of the > > best toolkits.Now I got a doubt can I interface GWT > > with python. > > Thanks , > > Shadab. You might also want to look at the javascript backend of pypy. It translates python code into javascript and has all kinds of cool mechanisms for "AJAX". pypy main page: http://codespeak.net/pypy/dist/pypy/doc/news.html javascript backend info: http://codespeak.net/pypy/dist/pypy/doc/js/webapps_with_pypy.html From gherron at digipen.edu Fri Feb 16 03:00:58 2007 From: gherron at digipen.edu (Gary Herron) Date: Fri, 16 Feb 2007 00:00:58 -0800 Subject: I'm faint why this can't work In-Reply-To: References: Message-ID: <45D564BA.70300@digipen.edu> JStoneGT at aol.com wrote: > Hello, > > I got this similar sample script from books: > > $ cat sampdict.py > #!/usr/bin/python > class SampDict(dict): > def __init__(self, filename=None): > self["name"] = filename > > But when I run it I got the errors: > > >>> from sampdict import SampDict > >>> SampDict("/etc/passwd") > Traceback (most recent call last): > File "", line 1, in ? > File "sampdict.py", line 4, in __init__ > self["name"] = filename > AttributeError: SampDict instance has no attribute '__setitem__' > > > I'm using Python 2.3.4. > > Please help.Thanks. It works just fine in all versions of Python I could find: 2.3.3, 2.3.5, 2.4, and 2.5. My only guesses: Have you mixed spaces and tabs for the indentation, so that the code Python sees is not as we see it printed? (Don't ever do that.) Do you have several copies of sampdict.py (or even sampdict.pyc) so that the copy being imported is not the one you printed? (Run Python with a -v switch to test for this possibility.) Gary Herron From tdelaney at avaya.com Tue Feb 27 15:53:47 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 28 Feb 2007 07:53:47 +1100 Subject: Python Source Code Beautifier Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ECC6@au3010avexu1.global.avaya.com> Alan Franzoni wrote: >> self.scriptcount = self.scriptcount + 1 => self.scriptcount += 1 > > the += operator is syntactic sugar just to save time... if one > doesn't use it I don't think it's a matter of beauty. This change can have semantic differences, and so should not be done for anything except basic, immutable objects (such as integers). As such, it can't be done automatically. Tim Delaney From steve at REMOVEME.cybersource.com.au Wed Feb 7 19:38:39 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Feb 2007 11:38:39 +1100 Subject: string.find for case insensitive search References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: On Wed, 07 Feb 2007 13:09:00 -0800, Don Morrison wrote: > string.find is deprecated as per the official python documentation. > > take a look at the "re" module Regular expressions are way, WAY overkill for a simple find. Just use the string methods. Instead of this: import string string.find("Norwegian Blue", "Blue") just do this: "Norwegian Blue".find("Blue") For case insensitive find: "Norwegian Blue".lower().find("Blue".lower()) (or better still, turn it into a function). -- Steven D'Aprano From steve at REMOVE.THIS.cybersource.com.au Fri Feb 9 18:23:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Feb 2007 10:23:46 +1100 Subject: Glob returning an empty list when passed a variable References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: On Fri, 09 Feb 2007 14:15:51 +0000, Steve Holden wrote: > area_name_string = '*% s*' % (Area_name) > > Interesting, I never realised until now that you can have spaces between > the percent sign and th format effector. Space is one of the flags. From the docs: The conversion flag characters are: Flag Meaning # The value conversion will use the ``alternate form'' (where defined below). 0 The conversion will be zero padded for numeric values. - The converted value is left adjusted (overrides the "0" conversion if both are given). (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. + A sign character ("+" or "-") will precede the conversion (overrides a "space" flag). http://docs.python.org/lib/typesseq-strings.html -- Steven. From nogradi at gmail.com Thu Feb 1 17:05:56 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 1 Feb 2007 23:05:56 +0100 Subject: pil, histogram, mask In-Reply-To: <1170327064.008134.151480@v33g2000cwv.googlegroups.com> References: <1170327064.008134.151480@v33g2000cwv.googlegroups.com> Message-ID: <5f56302b0702011405vb9226e0ka045b72aac50cb52@mail.gmail.com> > > I don't need the histogram really, only the mean color > > value, but as far as I can see the 'mean' attribute only applies to an > > image and a mask can not be specified. > > You can slice parts of the image, and then use the > ImageStat.Stat(im).mean > On it. > > Bye, > bearophile Okay, I'll try that, thanks a lot. From vishal at veriwave.com Sat Feb 3 03:59:13 2007 From: vishal at veriwave.com (vishal at veriwave.com) Date: Sat, 3 Feb 2007 00:59:13 -0800 (PST) Subject: Regd. Kodos Message-ID: <50310.71.109.230.173.1170493153.squirrel@mail.veriwave.com> I am trying to use Kodos..but not getting thru'..dont know whats goin on..does anyone have a regular expression for time in hh:mm:ss -Vishal From skip at pobox.com Thu Feb 1 22:23:28 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Feb 2007 21:23:28 -0600 Subject: Python does not play well with others In-Reply-To: References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> Message-ID: <17858.44720.889289.670649@montanaro.dyndns.org> John> From Aplus.net tech support: John> "No, db connectivity with Python is not supported. Modules for John> Python can't be installed by request on shared hosting." John> And these are companies that say they support Python. John> Python still isn't ready for prime time in the web hosting world. Why do you lay the blame at the feet of the Python developers? Find another hosting service. Skip From jstroud at mbi.ucla.edu Fri Feb 2 18:56:25 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 02 Feb 2007 15:56:25 -0800 Subject: How much introspection is implementation dependent? Message-ID: Hello, I wanted to automagically generate an instance of a class from a dictionary--which might be generated from yaml or json. I came up with this: # automagical constructor def construct(cls, adict): dflts = cls.__init__.im_func.func_defaults vnames = cls.__init__.im_func.func_code.co_varnames argnames = vnames[1:-len(dflts)] argvals = [adict.pop(n) for n in argnames] return cls(*argvals, **adict) I'm wondering, I did a lot of introspection here. How much of this introspection can I count on in other implementations. Is this a byproduct of CPython? Will all classes have these attributes, even classes imported from shared objects? It would be nice to rely on these things. Below is the example (optional reading). James == #! /usr/bin/env python # automagical constructor def construct(cls, adict): dflts = cls.__init__.im_func.func_defaults vnames = cls.__init__.im_func.func_code.co_varnames argnames = vnames[1:-len(dflts)] argvals = [adict.pop(n) for n in argnames] return cls(*argvals, **adict) def test(): class C(object): def __init__(self, arg1, arg2, kwa3=3): self.argsum = arg1 + arg2 self.kwsum = kwa3 def __str__(self): return "%s & %s" % (self.argsum, self.kwsum) # now a dict for autmagical generation adict = {'arg1':1, 'arg2':2, 'kwa3':42} print '======== test 1 ========' print adict print construct(C, adict) adict = {'arg1':1, 'arg2':2} print print '======== test 2 ========' print adict print construct(C, adict) if __name__ == "__main__": test() From python at rcn.com Wed Feb 14 03:11:36 2007 From: python at rcn.com (Raymond Hettinger) Date: 14 Feb 2007 00:11:36 -0800 Subject: Fast constant functions for Py2.5's defaultdict() In-Reply-To: References: <1171393305.268249.268580@q2g2000cwa.googlegroups.com> Message-ID: <1171440696.431692.10110@q2g2000cwa.googlegroups.com> On Feb 13, 5:09 pm, Giovanni Bajo wrote: > > The itertools.repeat(const).next approach wins on speed and > > flexibility. > > But it's the most unreadable too. Not really. It's unusual but plenty readable (no surprise that repeat(0) repeatedly gives you zero). I think it more surprising that int() with no arguments gives you a zero. > I'm surprised that defaultdict(int) is > slower than the lambda one though. What's the reason? All that comes to mind is that int() has to call PyArg_ParseTupleAndKeywords() while the lambda is unburdened by argument passing. Raymond From JStoneGT at aol.com Mon Feb 12 05:15:41 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Mon, 12 Feb 2007 05:15:41 EST Subject: sort sort sort Message-ID: I do need sorting a dict via its values. Please help give some reference or code samples. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Feb 6 14:05:45 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Feb 2007 20:05:45 +0100 Subject: XMLRPC Server In-Reply-To: <45C868FB.909@sweetapp.com> References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> <45C868FB.909@sweetapp.com> Message-ID: Brian Quinlan wrote: > Actually, you might not have to. 2000 calls/minute isn't that big, > assuming you have a decent server. well, if you're talking pure CGI, you need to start the interpreter, import the required modules, connect to the database, unmarshal the xml-rpc request, talk to the database, marshal the response, and shut down, in less than 30 milliseconds. just importing the CGI module (or the database module) can take longer than that... From tiedon_jano at hotmail.com Wed Feb 7 12:48:39 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Wed, 07 Feb 2007 17:48:39 GMT Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170860862.438897.244820@a75g2000cwd.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> <1170795607.938431.144340@p10g2000cwp.googlegroups.com> <45c8f5b5$0$19714$426a74cc@news.free.fr> <1170854927.013819.320020@a75g2000cwd.googlegroups.com> <1170860862.438897.244820@a75g2000cwd.googlegroups.com> Message-ID: jeremito kirjoitti: > On Feb 7, 8:28 am, "jeremito" wrote: >> On Feb 6, 5:10 pm, Bruno Desthuilliers >> >> >> >> wrote: >>> jeremito a ?crit : >>> > On Feb 6, 2:36 pm, Bruno Desthuilliers > wrote: >>> (snip) >>> >>Here's an alternative implementation, so you get the idea. >>> >>class Xs(dict): >>> oops ! I meant: >>> class Xs(object): >>> of course... >>> (snip) >>>> I guess I just >>>> need more experience. >>> Possibly - but not only. You may want to have a look at the >>> FineManual(tm) for all this kind of "magic", starting with :http://docs.python.org/ref/specialnames.htmlhttp://docs.python.org/re... >>> HTH >> Thanks again! Sometimes the problem is simply not knowing where to >> find the documentation, or finding the right portion of the >> documentation. Your help has been invaluable. >> >> Jeremy > > One more question. I will be asking for the value of cs.xT *many* > (~millions) times. Therefore I don't want it's value to be calculated > on the fly. How can I set the value of xT whenever xS, xF, or xG are > changed, but not allow it to be set directly? From the example given > previously, it seems like it can't be done this way. > > Thans, > Jeremy > I'm certainly no wizard in timing, but here goes: Using the class definition given to you by Bruno, adding the following to the end (and 'import timeit' at the start): #============ lst = timeit.Timer('for i in xrange(10): xx=xs.xT', \ 'from __main__ import Xs;xs = Xs()').repeat(100,1000) lst.sort() print lst print 'Average:', sum(lst)/100 #============ I get the output: [0.017246605364648282, 0.01727426251101738, 0.017275659336591698, 0.017290745052793044, 0.01733264982001903, 0.017347735536220377, and so on ... 0.029063749722380933, 0.029163762433493667, 0.029422733894950315, 0.029790378386079785] Average: 0.0182474979362 Thus: A 1000 assignments take a little over 18 milliseconds. The largest values in the list are probably caused bu GC occurring. But even 30 ms / 1000 iterations i.e. 30 microseconds per fetch seems to be fast enough. All this depends of course on the computer used. Mine is on the fast side, you might test it on your PC. The correct way of programming is to find a good simple algorithm and the data structures needed, to program a clean solution with them and then when you've got a correctly operating application and THEN IF you need speed try to do something about it. "Premature optimization is the worst evil" or something like that is how the saying goes. Hopefully I'm not leading you astray by being a novice in using the timeit module. HTH, Jussi From __peter__ at web.de Fri Feb 16 08:14:11 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Feb 2007 14:14:11 +0100 Subject: Regex - where do I make a mistake? References: <1171629872.499083.150140@p10g2000cwp.googlegroups.com> Message-ID: Johny wrote: > I have > string="""55. > 128 > 170 > """ > > where I need to replace > 55. > 170 > > by space. > So I tried > > ############# > import re > string="""55. class="test123">128170 > """ > Newstring=re.sub(r'.*'," ",string) > ########### > > But it does NOT work. > Can anyone explain why? "(?!123)" is a negative "lookahead assertion", i. e. it ensures that "test" is not followed by "123", but /doesn't/ consume any characters. For your regex to match "test" must be /immediately/ followed by a '"'. Regular expressions are too lowlevel to use on HTML directly. Go with BeautifulSoup instead of trying to fix the above. Peter From wattersmt at gmail.com Tue Feb 6 10:50:52 2007 From: wattersmt at gmail.com (wattersmt at gmail.com) Date: 6 Feb 2007 07:50:52 -0800 Subject: Running long script in the background In-Reply-To: <1170776253.027044.253050@q2g2000cwa.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170769014.352466.135280@h3g2000cwc.googlegroups.com> <1170776253.027044.253050@q2g2000cwa.googlegroups.com> Message-ID: <1170777052.386308.290760@q2g2000cwa.googlegroups.com> On Feb 6, 10:37 am, "watter... at gmail.com" wrote: > On Feb 6, 8:36 am, "jasonmc" wrote: > > > > Does anybody know a way to make output show in real time? > > > You can put: #!/usr/bin/python -u > > at the top of the script to have unbuffered binary stdout and stderr. > > Thanks. I tried that but it still times out waiting for output. > > Everything works fine until I call the popen function, then it > freezes. What I want is to print the output in real time, just like > it does when I run it from a shell. I tried flushing stdout and the same thing happens. As soon as the os.popen(command) line runs it stops there, the next print statement never even runs. I've also tried using os.spawnv to make the process run in the background but then the ssh command never runs. From mensanator at aol.com Wed Feb 21 20:08:45 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 21 Feb 2007 17:08:45 -0800 Subject: Convert to binary and convert back to strings In-Reply-To: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <1172106524.976297.262330@p10g2000cwp.googlegroups.com> On Feb 21, 5:50 pm, "Harlin Seritt" wrote: > Hi... > > I would like to take a string like 'supercalifragilisticexpialidocius' > and write it to a file in binary forms -- this way a user cannot read > the string in case they were try to open in something like ascii text > editor. I'd also like to be able to read the binary formed data back > into string format so that it shows the original value. Is there any > way to do this in Python? > > Thanks! > > Harlin import gmpy # GNU Multi-Prceision library for Python f = open('getty.txt','r') s = f.read() f.close print print 'source file:' print print s count = 0 f = open('getty_binary.txt','w') for c in s: o = ord(c) b = gmpy.digits(o,2) d = '0'*(8-len(b)) + b w = '%s ' % d f.write(w) count += 1 if count % 5==0: f.write('\n') f.close f = open('getty_binary.txt','r') s = f.readlines() f.close print print 'binary file:' print for i in s: print i, print c = [] for k in s: q = k.split() for m in q: c.append(chr(int(m,2))) new_s = ''.join(c) print print 'decoded binary:' print print new_s print ## output ## source file: ## ## Four score and seven years ago, ## our fathers brought forth on this continent ## a new nation, conceived in liberty ## and dedicated to the propostion that ## all men are created equal. ## ## ## binary file: ## ## 01000110 01101111 01110101 01110010 00100000 ## 01110011 01100011 01101111 01110010 01100101 ## 00100000 01100001 01101110 01100100 00100000 ## 01110011 01100101 01110110 01100101 01101110 ## 00100000 01111001 01100101 01100001 01110010 ## 01110011 00100000 01100001 01100111 01101111 ## 00101100 00001010 01101111 01110101 01110010 ## 00100000 01100110 01100001 01110100 01101000 ## 01100101 01110010 01110011 00100000 01100010 ## 01110010 01101111 01110101 01100111 01101000 ## 01110100 00100000 01100110 01101111 01110010 ## 01110100 01101000 00100000 01101111 01101110 ## 00100000 01110100 01101000 01101001 01110011 ## 00100000 01100011 01101111 01101110 01110100 ## 01101001 01101110 01100101 01101110 01110100 ## 00001010 01100001 00100000 01101110 01100101 ## 01110111 00100000 01101110 01100001 01110100 ## 01101001 01101111 01101110 00101100 00100000 ## 01100011 01101111 01101110 01100011 01100101 ## 01101001 01110110 01100101 01100100 00100000 ## 01101001 01101110 00100000 01101100 01101001 ## 01100010 01100101 01110010 01110100 01111001 ## 00001010 01100001 01101110 01100100 00100000 ## 01100100 01100101 01100100 01101001 01100011 ## 01100001 01110100 01100101 01100100 00100000 ## 01110100 01101111 00100000 01110100 01101000 ## 01100101 00100000 01110000 01110010 01101111 ## 01110000 01101111 01110011 01110100 01101001 ## 01101111 01101110 00100000 01110100 01101000 ## 01100001 01110100 00001010 01100001 01101100 ## 01101100 00100000 01101101 01100101 01101110 ## 00100000 01100001 01110010 01100101 00100000 ## 01100011 01110010 01100101 01100001 01110100 ## 01100101 01100100 00100000 01100101 01110001 ## 01110101 01100001 01101100 00101110 00001010 ## ## ## decoded binary: ## ## Four score and seven years ago, ## our fathers brought forth on this continent ## a new nation, conceived in liberty ## and dedicated to the propostion that ## all men are created equal. From steve at REMOVEME.cybersource.com.au Wed Feb 21 03:21:54 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 19:21:54 +1100 Subject: Python 3.0 unfit for serious work? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> <7x1wkkxnmn.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 20 Feb 2007 21:19:26 -0800, John Nagle wrote: > Well, something faster really should take over. It's a bit > embarassing that the main implementation of Python is still a > pure interpreter. Even Javascript has a JIT compiler now. > And it's tiny, under 1MB. Python has a compiler, just like Java. That's where the .pyc files come from. You might also notice the built-in function "compile", which compiles text strings into byte-code and puts it into a code object. The dis module may also be of interest. -- Steven D'Aprano From rganesan at myrealbox.com Mon Feb 5 01:10:45 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Mon, 05 Feb 2007 11:40:45 +0530 Subject: problems loading modules References: <1170654370.545302.277060@k78g2000cwa.googlegroups.com> Message-ID: >>>>> Frank writes: >>>> import random >>>> from numpy import * >>>> >>>> print random.randrange(10) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'randrange' >>>> > Here it does not work. Here's a clue. ====== >>> import numpy >>> numpy.random ======= Ganesan -- Ganesan Rajagopal From sturlamolden at yahoo.no Thu Feb 22 13:36:05 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 22 Feb 2007 10:36:05 -0800 Subject: export an array of floats to python In-Reply-To: References: Message-ID: <1172169365.508476.279360@a75g2000cwd.googlegroups.com> On Feb 22, 5:40 pm, Peter Wuertz wrote: > I'm writing a C module for python, that accesses a special usb camera. > This module is supposed to provide python with data (alot of data). Then > SciPy is used to fit the data. > > My question is, how to make python read from a C array? By reading the > documentation, one could get the impression that PyBufferObjects do that > job. Never mind the buffer object. Since you use SciPY I assume you want to wrap your C array with a NumPy array. This can be accomplished using the API call: PyObject *PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data); nd is the number of dimensions. dims is an array of length nd containing the size in each dimension. typenum can e.g. be NPY_FLOAT, NPY_DOUBLE, NPY_BYTE, NPY_UBYTE, NPY_INT, NPY_UINT, NPY_SHORT, NPY_USHORT, etc. Don't deallocate the data buffer until the NuPy array is deleted. Otherwise, you could create a new array from scratch using: PyObject *PyArray_SimpleNew(int nd, npy_intp* dims, int typenum); Then, use void *PyArray_DATA(PyObject* obj); to get a pointer to the data buffer. Then fill in (e.g. memcpy) whatever you have from your camera. If you e.g. have unsigned integers from the camera and want to cast them into Python floats: unsigned int *camera_buffer = ... /* whatever */ npy_int dim = {480, 640}; /* whatever the size of your data, in C- order */ PyObject *myarray; double *array_buffer; int i; myarray = PyArray_SimpleNew(2, &dim, NPY_DOUBLE); Py_INCREF(myarray); array_buffer = (double *)PyArray_DATA(myarray); for (i=0; i<640*480; i++) *array_buffer++ = (double) *camera_buffer++; Now return myarray and be happy. From michele.simionato at gmail.com Sun Feb 18 04:59:53 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Feb 2007 01:59:53 -0800 Subject: cmd all commands method? In-Reply-To: <1171792183.564570.307940@m58g2000cwm.googlegroups.com> References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> <53per7F1t12jjU1@mid.individual.net> <1171786661.599128.234300@k78g2000cwa.googlegroups.com> <1171792183.564570.307940@m58g2000cwm.googlegroups.com> Message-ID: <1171792793.211346.163520@p10g2000cwp.googlegroups.com> On Feb 18, 10:49 am, "placid" wrote: > On Feb 18, 7:17 pm, "Michele Simionato" > > > Yes, he is talking about the cmd module:http://docs.python.org/dev/lib/Cmd-objects.html. > > However that module was never intended as a real interpreter, so > > defining variables > > as the OP wants would require some work. > > > Michele Simionato > > How much work does it require ? Have you ever written an interpreter? It is a nontrivial job. Michele Simionato From lance at augustmail.com Thu Feb 8 16:54:26 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Thu, 08 Feb 2007 21:54:26 GMT Subject: excel find last column Message-ID: Hi all, I am trying to find the last used column in an excel sheet using win32com: lastcol = sh.UsedRange.Columns.Count works, but only if there is no formatting. I want to allow formatting in the columns. I would rather use the code below because formatted cells are irrelevant. using: lastcol = sh.UsedRange.Find("*",xlPrevious,xlByColumns).Column I get the error that xlPrevious is not defined. I am using Activestate PythonWin 2.3.5. makepy.py cannot be located. Is makepy.py needed? If so, where do I find it and how do I install it? Seems like I ran into this problem before but I cannot remember how I solved it? Lance From ccw.thomas at gmail.com Mon Feb 26 05:31:39 2007 From: ccw.thomas at gmail.com (ThomasC) Date: 26 Feb 2007 02:31:39 -0800 Subject: The Python interactive interpreter has no command history In-Reply-To: <45d494c1$0$5104$ba4acef3@news.orange.fr> References: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> <45d494c1$0$5104$ba4acef3@news.orange.fr> Message-ID: <1172485899.900548.84710@v33g2000cwv.googlegroups.com> Thank you a lot! I will try add readline library in my system. Thank you. On 2?16?, ??1?13?, Laurent Rahuel wrote: > Hi, > > You need to have readline installed. > > Laurent > > ThomasCwrote: From python at hope.cz Wed Feb 14 11:52:01 2007 From: python at hope.cz (Johny) Date: 14 Feb 2007 08:52:01 -0800 Subject: Urllib2 and timeouts Message-ID: <1171471921.142012.247450@p10g2000cwp.googlegroups.com> In my script I started using urllib2 to connect to a list of servers.It works well but only until a server from the list is not available.Then if it is down , there is a timeout and my script ends with the error. So, if I have a list of 10 servers, and the second from the list is not available , no others are used. Is there a way how to solve that problem, so that servers after the server that is not available will be used too? Thanks for help L. From skip at pobox.com Fri Feb 2 18:25:23 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 2 Feb 2007 17:25:23 -0600 Subject: Python does not play well with others In-Reply-To: <7xejp89pa9.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xejp89pa9.fsf@ruckus.brouhaha.com> Message-ID: <17859.51299.20226.524925@montanaro.dyndns.org> Paul> Why is it that PHP and J2SE manage deal with this problem but Paul> Python cannot? I can't speak authoritatively for either PHP or J2SE, but I suspect the latter at least has some signifiant monetary support (if not outright gobs of human resources) from Sun. PHP seems to have a more limited application domain (web apps) from which it has expanded a bit. Can I build a PHP site out of the box with a PostgreSQL or Oracle backend? Does J2SE have something comparable to Numpy or scipy? While might do the occasional bit of Python hacking for free, I still need to put food on the table. My employer doesn't care if MySQLdb (to use one of your examples) is delivered with Python or not. They aren't likely to want to support me to solve your problems. Skip From Bulkan at gmail.com Sat Feb 17 08:29:25 2007 From: Bulkan at gmail.com (placid) Date: 17 Feb 2007 05:29:25 -0800 Subject: cmd all commands method? Message-ID: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> Hi all, if i want to treat every cmdloop prompt entry as a potential command then i need to overwrite the default() method ? What i want to achieve is to be able to support global variable creation for example; res = sum 1 2 this would create a variable res with the result of the method do_sum() ? then would i be able to run; sum a 5 this would return 8 or an error saying that res is not defined Cheers From grante at visi.com Thu Feb 22 23:29:52 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 23 Feb 2007 04:29:52 -0000 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> <1172187153.711933.37870@m58g2000cwm.googlegroups.com> Message-ID: <12tsre08ha0p673@corp.supernews.com> On 2007-02-22, tac-tics wrote: > Tip: don't try learning perl. > > I agree the colon is largely redundant, but it's not > unreasonable. A certain amount of redundancy in languages (artificial or natrual) is a good thing. It makes error detection and correction far easier. -- Grant Edwards grante Yow! ... I think I'm at having an overnight visi.com sensation right now!! From koder.mail at gmail.com Tue Feb 20 05:59:09 2007 From: koder.mail at gmail.com (KoDer) Date: Tue, 20 Feb 2007 12:59:09 +0200 Subject: Python-list Digest, Vol 41, Issue 286 In-Reply-To: References: Message-ID: <6e8b06c90702200259r32b315c2q7a56aaed47a18015@mail.gmail.com> > Subject: Can I reverse eng a .pyc back to .py? > The short story is that someone left, but before he left he checked in a > .pyc and then both the directory was destroyed and the backups all got > TIA https://svn.cs.pomona.edu/sys/src/konane/pyunparse.py Need add new AST nodes if You want to use it with python2.5. -- K.Danilov aka KoDer From gibo at gentlemail.com Mon Feb 19 18:58:40 2007 From: gibo at gentlemail.com (GiBo) Date: Tue, 20 Feb 2007 12:58:40 +1300 Subject: Checking for EOF in stream Message-ID: <45DA39B0.7020403@gentlemail.com> Hi! Classic situation - I have to process an input stream of unknown length until a I reach its end (EOF, End Of File). How do I check for EOF? The input stream can be anything from opened file through sys.stdin to a network socket. And it's binary and potentially huge (gigabytes), thus "for line in stream.readlines()" isn't really a way to go. For now I have roughly: stream = sys.stdin while True: data = stream.read(1024) process_data(data) if len(data) < 1024: ## (*) break I smell a fragile point at (*) because as far as I know e.g. network sockets streams may return less data than requested even when the socket is still open. I'd better like something like: while not stream.eof(): ... but there is not eof() method :-( This is probably a trivial problem but I haven't found a decent solution. Any hints? Thanks! GiBo From mail at microcorp.co.za Sun Feb 11 01:09:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 11 Feb 2007 08:09:58 +0200 Subject: pygame and python 2.5 References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <17868.46349.59089.178486@montanaro.dyndns.org><013b01c74cd8$8d913860$03000080@hendrik> Message-ID: <003601c74da3$45065780$03000080@hendrik> "Steve Holden" > Hendrik van Rooyen wrote: > > wrote: > > "Ben Sizer" wrote: > > > > > >> Ben> Python extensions written in C require recompilation for each new > >> Ben> version of Python, due to Python limitations. > >> > >> Can you propose a means to eliminate this limitation? > >> > > > > Yes. - Instead of calling something, send it a message... > > > I suppose you are proposing to use the ISO 19999.333 generic > message-passing interface for this? The one that doesn't actually call a > function to pass a message? > Actually I am not aware that this ISO standard exists. My feeling about ISO standards in general are such that I would rather have *anything* else than an ISO standard. These feelings are mainly caused by the frustration of trying to decipher standards written in standardese, liberally sprinkled with non standard acronyms... Its very interesting to learn that you can pass a message without doing a call - when I next need to entertain a children's party as a magician I will endeavour to incorporate it into my act. Thanks for the tip. But more seriously, the concept is that you should couple as loosely as possible, to prevent exactly the kind of trouble that this thread talks about. Just as keyword parameters are more robust than positional parameters, the concept of doing something similar to putting a dict on a queue, is vastly more future-proof than hoping that your call will *get through* when tomorrow's compiler buggers around with the calling convention. One tends to forget that calling also builds messages on the stack. When you boil it right down, all you need for a minimalistic interface are four message types: - get something's value - set something to a value - return the requested value - do something This is not the most minimalistic interface, but its a nice compromise. The advantages of such loose coupling are quite obvious when you think about them, as you don't care where the worker sits - on the other side of the world over the internet, or in the same room in another box, or in the same box on another processor, or on the same processor in another process, or in the same process in another thread... The problem with all this, of course, is the message passing mechanism, as it is not trivial to implement something that will address all the cases. A layered approach (ISO ? ; - ) ) could do it... But Skip asked how to sort it, and this would be My Way. (TM circa 1960 F Sinatra) - Hendrik From lbates at websafe.com Mon Feb 26 16:15:55 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 26 Feb 2007 15:15:55 -0600 Subject: getting info on remote files In-Reply-To: <1172523279.352084.92920@t69g2000cwt.googlegroups.com> References: <1172523279.352084.92920@t69g2000cwt.googlegroups.com> Message-ID: <45E34E0B.5080802@websafe.com> gabriel.altay at gmail.com wrote: > hello everyone, > > Im trying to write some python code that will return information (file > size, last modified ...) about files on a remote computer that I have > 'no password' ssh access to. Ive been able to write code that logs on > to remote computers and I can issue a command using, > > os.system(ssh blah.blah.blah.org "ls -l myfile") > > but how do I store the information returned by the ls command into a > variable. The primary goal of this is to > 1. check file size on remote computer > 2. scp file to local computer > 3. make sure file size of copy and original are the same > > any suggestions would be appreciated > > thanks > gabe > Why not just use rsync across the ssh tunnel to synchronize the remote file to local file? This works great and you don't have to do much. -Larry From cito at online.de Sun Feb 11 06:53:58 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 11 Feb 2007 12:53:58 +0100 Subject: Problem with reimporting modules Message-ID: I'm currently investigating a problem that can hit you in TurboGears when Kid template modules are reloaded in the background, because in certain situations, global variables suddenly are set to None values. I tracked it down to the following behavior of Python. Assume you have a module hello.py like that: ---- hello. py ---- greeting = 'Hello!' def print_hello(): print greeting ------------------- Now run the following code: from hello import print_hello print_hello() import sys del sys.modules['hello'] # delete module import hello # recreate module print_hello() The second print_hello() prints "None" instead of "Hello!". Why is that? I had expected that it either prints an error or print "Hello!" as well. Is this intended behavior of Python? -- Christoph From sickcodemonkey at gmail.com Wed Feb 28 13:41:12 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 28 Feb 2007 13:41:12 -0500 Subject: Py2EXE problem In-Reply-To: References: <2adc542f0702271839u472dc57aj8c9bc6d7ad3c660d@mail.gmail.com> <2adc542f0702281009i2fd2c5e9nc626b7e34b80c270@mail.gmail.com> Message-ID: <2adc542f0702281041p5b6526dfk2a7b972650816b46@mail.gmail.com> Awesome. That is good to know. On 2/28/07, Thomas Heller wrote: > > Sick Monkey schrieb: > > Ok I found an extremely easy way to resolving this issue (I cannot > believe I > > did not think of it sooner). > > > > After Py2exe created the .exe file I noticed a "library.zip" file. I > took a > > look at the Py2exe output, and saw all of the libraries that it failed > to > > insert. I copied all of the .pyc that my application needed and > inserted > > them in the "email folder" within the library.zip. I fired up the > > application and it worked like a champ. > > > > Even easier would be to let py2exe include the whole email package. > One solution is to run > 'setup.py py2exe -p email' > > Thomas > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From toolmaster at 163.com Wed Feb 28 21:08:00 2007 From: toolmaster at 163.com (WaterWalk) Date: 28 Feb 2007 18:08:00 -0800 Subject: Make Tkinter canvas respond to MouseWheel event Message-ID: <1172714879.952669.42890@v33g2000cwv.googlegroups.com> Hello. When I tried to make Tkinter canvas widget respond to MouseWheel event on Windows XP, I failed. The canvas just doesn't receive MouseWheel event. I used bind_all to find out which widget receives this event and the result showed that only the top Tk widget gets it. This is really annoying. I wonder if this problem exists on other platform. I googled, but found no appliable solution, so I wrote one as following. It's not perfect, but works well for me. Please comment on my implementation, and if you have better solution, please show it. In this implementation, I bind the MouseWheel to the toplevel window which contains the canvas. To test if the canvas shall scroll, I check if the coordinates of the mouse is within the canvas. from Tkinter import * class ScrolledCanvas(Canvas): def __init__(self, parent, xscroll=False, yscroll=False, *args, **kargs): frm = Frame(parent) frm1 = Frame(frm) Canvas.__init__(self, frm1, *args, **kargs) self.pack(side=LEFT, fill=BOTH, expand=YES) frm1.pack(side=TOP, fill=BOTH, expand=YES) frm2 = Frame(frm) frm2.pack(side=BOTTOM, expand=YES, fill=X) if xscroll: xsbar = Scrollbar(frm2) xsbar.config(orient=HORIZONTAL) xsbar.config(command=self.xview) self.config(xscrollcommand=xsbar.set) xsbar.pack(fill=BOTH, expand=YES) self.winfo_toplevel().bind('', self.onMouseWheelX) if yscroll: ysbar = Scrollbar(frm1) ysbar.config(orient=VERTICAL) ysbar.config(command=self.yview) self.config(yscrollcommand=ysbar.set) ysbar.pack(side=RIGHT, fill=BOTH, expand=YES) self.winfo_toplevel().bind('', self.onMouseWheelY) self.pack = frm.pack # because the canvas is not contained in a frame self.canvasFrame = frm def onMouseWheelY(self, event): if event.widget == self.winfo_toplevel() and \ self.bInCanvas(event.x, event.y): self.yview_scroll(-event.delta, UNITS) def onMouseWheelX(self, event): if event.widget == self.winfo_toplevel() and \ self.bInCanvas(event.x, event.y): self.xview_scroll(-event.delta, UNITS) def bInCanvas(self, x, y): if x > self.canvasFrame.winfo_x() and \ y > self.canvasFrame.winfo_y() and \ x < self.canvasFrame.winfo_x() + int(self.winfo_width()) and \ y < self.canvasFrame.winfo_y() + int(self.winfo_height()): return True return False def test(): top = Frame() top.pack(expand=YES, fill=BOTH) sc = ScrolledCanvas(top, xscroll=True, yscroll=True, bg='Brown', relief=SUNKEN) sc.config(scrollregion=(0,0,1000, 1000)) sc.config(yscrollincrement=1) sc.config(xscrollincrement=1) sc.pack() for i in range(10): sc.create_text(150, 50+(i*100), text='spam'+str(i), fill='beige') top.mainloop() if __name__ == '__main__': test() From willievdm at gmail.com Mon Feb 5 03:11:21 2007 From: willievdm at gmail.com (willievdm at gmail.com) Date: 5 Feb 2007 00:11:21 -0800 Subject: Assigning pointer to PySwigObject in Boost Message-ID: <1170663081.223210.218110@v33g2000cwv.googlegroups.com> Hi all I'm working with Boost.Python at the moment and have to do the following: -Using Boost, assign a char* in C++ to a PySwigObject (SWIG exposed object) of type uchar*, which is received in C++ as a boost::python::object class. The uchar* pointer in the PySwigObject points to a buffer containing image data. All I wish to do is assign a C++ pointer that is also pointing to a buffer with image data to the PySwigObject pointer and send it back to Python. The PySwigObject is part of the CvMat class used with OpenCV for image-processing in Python. It is already wrapped in SWIG, so I CANNOT change it. I've already been to the python Wiki that explains how to extract SWIG exposed pointers in python (http:// wiki.python.org/moin/boost.python/HowTo), but this does NOT tell me how to do the opposite: assigning C++ pointers to SWIG exposed pointers with Boost. Any tips or tricks to get this working? Thanks Will From jordan.taylor2 at gmail.com Wed Feb 7 12:43:57 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 7 Feb 2007 09:43:57 -0800 Subject: Running long script in the background In-Reply-To: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> Message-ID: <1170870237.380149.114370@v33g2000cwv.googlegroups.com> On Feb 6, 8:26 am, "watter... at gmail.com" wrote: > Hello, > > I am trying to write a python cgi that calls a script over ssh, the > problem is the script takes a very long time to execute so Apache > makes the CGI time out and I never see any output. The script is set > to print a progress report to stdout every 3 seconds but I never see > any output until the child process is killed. > > Here's what I have in my python script: > > command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % > (host, domuname) > output = os.popen(command) > for line in output: > print line.strip() > > Here's a copy of the bash script. > > http://watters.ws/script.txt > > I also tried using os.spawnv to run ssh in the background and nothing > happens. > > Does anybody know a way to make output show in real time? Just a little note: os.popen has been replaced by the subprocess module. ;D From pydecker at gmail.com Sun Feb 18 09:14:05 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 18 Feb 2007 09:14:05 -0500 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: On 2/17/07, Stef Mientki wrote: > Some examples: > - Creating a treeview (like in the M$ explorer), with full edit capabilities and full drag & drop > facilities: Delphi takes about 40 lines of code (most of them even ^C ^V). > - Creating a graphical overview of relations between database tables, which can be graphical > manipulated by the user (like in M$ Access): Delphi 20 lines of code. > I wonder what this costs in Python ? You really need to get your thinking straightened out. You can't compare Delphi to Python; Delphi is a product that uses Pascal as its language, while Python is a language. When you compare a product for a language to an entire language, it makes the rest of your arguments look silly. BTW, you said you looked at the Dabo Class Designer - did you know that that tool itself was written in Dabo? The power is there. The fact that you couldn't completely understand it in a brief review says more about you than it does about Python, wxPython or Dabo. -- # p.d. From paul at boddie.org.uk Thu Feb 22 11:04:18 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Feb 2007 08:04:18 -0800 Subject: plugin development best practices In-Reply-To: <545q9iF1ujiklU1@mid.uni-berlin.de> References: <545q9iF1ujiklU1@mid.uni-berlin.de> Message-ID: <1172160258.523074.299770@q2g2000cwa.googlegroups.com> On 22 Feb, 16:13, "Diez B. Roggisch" wrote: > > Darn. You're right of course - I just got the basic idea, and formed in my > mind the "get the modules filename, thus the path, glob over it for *py, > and thus get the subsequent module names"-pattern. Which is trivial of > course, but not as trivial as just dir(module) The __init__.py file of a plugins package could contain something like this: # Start def init(): import os global __all__ this_dir = os.path.split(__file__)[0] py_suffix = os.path.extsep + "py" __all__ = [] for filename in os.listdir(this_dir): if os.path.isdir(os.path.join(this_dir, filename)) and \ os.path.exists(os.path.join(this_dir, filename, "__init__" + py_suffix)): __all__.append(filename) else: module, suffix = os.path.splitext(filename) if suffix == py_suffix and module != "__init__": __all__.append(module) init() del init # End This should populate the __all__ attribute of the package with then names of any submodules or subpackages. Although that in itself won't provide the names of the plugins via the dir function, the __all__ attribute is some kind of standard, and things like "from plugins import *" will import all the known plugins. In fact, if you add such an import statement to the end of the above code, you'll get all the names of the plugins stored within the package (and thus returned by the dir function) because the submodules and subpackages will actually have been imported. Even reloading the plugins package will update the __all__ attribute, although things like the unloading or removal of plugins might be challenging in a solution where such things are automatically imported. Having a variation of the above function in the standard library could be fairly useful, I suppose. Paul From dlenski at gmail.com Thu Feb 15 15:59:37 2007 From: dlenski at gmail.com (Dan Lenski) Date: 15 Feb 2007 12:59:37 -0800 Subject: Python code to do the *server* side of digest authentication? In-Reply-To: References: <1171570425.442828.73170@p10g2000cwp.googlegroups.com> Message-ID: <1171573177.380015.190240@p10g2000cwp.googlegroups.com> On Feb 15, 3:19 pm, Larry Bates wrote: > I think that is because normally the web server does the authentication on the > server side. Why not use Apache to do the digest authentication? > > http://httpd.apache.org/docs/2.0/mod/mod_auth_digest.html > > -Larry Hi Larry, I'm sorry that I wasn't clear in my original post! I don't need to do the server authentication on the proxy (WWW-Authentication and Authorization). What I need to do is the *proxy* authentication (Proxy-Authentication and Proxy-Authorization). Those headers are identical to the first pair, but they are handled by the proxy; if the client isn't authorized, then they can't use the proxy. Dan From dursuncaglar at gmail.com Tue Feb 6 21:16:25 2007 From: dursuncaglar at gmail.com (dursuncaglar at gmail.com) Date: 6 Feb 2007 18:16:25 -0800 Subject: VIDEO: US OIL NAZIS MAKE FUN OF KIDS In-Reply-To: <1170808713.898554.138550@a75g2000cwd.googlegroups.com> References: <1170807844.153137.308590@p10g2000cwp.googlegroups.com> <1170808713.898554.138550@a75g2000cwd.googlegroups.com> Message-ID: <1170814585.310829.35430@a34g2000cwb.googlegroups.com> There is more ... Some American soldiers raped Iraqi girls and The conservatives living in America still says they are not guilty.Bush must take responsible of these situation.These are massed most of Americans. thermate at india.com wrote: > Pretzel, please include scientific newsgroups like > sci.math,comp.lang.python,sci.optics,soc.culture.usa,soc.culture.europe > in your valuable posts > > On Feb 6, 4:24 pm, "M?bius Pretzel" > wrote: > > Breaking News: US Soldiers Do It Again- Please Watch! > > By: Seele > > > > 06.02.2007 > > > > US soldiers insulting and taunting little hungry Iraqi kids, asking > > them : > > > > "You fuck donkeys, right ? Donkey. Hey you fuck donkeys right ? " > > > > The Iraqi kids of course don t know what the US soldier says, but seem > > to believe that the soldier is asking them something good - and answer > > with "yes". > > > > US soldier: > > > > "Yeah ! Y'fucked a donkey. Are they good, he ? You're a donkey, > > right ? Yes, Donkey-fucker. Ah Donkey-fucker, alright ! " > > > > http://www.liveleak.com/view?i=52d7e3cd11 > > > > --- > > > > Every last US Oil Nazi DESERVES an IED shoved up his ass. From mensanator at aol.com Sat Feb 3 16:52:10 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 3 Feb 2007 13:52:10 -0800 Subject: Decimating Excel files In-Reply-To: References: Message-ID: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> On Feb 3, 1:43?pm, gonzlobo wrote: > No, I don't want to destroy them (funny how the word 'decimate' has > changed definition over the years) :). > > We have a data acquisition program that saves its output to Excel's > .xls format. Unfortunately, the programmer was too stupid to write > files the average user can read. > > I'd like some advice on how to go about: > 1. Reading a large Excel file and chop it into many Excel files (with > only 65535 lines per file) An Excel sheet only has 65535 lines. Or do yo mean it has multiple sheets? > or > 2. Decimate an Excel file & write... say every other line (user > selectable)... to a new file. Excel has VBA and can do this easily. One thing about Excel's VBA is that it already understands Excel. > > I'm pretty experienced at reading and writing simple text files, but > this is my first foray into using COM. I would imagine either choice 1 > or 2 is pretty simple once I can get the file open. Is it the case where you have .xls files but not the application? > > Thanks in advance. From S.Mientki-nospam at mailbox.kun.nl Fri Feb 9 09:30:34 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 09 Feb 2007 15:30:34 +0100 Subject: pycallgraph 0.1.0 In-Reply-To: References: Message-ID: Gerald Kaszuba wrote: > Hi > > I've just released the first version of Python Call Graph. I haven't > tested it too much so don't expect it not to crash :) > > An example of its output is: > http://pycallgraph.slowchop.com/files/examples/mongballs-client.png > > It's easy to use... you just need Graphviz installed and in your path > and a few lines of code changes. > > More details at http://pycallgraph.slowchop.com/ > > If you have any problems, don't hesitate to ask here or email me directly. > > Enjoy! > > Gerald looks quit good ... ... but isn't "__main__." non-information ? cheers, Stef From bj_666 at gmx.net Sat Feb 3 03:16:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 03 Feb 2007 09:16:42 +0100 Subject: Where Does One Begin? References: <1170485721.683685.178470@v33g2000cwv.googlegroups.com> Message-ID: In <1170485721.683685.178470 at v33g2000cwv.googlegroups.com>, Eric_Dexter at msn.com wrote: > pygame is probily a good program to start with as long as you keep in > mind that it is possible that up to 50% of the p.c. laptops may not be > able to run it. Huh? Care to explain this? Ciao, Marc 'BlackJack' Rintsch From jeffrey.aylesworth at gmail.com Sun Feb 25 19:57:25 2007 From: jeffrey.aylesworth at gmail.com (jeff) Date: 25 Feb 2007 16:57:25 -0800 Subject: newbie question In-Reply-To: References: Message-ID: <1172451445.535936.173510@k78g2000cwa.googlegroups.com> On Feb 25, 7:49 pm, "S.Mohideen" wrote: >... > > what does asd.update() signifies. What is the use of it. Any comments would > help to understand it. > > Thanks > Mohideen >>> print {}.update.__doc__ D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k] (if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k] so basically, this is what it does: >>> e = {} >>> f = {} >>> f['a'] = 123 >>> e.update(f) >>> e {'a': 123} From me at mylife.com Tue Feb 27 16:42:40 2007 From: me at mylife.com (Jason B) Date: Tue, 27 Feb 2007 21:42:40 GMT Subject: Pixel Array => Bitmap File Message-ID: Hi all, I'm somewhat new to Python and I'm trying to figure out the best way to accomplish the following: >From an array of pixel data in an XML file (given the format, width and height of the image as attributes) I must read in the data and save it off as a bmp file. I've gotten the PIL and Win32 packages and it seems that using functionallity from each I should be able to do this, but I haven't yet figured out how. Scouring the internet for a tutorial hasn't netted me anything so far, so I was hoping someone here could point me in the right direction... Thanks! J From pyscripter at gmail.com Wed Feb 14 21:21:47 2007 From: pyscripter at gmail.com (PyScripter) Date: 14 Feb 2007 18:21:47 -0800 Subject: pyscripter In-Reply-To: References: Message-ID: <1171506106.980071.9820@p10g2000cwp.googlegroups.com> On Feb 15, 12:41 am, Gigs_ wrote: > How to change syntax color inpyscripterfor python interpreter? > > I have change color in tools>options>editor options and everything is > fine till restartpyscripter. > After restart only in module is good syntax color, but in interpreter is > back to default. > > thx This is a bug in PyScripter that was fixed in version control. The fix will be available in the next version. Workaround: After starting Pyscripter, go to Tools, Option, Editor Options and press OK. This will apply your syntax highlighting changes to the interpreter window. From bdesth.quelquechose at free.quelquepart.fr Mon Feb 19 16:26:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Feb 2007 22:26:12 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com><14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl><45d626f5$0$19811$426a74cc@news.free.fr><53nt2aF1sn581U1@mid.uni-berlin.de> <45d85388$0$29060$426a74cc@news.free.fr> Message-ID: <45da0e70$0$31502$426a34cc@news.free.fr> Hendrik van Rooyen a ?crit : > "Bruno Desthuilliers" wrote: > > > >>Stef Mientki a ?crit : >>(snip) >> >>>I've been using Python for just 2 months, and didn't try any graphical >>>design, >> >>So how can you comment on GUI programming with Python ? > > > I think we have a language problem here (no pun intended) > > When Stef says "Gui Programming" he means using something like > Delphi or Boa to do the Graphical Layout, while on this group it > normally means writing the python code to make your own windows > etc., using Tkinter or better... It's now the *3rd* time I mention Glade, wxGlade and QTDesigner in this thread. Hendrik, I know *exactly* what Stef is talking about - been here, done that. > So from Stef's perspective he is right when he claims that Python's > "Gui Programming" is poor - in the standard library it is non existent, > as there are no Delphi-, Glade- or Boa-like tools available. > > And one can argue that something like Boa or the WX.. packages are > not Python, as they are not included in the standard library... > Then ObjectPascal his poor too. All the GUI part of Delphi is to ObjectPascal what wxPython etc are to Python. From thiw POV, Python is much richer than ObjectPascal : you have at least 3 or 4 usable GUI toolkits, at least two of them being full-featured and cross-platform. From jstroud at mbi.ucla.edu Wed Feb 14 16:25:21 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 13:25:21 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: Sergey Dorofeev wrote: > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>(1,)+[1] > > Traceback (most recent call last): > File "", line 1, in > TypeError: can only concatenate tuple (not "list") to tuple > >>>>[1]+(1,) > > Traceback (most recent call last): > File "", line 1, in > TypeError: can only concatenate list (not "tuple") to list > > > Its ugly and boring. > > Agreed. This would be similar to: py> 1 + 1.0 Traceback: can only add int to int. Etc. But then again, the unimaginative defense would be that it wouldn't be python if you could catentate a list and a tuple. James From timr at probo.com Sun Feb 11 18:24:40 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 11 Feb 2007 23:24:40 GMT Subject: Database Programming with Python References: <1171034880.089616.113380@p10g2000cwp.googlegroups.com> Message-ID: Finger.Octopus at gmail.com wrote: > >I wanted to connect Python to Ms-Access database using ADO or ODBC. I >have Python 2.5 and on mxODBC site, it has no higher version build >than 2.4. Moreoever, mxODBC is required for ADODB. >Can anyone guide me on this what should I do to make it work on Python >2.5? I have python 2.5 running on server. You don't actually need mxODBC to use ADODB. As long as you have the pywin32 extensions, you have what you need. import win32com.client conn = win32com.client.Dispatch('ADODB.Connection') conn.Open( "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=xxxxx.mdb" ) cmd = win32com.client.Dispatch('ADODB.Command') cmd.ActiveConnection = conn cmd.CommandText = "SELECT firstname,lastname FROM users;" rs = cmd.Execute()[0] while not rs.EOF: # Use elements of rs rs.MoveNext() There are samples on the web. Google should help. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jstroud at mbi.ucla.edu Sun Feb 11 19:53:16 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 11 Feb 2007 16:53:16 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: agent-s wrote: > Basically I'm programming a board game and I have to use a list of > lists to represent the board (a list of 8 lists with 8 elements each). > I have to search the adjacent cells for existing pieces and I was > wondering how I would go about doing this efficiently. Thanks > This isn't very clear. What do you mean by "I have to search the adjacent cells for existing pieces"? If piece is 1 and empty is 0 and piece is at ary[row][col]: import operator srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)] is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]]) James From Anders+news at Arnholm.nu Thu Feb 15 04:08:34 2007 From: Anders+news at Arnholm.nu (Anders Arnholm) Date: Thu, 15 Feb 2007 10:08:34 +0100 Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> <1171467933.663222.297490@v45g2000cwv.googlegroups.com> Message-ID: Nicola Musatti skriver: > On Feb 14, 2:41 pm, Neil Cerutti wrote: > [...] >> Don't forget the lack of standard garbage collection. > memory related problems. I'm aware that most is not the same as all, > but on the other hand garbage collection has it's problems too: And that garbabe collection is only good for memory, garbage collecting open files and network connections work much less well. Giving the need to add a maonual "delete" function to be called before the object is destroed when you need the life time controll. And this having to be reflected in application depenednt way to figure out how it works in each application. / Balp -- http://anders.arnholm.nu/ Keep on Balping From dsulkin at mqplp.com Tue Feb 6 07:52:57 2007 From: dsulkin at mqplp.com (David Sulkin) Date: Tue, 6 Feb 2007 06:52:57 -0600 Subject: Format a float and put in a list Message-ID: <44FE5DB1D8C46B41A60406A174446E04F5CF93@marquettemail.marquette.local> Hello, I have a float that I am trying to format to 2 decimal places, put the formatted float in a list and then output this to a file. My problem is, once I format my float, my float has quotations around the float due to my formatting. I am doing the following: ( "%.2f" % float( list[x] ) ) Is there a way I can format the float so when I see it in the file it looks like [19.45, 20.52, 16.56] instead of ['19.45', '20.52', '16.56']? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicola.musatti at gmail.com Wed Feb 14 06:36:14 2007 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 14 Feb 2007 03:36:14 -0800 Subject: c++ for python programmers In-Reply-To: References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <1171452974.820342.97230@q2g2000cwa.googlegroups.com> On Feb 14, 12:26 am, Sam wrote: [...] > C++ is -not- strongly typed. You can cast anything to void *, and > manipulate it in ways unimaginable. Plus there's the whole mess that > is pointer arithmetic and a weak typesystem... The previous poster wrote "strongly typed", not "a straight jacket". The fact that you may do certain things doesn't mean that you have to nor that they are going to be done to you against your will. > Disclaimer: I am unashamedly in the "C++ Is Evil" camp, and wholly > believe that if you want proper strong, static type checking, use > Haskell, or if you want proper, complete object-orientation (C++'s > primitive types compromise its object system's integrity, and I > believe I've already discussed casting and pointers), use Python, and > if you want under-the-hood pointer-fu, use C. The trouble is that in addition to proper, strong, static type checking people often also want their daily bread, fancy that. As to the merits of complete object orientation, I'd like to hear about them, because nobody managed to explain them to me in a satisfactory way yet. There are many valid reasons to dislike C++ and to prefer Python to it, but dismissing it as "C++ Is Evil" is just plain stupid. Moreover, C might be a valid competitor for small projects and it probably covers most Pythonistas' needs for "closeness to the metal", but it just doesn't scale. Cheers, Nicola Musatti From aboudouvas at panafonet.gr Wed Feb 7 11:59:12 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 7 Feb 2007 08:59:12 -0800 Subject: Object type check In-Reply-To: References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> Message-ID: <1170867552.247093.198800@j27g2000cwj.googlegroups.com> > Dont restrict them to particular types. You would > not restrict them to a particular class in C#. Instead, you define the > interfaces simply by how you use the objects. Of cource i restrict them to particular types! In C# you cannot pass something bad this way because the compiler will just catch it! I see what you mean by "duck typing". So you suggest the "do nothing at all" direction, better document my code so other can see what is expected, right ? From sjmachin at lexicon.net Sun Feb 25 08:31:11 2007 From: sjmachin at lexicon.net (John Machin) Date: 25 Feb 2007 05:31:11 -0800 Subject: finding out the precision of floats In-Reply-To: <1172405198.187516.276310@h3g2000cwc.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> Message-ID: <1172410271.154309.49700@j27g2000cwj.googlegroups.com> On Feb 25, 11:06 pm, "Arnaud Delobelle" wrote: > On Feb 25, 11:20 am, "John Machin" wrote: > [...] > > > I'm a little puzzled: > > > You don't seem to want a function that will tell you the actual number > > of significant decimal digits in a particular number e.g. > > > nsig(12300.0) -> 3 > > nsig(0.00123400) -> 4 > > etc > > > You appear to be trying to determine what is the maximum number of > > significant decimal digits afforded by the platform's implementation > > of Python's float type. > > Yes you are correct. > > > Is Python implemented on a platform that > > *doesn't* use IEEE 754 64-bit FP as the in-memory format for floats? > > I had no knowledge of IEEE 754 64-bit FP. The python doc says that > floats are implemented using the C 'double' data type but I didn't > realise there was a standard for this accross platforms . > > Thanks for clarifying this. As my question shows I am not versed in > floating point arithmetic! > > Looking at the definition of IEEE 754, the mantissa is made of 53 > significant binary digits, which means > 53*log10(2) = 15.954589770191003 significant decimal digits > (I got 16 with my previous dodgy calculation). > > Does it mean it is safe to assume that this would hold on any > platform? > Evidently not; here's some documentation we both need(ed) to read: http://docs.python.org/tut/node16.html """ Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 "double precision". """ I'm very curious to know what the exceptions were in November 2000 and if they still exist. There is also the question of how much it matters to you. Presuming the representation is 64 bits, even taking 3 bits off the mantissa and donating them to the exponent leaves you with 15.05 decimal digits -- perhaps you could assume that you've got at least 15 decimal digits. While we're waiting for the gurus to answer, here's a routine that's slightly less dodgy than yours: | >>> for n in range(200): | ... if (1.0 + 1.0/2**n) == 1.0: | ... print n, "bits" | ... break | ... | 53 bits At least this method has no dependency on the platform's C library. Note carefully the closing words of that tutorial section: """ (well, will display on any 754-conforming platform that does best- possible input and output conversions in its C library -- yours may not!). """ I hope some of this helps ... Cheers, John From xml0x1a at yahoo.com Mon Feb 19 23:53:34 2007 From: xml0x1a at yahoo.com (xml0x1a at yahoo.com) Date: 19 Feb 2007 20:53:34 -0800 Subject: exec "def.." in globals(), locals() does not work In-Reply-To: <1171944946.967005.86810@v33g2000cwv.googlegroups.com> References: <1171943563.164204.313540@p10g2000cwp.googlegroups.com> <1171944946.967005.86810@v33g2000cwv.googlegroups.com> Message-ID: <1171947214.600742.98050@p10g2000cwp.googlegroups.com> On Feb 19, 8:15 pm, "George Sakkis" wrote: > On Feb 19, 10:52 pm, xml0... at yahoo.com wrote: > > > How do I use exec? > > Before you ask this question, the one you should have an answer for is > "why do I (think I) have to use exec ?". At least for the example you > gave, you don't; Python supports local functions and nested scopes, > with no need for exec: > > from math import * > G = 1 > > def d(): > L = 1 > def f(x): > return L + log(G) > return f(1) > > > > >python -V > > Python 2.4.3 > > > ---- > > from math import * > > G = 1 > > def d(): > > L = 1 > > exec "def f(x): return L + log(G) " in globals(), locals() > > f(1) > > ---- > > > How do I use exec() such that: > > 1. A function defined in exec is available to the local scope (after > > exec returns) > > 2. The defined function f has access to globals (G and log(x) from > > math) > > 3. The defined function f has access to locals (L) > > > So far I have only been able to get 2 out of the 3 requirements. > > It seems that exec "..." in locals(), globals() only uses the first > > listed scope. > > > Bottomline: > > exec "..." in globals(), locals(), gets me 1. and 3. > > exec "..." in locals(), globals() gets me 1. and 2. > > exec "..." in hand-merged copy of the globals and locals dictionaries > > gets me 2. and 3. > > > How do I get 1. 2. and 3.? > > L is local in d() only. As far as f() is concerned, L,G and log are > all globals, only x is local (which you don't use; is this a typo?). > If you insist on using exec (which, again, you have no reason to for > this example), take the union of d's globals and locals as f's > globals, and store f in d's locals(): > Thanks! this works. I tried to use g to merge locals and globals But I didn't think of keeping the locals() so that f is visible in d. From bdesth.quelquechose at free.quelquepart.fr Sat Feb 3 12:27:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Feb 2007 18:27:08 +0100 Subject: How can I access data from MS Access? In-Reply-To: <1170517420.026596.74880@s48g2000cws.googlegroups.com> References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> Message-ID: <45c4bee4$0$453$426a74cc@news.free.fr> Finger.Octopus at gmail.com a ?crit : > How to access data from MS Access? I tried ADOdb for Python but it > doesn't seems to work. > > Even the official examples dont work, like this one: > > import adodb > conn = adodb.NewADOConnection('access') # mxodbc required > dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\inetpub\\adodb\ > \northwind.mdb;" > conn.Connect(dsn) > > > (I have downloaded mxodbc, but still it doesn't works) > "doesn't work" is the worst possible description of a problem. Did it print out some insults in a foreign language ? wipe out your HD ? Else ? From lbates at websafe.com Fri Feb 16 11:16:44 2007 From: lbates at websafe.com (Larry Bates) Date: Fri, 16 Feb 2007 10:16:44 -0600 Subject: why I don't like range/xrange In-Reply-To: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: <966dnX1598F5RUjYnZ2dnUVZ_uzinZ2d@comcast.com> stdazi wrote: > Hello! > > Many times I was suggested to use xrange and range instead of the > while constructs, and indeed, they are quite more elegant - but, after > calculating the overhead (and losen flexibility) when working with > range/xrange, and while loops, you get to the conclusion that it isn't > really worth using range/xrange loops. > > I'd like to show some examples and I'll be glad if someone can suggest > some other fixes than while a loop :-) > > a) range overfllow : > > > for i in range(0, 1 << len(S)) : > ..... > OverflowError: range() result has too many items > > ok, so we fix this one with xrange ! > > b) xrange long int overflow : > > for i in xrange(0, 1 << len(S)) : > ........ > OverflowError: long int too large to convert to int > > Next thing I miss is the flexibility as in C for loops : > > for (i = 0; some_function() /* or other condition */ ; i++) > > or, > > for (i = 0 ; i < 10 ; i++) > i = 10; > > > I don't think range/xrange sucks, but I really think there should be > some other constructs to improve the looping flexibility. Other thing > may be, that I just miss an equally elegant alternative that's why I'd > like to hear some suggestions on how to fix the above issues.. (btw, > I've already browsed the archives related to my issue,but i don't see > any good solution) > > Thanks > > Jernej. > Your example of for i in xrange(0, 1< Message-ID: <7xy7mpz6df.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > s = 'some string that needs a bcc appended' > ar = array.array('B',s) > bcc = 0 > for x in ar[:]: > bcc ^= x > ar.append(bcc) > s=ar.tostring() Untested: import operator s = 'some string that needs a bcc appended' ar = array.array('B',s) s += chr(reduce(operator.xor, ar)) From gagsl-py at yahoo.com.ar Wed Feb 14 01:18:20 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 03:18:20 -0300 Subject: barcode generation References: Message-ID: En Wed, 14 Feb 2007 00:56:14 -0300, escribi?: > I want to generate barcode based on an input which can be numbers or > numbers+alphabets. > How do I do this? Is there any library that will doo this? Try google... -- Gabriel Genellina From edreamleo at charter.net Fri Feb 16 08:04:00 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 07:04:00 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> Message-ID: <9ZhBh.1$963.0@newsfe03.lga> > There could be something like from __future__ import print_function To repeat: this would be compatible only with Python 2.6. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From bearophileHUGS at lycos.com Tue Feb 27 06:11:37 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Feb 2007 03:11:37 -0800 Subject: HTML to dictionary In-Reply-To: References: Message-ID: <1172574697.213297.75910@k78g2000cwa.googlegroups.com> Tina I: > I have a small, probably trivial even, problem. I have the following HTML: This is a little data munging problem. If it's a one-shot problem, then you can just load it with a browser, copy and paste it as text, and then process the lines of the text in a simple way (splitting lines according to ":", and using the stripped pairs to feed a dict). If there are more Html files, or you want to automate things more, you can use html2text: http://www.aaronsw.com/2002/html2text/ A little script like this may help you: from html2text import html2text txt = html2text(the_html_data) lines = str(txt).replace("**", "").strip().splitlines() fields = [[field.strip() for field in line.split(":")] for line in lines] print dict(fields) Note that splitlines() is tricky, if you find some problems, then you may want a smarter splitter. Bye, bearophile From paul at boddie.org.uk Tue Feb 20 14:47:36 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Feb 2007 11:47:36 -0800 Subject: threading and multicores, pros and cons In-Reply-To: References: <7x4pphfjnx.fsf@ruckus.brouhaha.com> Message-ID: <1172000856.742314.111100@k78g2000cwa.googlegroups.com> Nikita the Spider wrote: > > Hmmm, I hadn't thought about that since I've never used the Cheese Shop > myself. What benefits does Cheese > Shop confer to someone looking for a package? I ask because from my > perspective it just adds overhead to package maintenance. The Python Package Index, as I prefer to call it (but we're talking about the same thing), doesn't really make any special demands on distribution or maintenance: you just need to register yourself and add an entry for the package, filling in a few fields such as the homepage and perhaps the download link; you can also upload archives if you'd prefer. If you have a PKG-INFO file, you can either upload that in order to get fields filled out more conveniently (as long as the Package Index likes the file), and if you have a setup.py script you might be able to use the upload feature with that (and the PKG- INFO file, I suppose). Don't be confused by all the setuptools extras and any insistence that the Package Index works best with things that are packaged as Python Eggs: whilst that might confer certain benefits, mostly to users who rely on Egg dependencies, it's peripheral to the purpose of the Package Index itself. Paul From grante at visi.com Sun Feb 11 21:24:59 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 12 Feb 2007 02:24:59 -0000 Subject: Read/write 2D data from/to file..? References: <1171244850.077289.130330@s48g2000cws.googlegroups.com> Message-ID: <12svjvrpeev18fe@corp.supernews.com> On 2007-02-12, mech point wrote: > > I was able to read the data from file into a two dimensional array > (lists) > > rows=[map(float,line.split())for line in file("data")] > > but How to write them back into the file. for r in rows: file.write(" ".join(map(str,r)) + "\n") -- Grant Edwards grante Yow! My nose feels like a at bad Ronald Reagan movie... visi.com From horpner at yahoo.com Fri Feb 2 09:01:44 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 15:01:44 +0100 Subject: need help on a data structure problem References: Message-ID: On 2007-02-02, Ben Finney wrote: > "Dongsheng Ruan" writes: > >> Not quite related with Python. But my Data Structure course is >> experiemented on python and there is no data structure group, So I >> have to post here: > > Better, you should discuss it in your class, with your teacher. Also: comp.algorithms is the usual Usenet place for discussion of algorithms and data structures. However most of the talk there is pretty high-falutin'. -- Neil Cerutti It isn't pollution that is hurting the environment; it's the impurities in our air and water that are doing it. --Dan Quayle From rw at smsnet.pl Mon Feb 19 03:16:39 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 19 Feb 2007 00:16:39 -0800 Subject: How do I create an array of functions? In-Reply-To: References: Message-ID: <1171872999.751809.256880@p10g2000cwp.googlegroups.com> Steven W. Orr wrote: > I have a table of integers and each time I look up a value from the table > I want to call a function using the table entry as an index into an array > whose values are the different functions. I haven't seen anything on how > to do this in python. Do you mean something like that? # test.py def fun1(): return "fun1" def fun2(): return "fun2" def fun3(): return "fun3" # list of functions dsp = [f for fname, f in sorted(globals().items()) if callable(f)] tab = range(len(dsp)) print dsp[tab[2]]() # dictionary of functions d = dict([(fname, f) for fname, f in globals().items() if callable(f)]) tab = [fname for fname, f in sorted(globals().items()) if callable(f)] print d[tab[2]]() -- HTH, Rob From pgmdevlist at gmail.com Wed Feb 7 12:58:07 2007 From: pgmdevlist at gmail.com (Pierre GM) Date: Wed, 7 Feb 2007 12:58:07 -0500 Subject: what is wrong with my python code? In-Reply-To: References: Message-ID: <200702071258.08381.pgmdevlist@gmail.com> On Wednesday 07 February 2007 12:43:34 Dongsheng Ruan wrote: > I got feed back saying" list object is not callable". But I can't figure > out what is wrong with my code. > for i in range(l): > print A(i) You're calling A, when you want to access one of its elements: use the straight brackets [ for i in range(l): print A[i] From mbm at mediamonger.ch Wed Feb 7 11:49:24 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Wed, 07 Feb 2007 17:49:24 +0100 Subject: (n)curses or tcl/tk? In-Reply-To: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> References: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> Message-ID: <45CA0314.8080804@mediamonger.ch> As far as I know Windows does not support ncurses natively (using CygWin probably changes that). So go with Tkinter. Looks crappy but at least it should run on all major platforms... > Hi All, > > Just learning Python - my first new language for about 18 years (I'm > not a programmer ...). I'm writing a small utility to manipulate some > text files (for the game VGA Planets, if you're interested: http:// > www.phost.de). It's currently working, but it looks a bit ugly with > raw_input and just basic text output. > > I have plans to expand the functions of the utility, and I want a > simple GUI frontend. I assumed I'd end up with something that looks a > bit like the Debian installer: a curses-driven thing with simple ascii > boxes and buttons. But reading a bit more about Python makes me think > that support for tcl/tk is much more developed than support for > curses. > > So my question is, should I go to the trouble of learning how to make > boxes and stuff using tcl/tk, or just go with ncurses as I imagined? > > Which is more portable? The basic idea is that this just runs on the > largest possible variety of systems (er, assuming they have Python > installed, of course). I use Debian mostly, but of course it needs to > run on bog-standard Windows boxes. Does that tilt the balance in > favour of curses or tcl/tk? Or should I just stick with ugly text? > > Thanks for all your help, > > CC (noob) > > From stj911 at rock.com Sat Feb 3 00:17:54 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 2 Feb 2007 21:17:54 -0800 Subject: What is the Decisive "Clash" of Our Time? In-Reply-To: References: <1170289871.307738.216710@v33g2000cwv.googlegroups.com> Message-ID: <1170479874.053127.211780@k78g2000cwa.googlegroups.com> Forget about the lunacy ... just enjoy these fun movies that are also on optics education. You can also save them by right clicking the links and saving them as flv files and download a free flv player. google is your friend. "Bush Administration Insider Says U.S. Government Behind 911.flv" "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w" "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http:// youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" "911 Truth, Consequences of Revealing the Truth about 911.flv" "http:// youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv" "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax- v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" "Bush gets caught off guard on 9/11 prior knowledge question.flv" "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" "Bush gets caught off guard on 911 prior knowledge question.flv" "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" "World Trade Center -- Controlled Demolition.flv" "http:// v187.youtube.com/get_video?video_id=87fyJ-3o2ws" "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv" "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90" On Jan 31, 7:56 pm, "Overlord" wrote: > I never thought it would be possible for anyone to rival the lunacy of > Bitter Anko, but I was wrong... > > OL From jjl at pobox.com Sun Feb 11 16:16:31 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 11 Feb 2007 21:16:31 GMT Subject: MySQLdb binaries (was Re: huge amounts of pure...) References: <17864.51664.838043.38090@montanaro.dyndns.org> Message-ID: <87odo0ieea.fsf_-_@pobox.com> Robin Becker writes: > skip at pobox.com wrote: > > John> MySQLdb isn't fully supported for Python 2.5 yet, and there's no > > John> tested Windows executable available, although there's an untested > > John> version from a World of Warcraft guild available. > > As Andy Dustman has pointed out a number of times, he doesn't do > > Windows. > > Someone in the MySQLdb community who does use Windows is going to have to > > fill that void. > ...... > > well I have managed to build both extant versions > (MySQL-python-1.2.1_p2 & MySQL-python-1.2.2b2) from source with the > aid of Mr Dustman's comments in the site.cfg files and a very minor > hack to the earlier version. I had to have the sources for Mysql > available as well, but that probably comes with the territory. It > seems the very latest version won't play well with earlier MySQL so I > used MySQL-python-1.2.1_p2 as we are still using some 4.0.27 databases. > > Given that I used a particular version of MySQL, 5.0.33, to build > against I'm not certain that my builds are useful for everyone. I copy > here the differences I had to make to the source to get stuff to build > and run against stock win32 Python-2.5 [...] Robin may be right, but the resulting binaries are here (not supported, use at your own risk): http://www.reportlab.org/ftp/MySQLdb-1.1.2b2-win32-py25.zip or ftp://www.reportlab.org/MySQLdb-1.1.2b2-win32-py25.zip John From emami at knmi.nl Wed Feb 28 06:07:06 2007 From: emami at knmi.nl (Nader Emami) Date: Wed, 28 Feb 2007 12:07:06 +0100 Subject: installing "pysqlite" In-Reply-To: <1172576685.560386.306740@m58g2000cwm.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> Message-ID: <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> Paul Boddie wrote: > On 27 Feb, 10:31, Nader Emami wrote: >> I have installed "TurboGears" and I would install 'pysqlite' also. I am >> a user on a Linux machine. If I try to install the 'pysqlite' with >> 'easy_install' tool I get the next error message. The error message is >> longer than what I send here. > > [...] > >> src/connection.h:33:21: sqlite3.h: No such file or directory > > [...] > >> Could somebody tell me what I have to do to install 'pysqlite'? > > Install SQLite, perhaps? If the pysqlite build process can't find > sqlite3.h then you either don't have SQLite installed, or you don't > have the headers for SQLite installed. I'd recommend that you check > your installed packages for the SQLite libraries (eg. libsqlite3-0 on > Ubuntu) and/or the user interface (eg. sqlite3) and for the > development package (eg. libsqlite3-dev). > > If you can't install the packages, install SQLite from source (see > http://www.sqlite.org/) and try and persuade pysqlite to use your own > SQLite installation - there's a setup.cfg file in the pysqlite > distribution which may need to be changed to achieve this, but I don't > know how that interacts with setuptools. > > Paul > Hello, I am back with another problem. I suppose that I can tell it! I have installed both, 'sqlite' and 'pysqlite' without any problem. But If I try to test whether the 'pysqlite' interface works, I get the next error message: >>>from pysqlite2 import dbapi2 as sqlite Traceback (most recent call last): File "", line 1, in ? File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/dbapi2.py", line 27, in ? from pysqlite2._sqlite import * ImportError: /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so: undefined symbol: sqlite3_set_authorizer I don't understand it. Could you tell me how I can solve this last point? I hope so! With regards, Nader From grante at visi.com Thu Feb 22 10:00:20 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 22 Feb 2007 15:00:20 -0000 Subject: Creating a daemon process in Python References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> <1172152076.728838.187810@v33g2000cwv.googlegroups.com> Message-ID: <12trc0480c7v6af@corp.supernews.com> On 2007-02-22, okahashi at gmail.com wrote: > I understood there is no shortcut function like BSD daemon(). I'll do > it manually using examples from cookbook... Sure would be nice if somebody posted one. ;) -- Grant Edwards grante Yow! Oh, I get it!! "The at BEACH goes on", huh, visi.com SONNY?? From jeff.templon at gmail.com Tue Feb 20 16:53:07 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 13:53:07 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: <1172004973.139495.311980@h3g2000cwc.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> Message-ID: <1172008387.851412.181530@p10g2000cwp.googlegroups.com> Hi, Paul, thanks for this, I didn't realize the scope of the situation. I agree with your assessment to the extent that I understand what the whole python 3.0 thing is about. Let's see if I can scare up something I wrote about ten years ago on a now-dead language that I really wanted to use (wound up sticking with python instead because "it was supported" ;-) ======================= to figure out how to work things. The fact that there are three (or four depending if you count Linz V4) different Oberon System implementations, and several different compilers, and even four or five separate dialects of Oberon with none of them appearing to be really "official", gives the impression of a fragmented, directionless development effort, and a probability bordering on 1.0000 that whatever you try to do will be incompatible with all but a small subset of what's available (unless you stick to writing small programs like in the books.) It does not matter if you tell people that this is not so; something has to clearly stand out as being THE STANDARD STUFF and all the other stuff as INTERESTING BUT NONTHREATENING SIDE PROJECTS. The STANDARD STUFF must include a sufficient number of ========================= Oberon is really really cool, seriously, ... but nobody is using it. People working on python development are of course free to do what they want, but so are the users ... J "actie-reactie is what my ex-brother-in-law would say" T From aboudouvas at panafonet.gr Thu Feb 8 06:44:54 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 8 Feb 2007 03:44:54 -0800 Subject: Object type check In-Reply-To: <1170932865.701952.99210@v33g2000cwv.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> <1170932439.393593.200090@h3g2000cwc.googlegroups.com> <1170932865.701952.99210@v33g2000cwv.googlegroups.com> Message-ID: <1170935094.717123.236860@a75g2000cwd.googlegroups.com> ?/? Michele Simionato ??????: > See http://users.rcn.com/python/download/Descriptor.htm for more than > you ever wanted > to know about attribute access in Python. > > Michele Simionato Great stuff Michele, thanks! From lincolnr at oar.net Tue Feb 27 16:00:25 2007 From: lincolnr at oar.net (lincoln rutledge) Date: Tue, 27 Feb 2007 16:00:25 -0500 Subject: difference between string and list Message-ID: <45E45599020000C50000702F@gw.osc.edu> Hi Skip, Okay, I actually have those pages up in my browser. I found the string methods: http://docs.python.org/lib/string-methods.html But I am having trouble finding the same information for lists... Thanks I will look into it some more, Lincoln >>> 02/27/07 3:28 PM >>> lincoln> strings have methods like string.count("f") returns 1. What lincoln> methods do lists have? Is it a similar class to string? Similar in some ways, different in others. Some things to play with: 1. At an interpreter prompt, execute: help("") help([]) 2. Check the relevant sections of the tutorial: http://docs.python.org/dev/tut/node5.html#SECTION005120000000000000000 http://docs.python.org/dev/tut/node5.html#SECTION005140000000000000000 Two significant differences: 1. Strings are immutable. 2. Lists can contain any kind of object, not just characters. Skip From mikael at isy.liu.se Tue Feb 27 08:05:18 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 27 Feb 2007 14:05:18 +0100 Subject: newbie question(file-delete trailing comma) In-Reply-To: <743170.77162.qm@web7813.mail.in.yahoo.com> References: <743170.77162.qm@web7813.mail.in.yahoo.com> Message-ID: <45E42C8E.7020804@isy.liu.se> kavitha thankaian wrote: > i get an error when i try to delete in file and rename it as out > file,,the error says > "permission denied". Perhaps you should give us both the exact code you are running and the complete traceback of the error. That could make things easier. There can be numerous reasons for "permission denied". > actually i need something like following: > > in_file = open('in.txt','w') > for line in in_file: > line.strip().strip(',') > > but when i run the above code,i get an error"bad file descriptor" Of course you do! You are opening the file for writing, but your code attempts to read the file. Probably, you think that the code would change the lines in the file itself, which it does not, even if it would be possible to read from a file opened for writing. What's wrong with the code that Mohammad posted? Note that you might need to close out_file in his code. /MiO From gagsl-py at yahoo.com.ar Mon Feb 5 18:38:16 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:38:16 -0300 Subject: CTypes References: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> Message-ID: En Sat, 03 Feb 2007 13:01:56 -0300, SoutoJohn at gmail.com escribi?: > I'm trying to install PyWinAuto for Python 2.4. It said that one of > the required libraries that I need to install would be CTypes. So I > head over to CTypes's SourceForge page and I installed CTypes for > Python 2.4. I go to run the PyWinAuto installation file and it throws > up this error: > > GetModuleFileNameEx = > ctypes.windll.psapi.GetModuleFileNameExW > > So my best guess is that I'm either missing a Python library or I'm > missing a DLL. Too bad I don't know which, does anyone know what I'm > missing? From the line above, should be "psapi.dll" I don't know it. -- Gabriel Genellina From boris.smirnov at gmail.com Mon Feb 26 10:08:48 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 26 Feb 2007 07:08:48 -0800 Subject: Interactive os.environ vs. os.environ in script Message-ID: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> Hi there, I have a problem with setting environment variable in my script that uses qt library. For this library I have to define a path to tell the script whre to find it. I have a script called "shrink_bs_070226" that looks like this: ********************************** import sys, re, glob, shutil import os os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' from qt import * *********************** When I run this script I get this error: > python shrink_bs_070226.py Traceback (most recent call last): File "shrink_bs_070226.py", line 25, in ? from qt import * File "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ qt.py", line 46, in ? import libsip ImportError: libadamsqt.so: cannot open shared object file: No such file or directory What is important here that when I set this variable interactive in python session, there is no problem with import. > python Python 2.2.3 (#1, Aug 8 2003, 08:44:02) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> import shrink_bs_070226 Traceback (most recent call last): File "", line 1, in ? File "shrink_bs_070226.py", line 25, in ? from qt import * ImportError: No module named qt >>> os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' >>> import shrink_bs_070226 >>> Could anybody explain me the logic here? Am I missing something? Thank in advance. Rg Boris From steve at REMOVEME.cybersource.com.au Tue Feb 27 01:24:14 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Feb 2007 17:24:14 +1100 Subject: Is type object an instance or class? References: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> Message-ID: On Mon, 26 Feb 2007 18:00:00 -0800, JH wrote: > A object should not be both a class and an instance at the same time. Why ever not? A meta-class is a class (or at least a class-like object) whose instances are themselves classes. Under the hood, Python uses meta-classes extensively. Most Python developers probably never need to use it, but if you want your head to explode, read this: http://www.python.org/doc/essays/metaclasses/ A couple of more gentle introductions are here: http://www.python.org/doc/essays/metaclasses/meta-vladimir.txt http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html Me, I think I'll stick to class factories. -- Steven D'Aprano From sxn02 at yahoo.com Fri Feb 16 11:51:29 2007 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Fri, 16 Feb 2007 08:51:29 -0800 (PST) Subject: Enter Enter... troubles Message-ID: <759406.30368.qm@web56015.mail.re3.yahoo.com> It works, thanks. Sorin ____________________________________________________________________________________ Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. http://answers.yahoo.com/dir/?link=list&sid=396546091 From paddy3118 at netscape.net Fri Feb 2 09:39:30 2007 From: paddy3118 at netscape.net (Paddy) Date: 2 Feb 2007 06:39:30 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: <1170427170.621243.160150@s48g2000cws.googlegroups.com> On Feb 2, 1:55 pm, "ardief" wrote: > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] > > I have the feeling it's trivial, and I've scoured the group archives - > sets might be a possibility, but I'm not sure how to operate on a list > of lists with sets. > > This function also gives me what I want, more or less, but I don't > know how to make it run until it's covered all the possibilities, if > that makes sense... > > def sigh(list): > for a in list: > i = list.index(a) > if a != list[-1]: ##if a is not the last one, i.e. there is a > next one > n = alist[i+1] > if a[0] == n[0]: > a.append(n[1:]) > del alist[i+1] > > Sorry about the lengthy message and thanks for your suggestions - I'm > trying to learn... : python Python 2.5 (r25:51908, Nov 28 2006, 16:10:01) [GCC 3.4.3 (TWW)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> from pprint import pprint as pp >>> from collections import defaultdict >>> data = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] >>> d = defaultdict(list) >>> _ = [d[x0].append(x1) for x0,x1 in data] >>> pp(d) defaultdict(, {'a': ['13', '3'], 'c': ['12', '15', '4'], 'b': ['6'], 'e': ['11', '5', '16', '7'], 'd': ['2']}) >>> pp(sorted(d.items())) [('a', ['13', '3']), ('b', ['6']), ('c', ['12', '15', '4']), ('d', ['2']), ('e', ['11', '5', '16', '7'])] >>> - Paddy From eopadoan at altavix.com Fri Feb 2 07:16:11 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 2 Feb 2007 10:16:11 -0200 Subject: File system API In-Reply-To: <7afdee2f0702020402h55e605cv6b591cafe91bf2b4@mail.gmail.com> References: <7afdee2f0702020402h55e605cv6b591cafe91bf2b4@mail.gmail.com> Message-ID: On 2/2/07, Tal Einat wrote: > > I think that there aready exists a proposal for an Abstract FS Layer > > for Python somewere. > > I haven't been able to find any mention of it. Maybe you could point me in > the right direction? > > - Tal > http://wiki.python.org/moin/CodingProjectIdeas/FileSystemVirtualization Another related reference is the recently announced UniPath module: http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 15:29:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 21:29:23 +0100 Subject: Question about a single underscore. In-Reply-To: <7xy7nhk89x.fsf@ruckus.brouhaha.com> References: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> <7xveilzpvs.fsf@ruckus.brouhaha.com> <7xy7nhk89x.fsf@ruckus.brouhaha.com> Message-ID: <45c246ab$0$23014$426a74cc@news.free.fr> Paul Rubin a ?crit : > "Steven W. Orr" writes: > >>AttributeError: _const instance has no attribute '_const' >> >>What am I missing here? (Sorry if it should be obvious) > > > Oh I see. No it's not obvious. module "const" has gotten overwritten > by the _const instance. I think that module author was too clever for > his or her own good. Not necessarily - given the intent, it's just smart IMHO. But the workaround is quite obvious anyway: >>> import const >>> # so what is const ? >>> const >>> # ok, it's an instance, so it should refer to it's class: >>> Const = const.__class__ >>> Const >>> # Bingo. Let's have another _const instance: >>> c = Const() >>> c >>> c.pi = 42 >>> c.pi = 33 Traceback (most recent call last): File "", line 1, in ? File "const.py", line 5, in __setattr__ raise self.ConstError, "Can't rebind const(%s)"%name const.ConstError: Can't rebind const(pi) >>> HTH From antroy at gmail.com Mon Feb 26 03:51:56 2007 From: antroy at gmail.com (Ant) Date: 26 Feb 2007 00:51:56 -0800 Subject: help regarding python and jsp In-Reply-To: <1172472076.032230.127280@k78g2000cwa.googlegroups.com> References: <1172472076.032230.127280@k78g2000cwa.googlegroups.com> Message-ID: <1172479916.859672.55220@k78g2000cwa.googlegroups.com> On Feb 26, 6:41 am, chandra... at gmail.com wrote: > Hi, > i am working with jsp .. > i wanna help regarding how to import or how to call python modules to > jsp You are aware that JSP's are a Java technology, and not Python. And that they are a templating language in themselves. And that scriptlets (Java code inside of a JSP) have not been regarded as good practice for years now, and that would be the only way of getting Python code inside a JSP (using an ugly hack such as creating a Jython engine and writing the python as strings to be eval'ed) So what is it that you are trying to do exactly here? -- Ant. From sjmachin at lexicon.net Fri Feb 23 11:47:38 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Feb 2007 08:47:38 -0800 Subject: Finding non ascii characters in a set of files In-Reply-To: <9sidnRutcqCLkULYnZ2dnUVZ_gydnZ2d@comcast.com> References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> <9sidnRutcqCLkULYnZ2dnUVZ_gydnZ2d@comcast.com> Message-ID: <1172249258.166435.34080@k78g2000cwa.googlegroups.com> On Feb 24, 2:44 am, Larry Bates wrote: > Peter Bengtsson wrote: > > On Feb 23, 2:38 pm, b... at yahoo.com wrote: > >> Hi, > > >> I'm updating my program to Python 2.5, but I keep running into > >> encoding problems. I have no ecodings defined at the start of any of > >> my scripts. What I'd like to do is scan a directory and list all the > >> files in it that contain a non ascii character. How would I go about > >> doing this? > > > How about something like this: > > content = open('file.py').read() > > try: > > content.encode('ascii') > > except UnicodeDecodeError: > > print "file.py contains non-ascii characters" > > The next problem will be that non-text files will contain non-ASCII > characters (bytes). The other 'issue' is that OP didn't say how large > the files were, so .read() might be a problem. > > -Larry The way I read it, the OP's problem is to determine in one big hit which Python source files need a # coding: whatever line up the front to stop Python 2.5 complaining ... I hope none of them are so big as to choke .read() Cheers, John From kavithapython at yahoo.co.in Wed Feb 28 06:34:29 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Wed, 28 Feb 2007 11:34:29 +0000 (GMT) Subject: newbie question(file-delete trailing comma) In-Reply-To: <45E54D7A.8060203@isy.liu.se> Message-ID: <787921.87592.qm@web7806.mail.in.yahoo.com> thanks,, now i have one more problem,,, the strings should be seperated in an order,,, some={1:'a', 2:7, 3:'c', 4:'d'} i need the output to be a,c,d,7 before my code was: field_order = [1,3,4,2] for field in field_order: f.writelines('\"%s\",' % someprt[field] ) do you have an idea now how should it look like??? Mikael Olofsson wrote: kavitha thankaian wrote: > my script writes a dictionary to a file.but i need only the values > from the dictionary which should be sepearted by a comma,,,so i did as > following: > [snip code that generates the incorrect original file] > when i execute the above code,my test.txt file has the following: > a,b,c,d, > now i need to delete the comma at the end,,,this is my problem,,, This is the first time you mention that you have control over the generation of the original file. Then I suggest that you fix the problem before generating the file. For instance, consider the following interactive session. >>> some={1:'a',2:7,3:'c',4:'d'} >>> some {1: 'a', 2: 7, 3: 'c', 4: 'd'} >>> some.values() ['a', 7, 'c', 'd'] >>> [str(x) for x in some.values()] ['a', '7', 'c', 'd'] >>> ','.join([str(x) for x in some.values()]) 'a,7,c,d' Then write that to your file instead. /MiO -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From jm.suresh at gmail.com Sun Feb 25 04:52:56 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 25 Feb 2007 01:52:56 -0800 Subject: Find the first element that meets the condition Message-ID: <1172397176.024303.257890@t69g2000cwt.googlegroups.com> Hi, I have a list and I want to find the first element that meets a condition. I do not want to use 'filter', because I want to come out of the iteration as soon as the first element is found. I have implemented it this way, may be, there should be a built in hiding somewhere in the standard libraries? def exists(iterable, condition): ''' Return the first element in iterble that meets the condition. ''' for x in iterable: if condition(x): return x raise Exception('No element meets the given condition.') >>> exists(xrange(1000), lambda x: x>13) 14 - Suresh From mail at timgolden.me.uk Wed Feb 28 17:01:24 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 28 Feb 2007 22:01:24 +0000 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: <1172697850.946627.196420@a75g2000cwd.googlegroups.com> References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> <1172697850.946627.196420@a75g2000cwd.googlegroups.com> Message-ID: <45E5FBB4.3050706@timgolden.me.uk> kevinliu23 wrote: > Thanks so much for the help guys. I got the code Sick Monkey provided > to work on my computer. Now I"m more confused than ever though. :) I > thought the only standard modules provided by Python are listed here: > > http://docs.python.org/modindex.html > > But it appears that there are other modules available to me without > having to download third party code. Could someone point me to the > documentation of these other modules such as win32com.client? Thanks > everyone for your help. :) Chances are you're running the ActiveState distro of Python. Either that or you downloaded the pywin32 extensions in your sleep: http://pywin32.sf.net In any case, that's where the win32com.client and friends come from. The installation normally supplies a handy .chm file which gives all the docs. > Also, how could I get the computer name? You can do that with WMI as well. Just look at the Win32_ComputerSystem object and its Caption attribute: http://msdn2.microsoft.com/en-us/library/aa394102.aspx TJG From karoly.kiripolszky at gmail.com Sat Feb 3 12:34:59 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 3 Feb 2007 09:34:59 -0800 Subject: strange test for None In-Reply-To: References: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> Message-ID: <1170524099.468603.167340@h3g2000cwc.googlegroups.com> the tested variable was really a string containing "None" instead of simply None. this is the first time i ran into this error message confusion. :) thanks for the help! On Feb 3, 6:29 pm, Michael Bentley wrote: > On Feb 3, 2007, at 7:47 AM, karoly.kiripolszky wrote: > > > in my server i use the following piece of code: > > > ims = self.headers["if-modified-since"] > > if ims != None: > > t = int(ims) > > > and i'm always getting the following error: > > > t = int(ims) > > ValueError: invalid literal for int(): None > > > i wanna know what the hell is going on... first i tried to test using > > is not None, but it makes no difference. > > Sounds like ims == 'None'. Try changing: > > if ims != None: > > to > > if ims: > > and you might also wrap your call to int(ims) in a try block. > > HTH, > Michael From laurent.pointal at limsi.fr Wed Feb 21 03:50:55 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 21 Feb 2007 09:50:55 +0100 Subject: eval('000052') = 42? In-Reply-To: References: Message-ID: Astan Chee a ?crit : > Hi, > I just tried to do > eval('00052') and it returned 42. > Is this a known bug in the eval function? Or have I missed the way eval > function works? > Thanks Ad Erik replied, a literal value beginning by 0 is interpreted as an octal value (and beginning by 0x it is interpreted as hexadecimal value). You may use int construction from string, which allow to specify a base (default to ten): >>> int('00052') 52 >>> int('00052',10) 52 >>> int('00052',8) 42 Note: this avoid possible evaluation of undesired Python expressions... A+ Laurent. From yinglcs at gmail.com Tue Feb 27 19:05:40 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 27 Feb 2007 16:05:40 -0800 Subject: how to convert an integer to a float? Message-ID: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, i1)' always return 0, can you please tell me how can i convert it from an integer to float? def compareValue(n1, n2): i1 = int(n1) i2 = int(n2) dx = abs(i2 - i1)/min(i2, i1) print dx return dx < 0.05 From smusnmrNOSPAM at yahoo.com Fri Feb 9 08:48:58 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 9 Feb 2007 14:48:58 +0100 Subject: pygame and python 2.5 Message-ID: @Ben Sizer Hi Ben, in January I received your message re Pygame and Python 2.5: >pygame and python 2.5 >Ben Sizer kylotan at gmail.com >Fri Jan 12 11:01:00 CET 2007 >-------------------------------------------------------------------------------- > >siggi wrote: > >> when I rtry to install pygame (pygame-1.7.1release.win32-py2.4.exe, the >> most >> ciurrent version I found) it requires Python 2.4! Will I really have to >> uninstall my Python 2.5 and install the old Python 2.4 in order to use >> pygame? > >For now, yes. This is a long-standing problem with Python really, >requiring extensions to always be recompiled for newer versions. I >usually have to wait about 6 months to a year after any new release >before I can actually install it, due to the extension lag. > >-- >Ben Sizer As a Python (and programming ) newbie allow me a - certainly naive - question: What is this time consuming part of recompiling an extension, such as Pygame, from source code to Windows? Is it a matter of spare time to do the job? Or do you have to wait for some Windows modules that are necessary for compiling? I am just asking for sake of "scientific" interest; building, compiling from source code is a mystery to me poor Windows user ;-) Thank you, siggi From kylotan at gmail.com Fri Feb 9 12:39:03 2007 From: kylotan at gmail.com (Ben Sizer) Date: 9 Feb 2007 09:39:03 -0800 Subject: pygame and python 2.5 In-Reply-To: References: Message-ID: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> On Feb 9, 1:48 pm, "siggi" wrote: > @Ben Sizer Lucky I spotted this... > As a Python (and programming ) newbie allow me a - certainly naive - > question: > > What is this time consuming part of recompiling an extension, such as > Pygame, from source code to Windows? Is it a matter of spare time to do the > job? Or do you have to wait for some Windows modules that are necessary for > compiling? The problem is something like this: - Python extensions written in C require recompilation for each new version of Python, due to Python limitations. - Recompiling such an extension requires you to have a C compiler set up on your local machine. - Windows doesn't come with a C compiler, so you have to download one. - The compiler that Python expects you to use (Visual Studio 2003) is no longer legally available. - The other compiler that you can use (MinGW) is requires a slightly convoluted set of steps in order to build an extension. Hopefully in the future, some of those convoluted steps will be fixed, but that requires someone putting in the effort to do so. As is often the case with Python, and indeed many open source projects, the people who are knowledgeable enough to do such things usually don't need to do them, as their setup already works just fine. -- Ben Sizer From JohnRoth1 at jhrothjr.com Tue Feb 6 11:50:03 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 6 Feb 2007 08:50:03 -0800 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: Message-ID: <1170780602.945994.34390@k78g2000cwa.googlegroups.com> On Feb 6, 8:40 am, Steven Bethard wrote: > Jean-Paul Calderone wrote: > > > Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve At a guess, the most likely thing to break code in job lots in 2.5 was the change in default coding from latin-1 (or whatever the installation has the default set to) to ascii. This would have a tendency to break most modules that depended on the default source coding. Fortunately, the fix is (not quite trivially) easy - just scan the library and put the right coding comment in the front. John Roth From gagsl-py at yahoo.com.ar Thu Feb 1 20:36:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 22:36:19 -0300 Subject: coping directories References: Message-ID: En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ escribi?: > class CVisitor(FileVisitor): > def __init__(self, fromdir, todir): > self.fromdirLen = len(fromdir) + 1 # here is my problem > self.todir = todir > FileVisitor.__init__(self, fromdir) > def visitdir(self, dirpath): > topath = os.path.join(self.todir, dirpath[self.fromdirLen:]) > os.mkdir(topath) > def visitfile(self, filepath): > topath = os.path.join(self.todir, filepath[self.fromdirLen:]) > cpfile(filepath, topath) #copy contents from filepath to > topath[/code] > > > When I copy contents from C:\IronPython to C:\temp > its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this > self.fromdirLen = len(fromdir) + 1 > but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen > = len(fromdir) i get contents copied to C:\ (actually to parent dir) Instead of actually doing os.mkdir and cpfile, use a print statement to output the involved variables, and try with and without +1. You'll see yourself what happens. -- Gabriel Genellina From steve at REMOVEME.cybersource.com.au Wed Feb 14 21:17:00 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 13:17:00 +1100 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> <7xr6ssqis8.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 14 Feb 2007 18:03:19 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> self.isDataLoaded = False >> try: >> f = open(self.filename, 'rb') >> f.seek(DATA_OFFSET) >> self.__data = f.read(DATA_SIZE) >> self.isDataLoaded = True >> except: >> pass >> else: >> pass >> >> (apart from being four lines shorter) > > Your version never closes the file. Yes it does. Eventually f goes out of scope and is closed automatically. I don't see where the "with" version closes the file either. How does it know that I want to call the f's close() method, rather than, say, f.exit() or f.do_something_else()? -- Steven D'Aprano From savvas83 at gmail.com Mon Feb 26 16:16:14 2007 From: savvas83 at gmail.com (iceman) Date: 26 Feb 2007 13:16:14 -0800 Subject: Add images together In-Reply-To: <1172523536.033424.122230@a75g2000cwd.googlegroups.com> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> <54gtc3F214sakU1@mid.uni-berlin.de> <1172521836.797866.96220@z35g2000cwz.googlegroups.com> <1172523536.033424.122230@a75g2000cwd.googlegroups.com> Message-ID: <1172524574.348556.216270@z35g2000cwz.googlegroups.com> a)Yes, I am using PIL. b)The color of each pixel over a sequence of frames From jstroud at mbi.ucla.edu Thu Feb 15 07:38:41 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 15 Feb 2007 04:38:41 -0800 Subject: f---ing typechecking In-Reply-To: <1171526027.568047.186800@v33g2000cwv.googlegroups.com> References: <1171526027.568047.186800@v33g2000cwv.googlegroups.com> Message-ID: Paul McGuire wrote: > Since tuples are immutable, I think of them as fixed data objects with > some simple sequential structure, as opposed to lists which are much > more dynamically accessible/updateable data containers. Back in my > relational database design days, I sometimes had to create a primary > key for a table by combining values stored in two or more columns - > neither column value alone was unique, but the combination of them > was, and so made a good retrieval index. In Python, such data pairs > would be ideally represented with tuples, in support of in-memory data > cacheing or tree indexing - for a given record, the values don't > change, so the immutability of their tupleness doesn't get in the way. > > In similar vein, I've used tuples internally in my Python code as > cache keys for function memoizing. They are WORM structures - write > once, read many - built to represent the cache value, but never > updated. > With this idea of tuples as a data structure, I could reasonably > interpret this: > > (1,"abc",3) + [1] > > to result in (1,"abc",3,[1]) just as well as (1,"abc",3,1). But > instead of just picking one, Python complains about this, and so > forces me to explicitly use > > (1,"abc",3) + tuple([1]) > > or > > (1,"abc",3) + ([1],) > > I don't think tuples are just an academic curiosity, as your post > seems to suggest. > > -- Paul Were lists implemented as efficiently as tuples in terms of memory and speed, there would be no difference except the academic one--which is perhaps important. Actually, I must admit that I use them and their implicit meanings all the time in my code (as proof, notice in the "any way to create a table-like object?" thread how I specify column headers--its for a reason I use tuple in the example because the resulting data structures will be ordered according to the tuple passed--of course, I refuse to enforce this via "ugly and boring" type checking). For the most part, I ignore the implementation differences and draw the distinction at their semantics. Also, risking getting a reputation for being overly contentious, I think your argument falls apart in the latter half of your post because "+", as far as I can tell with python sequences, is used to mean catenate exclusively and not append, which is what you suggest as a possibility. Anyway, D'Arpano made an excellent point with a good mind-reading example and so I understand the design decision regarding catenation of tuples and lists more clearly now. I'm still not sure I like it, but there is no accounting for taste. James From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 28 18:22:12 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 00:22:12 +0100 Subject: using telnetlib References: <1172654582.919944.13530@k78g2000cwa.googlegroups.com> <54l6hpF21daqnU1@mid.individual.net> <1172667194.789186.235640@p10g2000cwp.googlegroups.com> Message-ID: <54mh54F21ho3eU2@mid.individual.net> Phoe6 wrote: > That did help and solved my problem. ":" after \n was just a typo. Thanks for feedback :) I've had a similar problem once, too. Regards, Bj?rn -- BOFH excuse #166: /pub/lunch From worlman385 at yahoo.com Mon Feb 12 19:45:10 2007 From: worlman385 at yahoo.com (worlman385 at yahoo.com) Date: Mon, 12 Feb 2007 16:45:10 -0800 Subject: star_new_thread References: Message-ID: Simpified the code to use FUNCTION only without CLASS http://chiu424.hypermart.net/code5-demo2.py.txt (short version) the above code start a new thread to run the function that send / receive data to socket, but still hangs at the timeout_h function forever ================================== http://chiu424.hypermart.net/code5i.py.txt (full version) above used threads to send /receive data to socket, will hang at function timeout_h forever ANYONE KNOWS WHY????? ================================== http://chiu424.hypermart.net/code5j.py.txt (full version) above used single thread and it can receive and send data at the same socket at same time ANY ONE KNOWS why the one with 2 threads doesn't work ?????? thank you From fuzzyman at gmail.com Sun Feb 18 18:56:48 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 18 Feb 2007 15:56:48 -0800 Subject: Getting a class name In-Reply-To: <45d8df9d$0$28886$426a74cc@news.free.fr> References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> <1171818881.871094.295870@v33g2000cwv.googlegroups.com> <45d8df9d$0$28886$426a74cc@news.free.fr> Message-ID: <1171843008.635203.50290@v45g2000cwv.googlegroups.com> On Feb 18, 11:54 pm, Bruno Desthuilliers wrote: > Gabriel Genellina a ?crit : > > > En Sun, 18 Feb 2007 14:14:41 -0300, goodwolf > > escribi?: > > >> On Feb 18, 9:17 am, "Gabriel Genellina" wrote: > > >>> En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf > >>> escribi?: > > >>> > I suppose that you wont get class name into its code (or before > >>> > definition end) but not into a method definition. > > >>> > import sys > > >>> > def getCodeName(deap=0): > >>> > return sys._getframe(deap+1).f_code.co_name > > >>> > class MyClass (object): > >>> > name = getCodeName() + '!' > > >>> What's the advantage over MyClass.__name__? > > >>> -- > >>> Gabriel Genellina > > >>>>> class C(object): > > >> ... name = C.__name__ > >> ... > >> Traceback (most recent call last): > >> File "", line 1, in ? > >> File "", line 2, in C > >> NameError: name 'C' is not defined > > > I were asking, why do you want a "name" attribute since "__name__" > > already exists and has the needed information. And worst, using an > > internal implementation function to do such task. > > This might be useful to avoid metaclass hacks when trying to initialize > a class attribute that would require the class name. (my 2 cents) It's still an ugly hack. :-) (But a nice implementation detail to know about none-the-less.) Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From gagsl-py at yahoo.com.ar Thu Feb 1 20:55:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 22:55:32 -0300 Subject: win32com.client References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170292629.986774.88240@a34g2000cwb.googlegroups.com> <1170379129.022674.121600@v45g2000cwv.googlegroups.com> Message-ID: En Thu, 01 Feb 2007 22:18:49 -0300, vithi escribi?: > If you are saying win32com in part of the python then you are wrong. Uh, what is so difficult to understand? vithi wrote: >> Any one tell me where I can get (or download) python modules win32com On Jan 31, 1:45 pm, Gary Herron wrote: >> You want the "python for windows" extension, available from >> http://sourceforge.net/projects/pywin32/ You didn't believe him, so I wrote: >> Yes. You get the win32com module from the above url. It's part of that >> package, by Mark Hammond, and a lot of people uses it. rzed wrote: >> I think the ActiveState distro includes it as part of its package. vithi wrote: >>>> import win32com > > Traceback (most recent call last): > File "", line 1, in > import win32com > ImportError: No module named win32com >>>> Sure, you don't have it installed, else you would not be asking here. > you try in your computer Why should I? -- Gabriel Genellina From Finger.Octopus at gmail.com Fri Feb 9 05:24:31 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 9 Feb 2007 02:24:31 -0800 Subject: Problem - Win32 Programming Message-ID: <1171016671.740414.30730@p10g2000cwp.googlegroups.com> Hi .. I'm a newbie to python win32 programming. I was just reading Python Programming on Win32 and I was trying to run this program: # SimpleCOMServer.py - A sample COM server - almost as small as they come! # # We expose a single method in a Python COM object. class PythonUtilities: _public_methods_ = [ 'SplitString' ] _reg_progid_ = "PythonDemos.Utilities" # NEVER copy the following ID # Use "print pythoncom.CreateGuid()" to make a new one. _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}" def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) # Add code so that when this script is run by # Python.exe, it self-registers. if __name__=='__main__': print "Registering COM server..." import win32com.server.register win32com.server.register.UseCommandLine(PythonUtilities) I am using Python 2.5 and it says: Traceback (most recent call last): File "E:/PyEN/PythonUtilities.py", line 20, in import win32com.server.register ImportError: No module named win32com.server.register From a.schmolck at gmail.com Mon Feb 5 13:17:31 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 18:17:31 +0000 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: Larry Bates writes: > And why is that superior to this: > > def avg(l): > return float(sum(l))/len(l) > > >>>avg([1,2,3,4]) > 2.5 Apart from being less to type and it is superior in that it's generalizes much better, e.g: avg&.^. NB. geomtric mean avg&.% NB. harmonic mean avg M NB. column mean of matrix M avg"1 M NB. row mean of matrix M 'as From sjdevnull at yahoo.com Mon Feb 5 16:57:48 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 5 Feb 2007 13:57:48 -0800 Subject: Python does not play well with others In-Reply-To: <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> References: <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> Message-ID: <1170712668.870316.247580@q2g2000cwa.googlegroups.com> On Feb 5, 12:52 pm, John Nagle wrote: > sjdevn... at yahoo.com wrote: > > John Nagle wrote: > > >>Graham Dumpleton wrote: > > >>>On Feb 4, 1:05 pm, Paul Rubin wrote: > > >>>>"Paul Boddie" writes: > >> Realistically, mod_python is a dead end for large servers, > >>because Python isn't really multi-threaded. The Global Python > >>Lock means that a multi-core CPU won't help performance. > > > The GIL doesn't affect seperate processes, and any large server that > > cares about stability is going to be running a pre-forking MPM no > > matter what language they're supporting. > > Pre-forking doesn't reduce load; it just improves responsiveness. > You still pay for loading all the modules on every request. No, you don't. Each server is persistent and serves many requests-- it's not at all like CGI, and it reuses the loaded Python image. So if you have, say, an expensive to load Python module, that will only be executed once for each server you start...e.g. if you have Apache configured to accept up to 50 connections, the module will be run at most 50 times; once each of the 50 processes has started up, they stick around until you restart Apache, unless you've configured apache to only serve X requests in one process before restarting it. (The one major feature that mod_python _is_ missing is the ability to do some setup in the Python module prior to forking. That would make restarting Apache somewhat nicer). The major advantage of pre-forking is that you have memory protection between servers, so a bug in one won't take down the whole apache server (just the connection(s) that are affected by that bug). Most shared hosting providers use pre-forking just for these stability reasons. A nice side effect of the memory protection is that you have completely seperate Python interpreters in each process--while each one is reused between connections, they run in independent processes and the GIL doesn't come into play at all. From boris.smirnov at gmail.com Tue Feb 27 02:43:32 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 26 Feb 2007 23:43:32 -0800 Subject: Interactive os.environ vs. os.environ in script In-Reply-To: References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> Message-ID: <1172562212.691747.150310@m58g2000cwm.googlegroups.com> On Feb 26, 5:44 pm, Thinker wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > > > > boris.smir... at gmail.com wrote: > > > OK then I have to reformulate my question. :) > > > In my script I have a line with > > > os.environ["LD_LIBRARY_PATH"]='/path/Linux/rh_linux' > > > but this line didn't work. But when I set this environment variable > > in Linux shell it works. Here is a small example. > > >> python shrink_bs_070226.py > > Traceback (most recent call last): File "shrink_bs_070226.py", line > > 25, in ? from qt import * File > > "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ qt.py", > > line 46, in ? import libsip ImportError: libadamsqt.so: cannot open > > shared object file: No such file or directory > > ld-elf.so reads environment variables when it was loaded. > It never reads environment variables again! > That you setting environment in the process does not make link-editor > to re-read environment variable and take effect. > > To resolve the problem, you can try to add the path to sys.path. > > - -- > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF4w6H1LDUVnWfY8gRAoI0AKCLikYsFU2N6aaOZFDd1L2KY8DjqACg3QQn > KsEEcrvpw1CktEkVCKe/ojk= > =EQG6 > -----END PGP SIGNATURE------ Hide quoted text - > > - Show quoted text - Hi, thanks for the tip, but it didn't help. I used: sys.path.append('/path/Linux/rh_linux') and the problem still persists: Traceback (most recent call last): File "shrink_bs_070226.py", line 26, in ? from qt import * File "/path/Linux/python/rh_linux/lib/python2.2/site-packages/ qt.py", line 46, in ? import libsip ImportError: libadamsqt.so: cannot open shared object file: No such file or directory Is there another possibility of how to solve it just by adding some lines in script? Thanks Boris From nagle at animats.com Tue Feb 13 13:29:38 2007 From: nagle at animats.com (John Nagle) Date: Tue, 13 Feb 2007 18:29:38 GMT Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: Daniel Nogradi wrote: >> I use the thread module (not threading) for a client/server app where I >> distribute large amounts of pickled data over ssh tunnels. What module are you using for SSH? What's in your program that isn't pure Python? The problem is probably in some non-Python component; you shouldn't be able to force a memory protection error from within Python code. Also note that the "marshal" module may be unsafe. John Nagle From uval at rz.uni-karlsruhe.de Mon Feb 19 11:24:11 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Mon, 19 Feb 2007 17:24:11 +0100 Subject: pylab, integral of sinc function Message-ID: Hello, In [19]: def simple_integral(func,a,b,dx = 0.001): ....: return sum(map(lambda x:dx*x, func(arange(a,b,dx)))) ....: In [20]: simple_integral(sin, 0, 2*pi) Out[20]: -7.5484213527594133e-08 ok, can be thought as zero In [21]: simple_integral(sinc, -1000, 1000) Out[21]: 0.99979735786416357 hmm, it should be something around pi it is a way too far from it, even with a=-10000,b=10000 In [22]: def ppp(x): ....: return sin(x)/x ....: In [23]: simple_integral(ppp, -1000, 1000) Out[23]: 3.1404662440661117 nice is my sinc function in pylab broken? is there a better way to do numerical integration in pylab? Regards, Daniel From garrickp at gmail.com Fri Feb 16 18:07:47 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 16 Feb 2007 15:07:47 -0800 Subject: output to console and to multiple files In-Reply-To: References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171645473.844315.152020@k78g2000cwa.googlegroups.com> Message-ID: <1171667267.259758.68440@k78g2000cwa.googlegroups.com> On Feb 16, 3:28 pm, "Gabriel Genellina" wrote: > > That's ok inside the same process, but the OP needs to use it "from a > subprocess or spawn". > You have to use something like tee, working with real file handles. > I'm not particularly familiar with this, but it seems to me that if you're trying to catch stdout/stderr from a program you can call with (say) popen2, you could just read from the returned stdout/stderr pipe, and then write to a series of file handles (including sys.stdout). Or am I missing something? =) ~G From deviantbunnylord at gmail.com Sun Feb 11 11:35:26 2007 From: deviantbunnylord at gmail.com (deviantbunnylord at gmail.com) Date: 11 Feb 2007 08:35:26 -0800 Subject: Regular Expressions In-Reply-To: References: Message-ID: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> > That's a little harsh -- regexes have their place, together with pointer > arithmetic, bit manipulations, reverse polish notation and goto. The > problem is when people use them inappropriately e.g. using a regex when a > simple string.find will do. > > > A quote attributed variously to > > Tim Peters and Jamie Zawinski says "Some people, when confronted with a > > problem, think 'I know, I'll use regular expressions.' Now they have two > > problems." > > I believe that is correctly attributed to Jamie Zawinski. > > -- > Steven So as a newbie, I have to ask. I've played with the re module now for a while, I think regular expressions are super fun and useful. As far as them being a problem I found they can be tricky and sometimes the regex's I've devised do unexpected things...(which I can think of two instances where that unexpected thing was something that I had hoped to get into further down the line, yay for me!). So I guess I don't really understand why they are a "bad idea" to use. I don't know of any other way yet to parse specific data out of a text, html, or xml file without resorting to regular expressions. What other ways are there? From igorr at ifi.uio.no Fri Feb 2 13:30:53 2007 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 02 Feb 2007 19:30:53 +0100 Subject: Checking default arguments Message-ID: Hi, I was wondering whether it was possible to find out which parameter value is being used: the default argument or the user-supplied one. That is: def foo(x, y="bar"): # how to figure out whether the value of y is # the default argument, or user-supplied? foo(1, "bar") => user-supplied foo(1) => default {}.pop seems to be able to make this dictinction. I've checked the inspect module, but nothing obvious jumped at me. Any hints? Thanks, ivr -- "...but it's HDTV -- it's got a better resolution than the real world." -- Fry, "When aliens attack" From TBollmeier at web.de Wed Feb 21 09:18:55 2007 From: TBollmeier at web.de (Thomas Bollmeier) Date: 21 Feb 2007 06:18:55 -0800 Subject: Replacement for GnomeDateEdit? Message-ID: <1172067535.456885.176190@j27g2000cwj.googlegroups.com> Hi, I'm currently designing a dialog using pygtk/Glade. One of the attributes to be edited is a date. I tried to use the GnomeDateEdit widget that is available among the widgets in glade. Unfortunately the "time"-property only allows me to use timestamps for dates >= January 1st 1970. Since the date to be edited is a birth date this constraint is not acceptable for my application. Does anyone know whether there is another widget around with a pygtk-binding that I could use instead? Best regards, Thomas From nagle at animats.com Fri Feb 2 17:34:49 2007 From: nagle at animats.com (John Nagle) Date: Fri, 02 Feb 2007 14:34:49 -0800 Subject: Where Does One Begin? In-Reply-To: References: Message-ID: Mister Newbie wrote: > I have no programming experience. I want to learn Python so I can make > simple, 2D games. Where should I start? Can you recommend a good book? > > Thank you. Blender GameKit. John Nagle From bignose+hates-spam at benfinney.id.au Sat Feb 3 00:24:54 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Feb 2007 16:24:54 +1100 Subject: from... import... References: <9s28s29864vgkdbtevi8fna5h1r04ekgr9@4ax.com> Message-ID: <874pq3u82h.fsf@benfinney.id.au> fatwallet961 at yahoo.com writes: > what's the from ... import keyword use for? > for example - from contenttype import getContentType > > import os > import sys > import getopt > import types > import re > import pprint > import logging > from contenttype import getContentType The program now can access attributes as follows: foo = sys.argv[1] bar = logging.getLogger() baz = getContentType() In other words, use 'from spam import eggs' when you want to refer to 'eggs' instead of 'spam.eggs'. In the specific case you cite, probably the programmer knows they only want to access one attribute -- 'getContentType' -- and would rather use that name for ease of reading rather than the longer 'contenttype.getContentType'. It's for this reason that many of the standard library modules have relatively short names, eight characters or less. It has the result that 'import spam' followed by access to 'spam.eggs' is both clear, and easy enough to read. To learn more, read about Python namespaces. -- \ "I bought a dog the other day. I named him Stay. It's fun to | `\ call him. 'Come here, Stay! Come here, Stay!' He went insane. | _o__) Now he just ignores me and keeps typing." -- Steven Wright | Ben Finney From uval at rz.uni-karlsruhe.de Thu Feb 15 03:20:18 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 15 Feb 2007 09:20:18 +0100 Subject: builtin set literal In-Reply-To: References: Message-ID: Steven Bethard schrieb: > Sch?le Daniel wrote: >> Hello, >> >> lst = list((1,2,3)) >> lst = [1,2,3] >> >> t = tupel((1,2,3)) >> t = (1,2,3) >> >> s = set((1,2,3)) >> s = ... >> >> it would be nice feature to have builtin literal for set type >> maybe in P3 .. what about? >> s = <1,2,3> > > In Python 3.0, this looks like:: > > s = {1,2,3} jepp, that looks not bad .. as in a mathe book. the only disadvantage I see, that one may confuse it with a dict. Regards, Daniel From robin at reportlab.com Mon Feb 26 05:51:14 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 26 Feb 2007 10:51:14 +0000 Subject: newbie question(file-delete trailing comma) In-Reply-To: <860807.3780.qm@web7805.mail.in.yahoo.com> References: <860807.3780.qm@web7805.mail.in.yahoo.com> Message-ID: <45E2BBA2.1040405@chamonix.reportlab.co.uk> kavitha thankaian wrote: > hi, > > i have a file which has the contents as follows: > > a,b,c,d, > a1,b1,c1,d1, > a2,b2,c2,d2, > > i would like to delete all the trailing commas,, > > if someoneknows pls help me,, > > kavitha ...... I often use sed for such small problems. c:\tmp>cat ex.txt a,b,c,d, a1,b1,c1,d1, a2,b2,c2,d2, c:\tmp>sed -e"s/,$//" ex.txt a,b,c,d a1,b1,c1,d1 a2,b2,c2,d2 c:\tmp> that doesn't involve python of course. I recommend one of the many tutorial introductions to python if the problem requires its use. -- Robin Becker From deets at nospam.web.de Sat Feb 3 11:59:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 03 Feb 2007 17:59:13 +0100 Subject: Python does not play well with others In-Reply-To: <7xfy9n2pz4.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xejp89pa9.fsf@ruckus.brouhaha.com> <7xfy9n2pz4.fsf@ruckus.brouhaha.com> Message-ID: <52jtb2F1o9nc2U1@mid.uni-berlin.de> Paul Rubin schrieb: > skip at pobox.com writes: >> I can't speak authoritatively for either PHP or J2SE, but I suspect the >> latter at least has some signifiant monetary support (if not outright gobs >> of human resources) from Sun. PHP seems to have a more limited application >> domain (web apps) from which it has expanded a bit. Can I build a PHP site >> out of the box with a PostgreSQL or Oracle backend? > > I believe so, from having looked at the docs a while back, but I > haven't tried it. The docs cover all the available drivers, as they are hard-coded in the source. Yet you need to specify inclusion of them at compile-time, and as I said: some distros don't ship with non-OS-drivers. >> Does J2SE have something comparable to Numpy or scipy? > > I don't think so, but Python doesn't either. > >> While might do the occasional bit of Python hacking for free, I still need >> to put food on the table. My employer doesn't care if MySQLdb (to use one >> of your examples) is delivered with Python or not. They aren't likely to >> want to support me to solve your problems. > > The same could be said of Tkinter (a large and complex library module) > or IDLE (a full blown mid-sized application shipped with Python). The > answer is the same for both: if you don't need to use a given module, > then don't. Why would I expect your employer to solve my problems > anyway, even if they relate to some module that you actually use? As far as I can tell, primary concerns for inclusion of modules are twofold: - dependencies, which certainly are an issue for DB-modules! Or do you want every python build to need the oracle OCI drivers installed? Plus headers? - maintainer commitment. Diez From deets at nospam.web.de Thu Feb 22 04:58:32 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 10:58:32 +0100 Subject: jython import search path References: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> <1172105604.157543.191450@k78g2000cwa.googlegroups.com> Message-ID: <5457q8F1rqvu1U1@mid.uni-berlin.de> Russ wrote: > On Feb 21, 4:15 pm, Larry Bates wrote: >> Russ wrote: >> > I have a Python program that I want to run in Jython so I can get Java >> > bytecode output. The program runs fine in Python, but when I change >> > the first line of the main program to make it run in Jython, it fails >> > to find some of the imported modules. These are just plain Python >> > imports of code I wrote myself in another directory. >> >> > Apparently Jython does not use the PYTHONPATH environment variable. I >> > created an environment variable called JYTHONPATH just to see what >> > would happen, but it didn't work either. How am I supposed to tell >> > Jython where to search for imported modules? Thanks. >> >> Maybe Jython expert has the perfect answer but til then. >> >> Did you try: >> >> sys.path.append('path to search') >> >> Usually this works if nothing else does. >> >> -Larry > > Thanks. That's a good workaround, but I would like to know the > "correct" way to do it too if anyone out there knows. That is pretty much an accepted strategy. Another one is to alter the registry file, which has a property python.path. It might even be possible to use java -Dpython.path= to accomplish that - but I'm to lazy to toy around now. Diez From bob at work.org Tue Feb 13 23:12:59 2007 From: bob at work.org (Martien Friedeman) Date: 14 Feb 2007 17:12:59 +1300 Subject: Testers please References: <8cde9$45d179ba$83aef404$16072@news1.tudelft.nl> <45d2449e$1@clear.net.nz> <12t4tuel9uah410@corp.supernews.com> Message-ID: <45d28c4b$1@clear.net.nz> Thanks for that for that Scott. Most of hassle is storing the program flow. For example: Iteration 3 of the loop starting on line 12 has itself a loop on line 15 that has 14 iterations. Iteration 4 of the loop starting on line 12 has a completely different set of iterations for the loop on line 15. If at all(!) All that is stored in a tree which I pickle and write to the database. Massive program runs will create large trees. And this pickling is expensive. From deets at nospam.web.de Wed Feb 14 07:16:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Feb 2007 13:16:11 +0100 Subject: replacing substrings within strings References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> Message-ID: <53gcsbF1sbe8oU1@mid.uni-berlin.de> amadain wrote: > Hi > I was wondering if there was a nicer way to swap the first 2 > characters in a string with the 4th and 5th characters other than: > > darr=list("010203040506") > aarr=darr[:2] > barr=darr[4:6] > darr[:2]=barr > darr[4:6]=aarr > result="".join(darr) > > The above code works fine but I was wondering if anybody had another > way of doing this? You can do it like this: darr=list("010203040506") darr[:2], darr[4:5] = darr[4:6], darr[:2] result="".join(darr) print result Diez From rNOSPAMon at flownet.com Thu Feb 1 22:50:42 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 01 Feb 2007 19:50:42 -0800 Subject: Python, readline and OS X References: Message-ID: In article , James Stroud wrote: > Ron Garret wrote: > > I have installed Python 2.5 on my new Intel Mac but I can't for the life > > of me get readline to work. I have libreadline installed, I've tried > > copying readline.so from my Python 2.3 installation into 2.5, I've > > searched the web, and no joy. Could someone please give me a clue? > > > > rg > > Where have you installed libreadline? /usr/local/lib > Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib? It wasn't, but changing it so it did didn't fix the problem. (I didn't try recompiling Python, just running it. I'll try rebuilding later.) > Did you install libreadline with fink? No, I just got the source from the FSF and did ./configure ; make install > Bash (OSX default) and similar shells use this silly 2 part syntax: > > LD_LIBRARY_PATH=/sw/lib > export LD_LIBRARY_PATH Actually you can do it in one line: export LD_LIBRARY_PATH=whatever :-) > Do a "locate libreadline.dylib" and set the LD_LIBRARY_PATH to the > containing directory and then > > make clean > ./configure > make > make install > > or similar. I'll give that a whirl. Thanks. rg From rscottco at gmail.com Thu Feb 22 00:23:20 2007 From: rscottco at gmail.com (rscottco at gmail.com) Date: 21 Feb 2007 21:23:20 -0800 Subject: Looking for contract developer(s) - where can I find them? In-Reply-To: References: Message-ID: <1172121800.532683.126450@q2g2000cwa.googlegroups.com> On Feb 21, 9:51 pm, Scott SA wrote: > > I've just sent a job listing to python.org and posted this message on > comp.lang.python, Interesting, so Python-list at python.org and comp.lang.python are _related_. I guess that means I'm the new guy on the block. Well I guess this joke is on me this time ... LOL! Sorry for the double-post, I'll do my best to make it the last one. Cheers, Scott From http Thu Feb 15 17:26:37 2007 From: http (Paul Rubin) Date: 15 Feb 2007 14:26:37 -0800 Subject: Automated resizing of JPEG image + making slices? References: Message-ID: <7xk5yjukf6.fsf@ruckus.brouhaha.com> Michiel Sikma writes: > I know some Python (but not much since I've never actually written > that many things in it), and with some effort I could probably make a > simple image manipulator frontend in it, but only if I can find a > good library for doing the actual manipulation. Do any of you know > such libraries? Search for "Python Imaging Library". From george.sakkis at gmail.com Wed Feb 28 22:18:01 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 28 Feb 2007 19:18:01 -0800 Subject: Subprocess timeout Message-ID: <1172719081.740323.57490@s48g2000cws.googlegroups.com> I'm trying to use a threaded timeout decorator (http:// aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752) to spawn a subprocess with a timeout. On a linux box runnning python 2.5 I get "OSError: [Errno 10] No child processes" on wait(); running the same program on a different box (again linux) with python 2.4 doesn't throw an exception. Here's a sample snippet: import os from subprocess import Popen,PIPE @timelimit(3) def f(cmd): return Popen(cmd, stdout=PIPE) p = f('ls') print os.getpid(), p.pid # the next line raises OSError on 2.5 but not on 2.4 print os.waitpid(p.pid, 0) What gives ? George From wolf_tracks at invalid.com Thu Feb 8 19:24:06 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 08 Feb 2007 16:24:06 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> <45CBB3CA.7010501@invalid.com> Message-ID: <45CBBF26.9020405@invalid.com> Robert Kern wrote: > W. Watson wrote: > >> Here's the program I ran. >> >> ### begin >> #!/usr/bin/python >> >> # Check mysys >> >> import sys >> print sys.executable >> >> ### end >> >> It put up a black screen in a flash and disappeared. > > Run it from the terminal or execute those lines in the interactive interpreter > in IDLE. Also, you may want to use the Tutor list, instead of comp.lang.python. > It is more geared towards the questions you are asking. > > http://mail.python.org/mailman/listinfo/tutor > I entered each line in the shell, and the output shows C:\Python25\pythonw.exe, so it's not using 2.4. How do I change that? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two million years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From mike.klaas at gmail.com Thu Feb 8 21:17:55 2007 From: mike.klaas at gmail.com (Klaas) Date: 8 Feb 2007 18:17:55 -0800 Subject: Built-in datatypes speed In-Reply-To: References: Message-ID: <1170987475.883562.67860@j27g2000cwj.googlegroups.com> On Feb 7, 2:34 am, Ma?l Benjamin Mettler wrote: > Anyway, I reimplemented parts of TigerSearch (http://www.ims.uni-stuttgart.de/projekte/TIGER/TIGERSearch/) in Python. > I am currently writing the paper that goes along with this > reimplementation. Part of the paper deals with the > differences/similarities in the original Java implementation and my > reimplementation. In order to superficially evaluate differences in > speed, I used this paper (http://www.ubka.uni-karlsruhe.de/cgi-bin/psview?document=ira/2000/5&f... > ) as a reference. Now, this is not about speed differences between Java > and Python, mind you, but about the speed built-in datatypes > (dictionaries, lists etc.) run at. As far as I understood it from the > articles and books I read, any method call from these objects run nearly > at C-speed (I use this due to lack of a better term), since these parts > are implemented in C. Now the question is: > > a) Is this true? > b) Is there a correct term for C-speed and what is it? I think the statement is highly misleading. It is true that most of the underlying operations on native data types are implemented in c. If the operations themselves are expensive, they could run close to the speed of a suitably generic c implementation of, say, a hashtable. But with richer data types, you run good chances of landing back in pythonland, e.g. via __hash__, __equals__, etc. Also, method dispatch to c is relatively slow. A loop such as: lst = [] for i in xrange(int(10e6)): lst.append(i) will spend most of its time in method dispatch and iterating, and very little in the "guts" of append(). Those guts, mind, will be quick. -Mike From jura.grozni at gmail.com Thu Feb 8 12:26:57 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 09:26:57 -0800 Subject: python linux distro In-Reply-To: References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: <1170955617.478249.82460@m58g2000cwm.googlegroups.com> thanks guys when i wrote this, i thought that out there is some crazy guy like me. i was hoping for more support but after these arguments, there is nothing more then to say:you are right. the world doesnt need another distro. but if one day I mange to do it, hope you will be glade that i post the lik here. i will look out (if i mange to do it) to use the slax distro and just add some packages. thnx On Feb 8, 5:56 pm, Steve Holden wrote: > azrael wrote: > > Hy guys > > > last night i was lying in my bed and thinking about something. is > > there any linux distro that is primary oriented to python. you know > > what i mean. no need for php, java, or something like this. pure > > python and containig all the funky modules like scipy, numpy, > > boaconstructor (wx of course). something like the python enthought > > edition, but all this on a distro included. maybe psql but persistant > > predered, zope of course. everything a developer is ever going to > > need. > > So i stood up, sat down on my ugly acer notebook with a python stiker > > on it and made a huge list of cool modles i would prefer. I would like > > to make such a distro but i am not a linux pro. so this is going to > > stay just a idea. i thouht it should be realy user fredly like sabayon > > or ubuntu (without xgel). if this were a live distro it would be > > amazing. > > I know, dont expet someone else to do your work, but is there anyone > > who likes the idea and has the knowledge i dont have. > > I also know for quantian (cool distro), but for me, there is too much > > other crap and not enough python. > > > i even got the nam of it. maybee not the best but it fits the context. > > PyTux > > Well, Ubuntu is normally held to be a pretty Python-friendly distro. But > nowadays you might get more mileage out of distributing a Xen or VMWare > virtual machine that has Python and all necessary packages installed > with it. There is a fine example, the Python Web Developer Appliance, at > > http://www.mcguru.net/pyweb.html > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007 From savvas83 at gmail.com Mon Feb 26 15:30:36 2007 From: savvas83 at gmail.com (iceman) Date: 26 Feb 2007 12:30:36 -0800 Subject: Add images together In-Reply-To: <54gtc3F214sakU1@mid.uni-berlin.de> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> <54gtc3F214sakU1@mid.uni-berlin.de> Message-ID: <1172521836.797866.96220@z35g2000cwz.googlegroups.com> What i am trying to do is to separate the foreground object from the background.All my images contain a foreground object (i don't have a reference image). What i am trying to do is to calculate a color-over-time-function for each pixel. From nogradi at gmail.com Fri Feb 16 04:58:54 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 16 Feb 2007 10:58:54 +0100 Subject: KeyboardInterrupt not caught In-Reply-To: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> References: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> Message-ID: <5f56302b0702160158g2bc55f99qdd00a06cfc4f8e09@mail.gmail.com> > why is KeyboardInterrupt not caught (xp)? > import sys > try: > inp = sys.stdin.read() > except (KeyboardInterrupt, SystemExit): > print "kbd-interr,SystemExit" > except EOFError: > print "eof encountered" > except: > print "caught all" > self.showtraceback() > print "normal end" > > result after script startet and ^C hit: > >ctrl_test.py > normal end > Traceback (most recent call last): > File "C:\work\py_src\ctrl_test.py", line 11, in ? > print "normal end" > KeyboardInterrupt Hi, are you sure this is exactly what you run? The code above works perfectly for me and prints kbd-interr,SystemExit normal end as it should upon pressing Ctrl-C (although I'm on linux not xp but that shouldn't matter at all). From Robert.Katic at gmail.com Sat Feb 17 10:06:41 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 17 Feb 2007 07:06:41 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <1171724801.726988.15210@j27g2000cwj.googlegroups.com> In your situation consider C# too. If you like python then try IronPython for .NET. I think that C++ is not ideal for you. P.S.: VB6 is NOT a real OOP language. From anil.jupiter9 at gmail.com Mon Feb 19 00:54:45 2007 From: anil.jupiter9 at gmail.com (jupiter) Date: 18 Feb 2007 21:54:45 -0800 Subject: function & class In-Reply-To: <53s2hsF1tr4fuU1@mid.individual.net> References: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> <53s2hsF1tr4fuU1@mid.individual.net> Message-ID: <1171864485.501767.307420@v33g2000cwv.googlegroups.com> c.execute("select symbol,tvolume,date,time from "+self.dbase+" where symbol= ?",t) ProgrammingError: SQLite objects created in a thread can only be used in that sa me thread.The object was created in thread id 976 and this is thread id 944 I am getting this error when I am using sql command within class.function accessing from another class how can I create seperate instance for sqlite objects ??????? @nil From liuwensui at gmail.com Tue Feb 27 17:31:05 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Tue, 27 Feb 2007 17:31:05 -0500 Subject: book for a starter In-Reply-To: <1172606926.215944.227660@v33g2000cwv.googlegroups.com> References: <54j9qfF20cqgnU1@mid.individual.net> <1172603326.853903.315620@z35g2000cwz.googlegroups.com> <1172606926.215944.227660@v33g2000cwv.googlegroups.com> Message-ID: <1115a2b00702271431x59272addq3beab195b0f696c5@mail.gmail.com> Thank you all for your wonderful suggestion and advice. Have a great evening! wensui On 27 Feb 2007 12:08:46 -0800, RickMuller wrote: > On Feb 27, 12:08 pm, "Sriram" wrote: > > Hi, > > > > If you have experience programming, just read the online tutorial athttp://docs.python.org/tut/tut.html > > > > Seconded. It really is a wonderful introduction to Python. Once you've > digested that, the Python Library Reference in the docs is your best > friend. The nice thing about getting familiar with the official python > documentation is that it's always available to you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From nelson1977 at gmail.com Wed Feb 21 16:40:32 2007 From: nelson1977 at gmail.com (nelson -) Date: Wed, 21 Feb 2007 22:40:32 +0100 Subject: FloatCanvas in a wxpython application.... layout problems Message-ID: Hi all, i'm developing an application that uses Floatcanvas to diplay a cartesian plane. how can i embed it into a "complex" layout? I have this controls MENUS TOOLBAR NOTEBOOK FLOATCANVAS PYSHELL The problem is that i can show all the components but i can't insert the floatcanvas in the right position... it is'n displaied... can annyone give me an example of use of floatcanvas in an application with more than one panel... thanks a lot! nelson From bayer.justin at googlemail.com Wed Feb 28 16:27:43 2007 From: bayer.justin at googlemail.com (bayer.justin at googlemail.com) Date: 28 Feb 2007 13:27:43 -0800 Subject: Dialog with a process via subprocess.Popen blocks forever Message-ID: <1172698063.670659.318340@k78g2000cwa.googlegroups.com> Hi, I am trying to communicate with a subprocess via the subprocess module. Consider the following example: >>> from subprocess import Popen, PIPE >>> Popen("""python -c 'input("hey")'""", shell=True) >>> hey Here hey is immediately print to stdout of my interpreter, I did not type in the "hey". But I want to read from the output into a string, so I do >>> x = Popen("""python -c 'input("hey\n")'""", shell=True, stdout=PIPE, bufsize=2**10) >>> x.stdout.read(1) # blocks forever Is it possible to read to and write to the std streams of a subprocess? What am I doing wrong? Regards, -Justin From mail at microcorp.co.za Fri Feb 16 01:04:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 16 Feb 2007 08:04:28 +0200 Subject: how do "real" python programmers work? References: <0EC8A68FD54CDD4FB6B92EE7B713ED3601331455@SAN-THC-NODE02.lbcamden.net> <45D431B5.3080107@timgolden.me.uk> Message-ID: <023d01c75197$a7160c20$03000080@hendrik> "Tim Golden" wrote: > Tyrrell, Wendy wrote: > > (Well, nothing) > 8<-------------------------- > Your organisation seems to deal with partnerships between > business and education; are you looking to promote the use > of programming in schools? Or is there something else you're > after? > > (I'm above-averagely curious because I work in Camden and > I'm involved in Youth work in Ealing). oooooh! - The line has caught a fish. And a fine one too... - Hendrik From boris.smirnov at gmail.com Wed Feb 28 03:07:51 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 28 Feb 2007 00:07:51 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172609807.109748.93170@8g2000cwh.googlegroups.com> <1172617785.871756.77380@j27g2000cwj.googlegroups.com> Message-ID: <1172650071.878083.106290@h3g2000cwc.googlegroups.com> On Feb 28, 8:56 am, Phil Thompson wrote: > On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > > > When your programs stops with the error, it should also be printing a > > stack trace. This is a list of all the functions that have been called > > when Python had the problem. > > > You shouldn't have to do anything extra to get the stack trace. > > The error is raised in Qt and aborts immediately. It never gets back to Python > to generate a trace. > > He needs to produce a short and complete test which demonstrates the problem, > then we can point out where the QPaintDevice is being created. > > Phil OK, but before I do a complete test, could anybody tell/explain me why the same file is working on Windows? Did anybody already meet with something similar Win vs. Linux? b. From bbands at gmail.com Tue Feb 6 15:51:13 2007 From: bbands at gmail.com (BBands) Date: 6 Feb 2007 12:51:13 -0800 Subject: Python editor Message-ID: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> No, no, no, this is not an invitation to the editor wars. I have been using Jos? Cl?udio Faria's superb Tinn-R, http://www.sciviews.org/Tinn-R/, with the R language, http://www.r-project.org/. This editor allows you to send code to the R shell for execution. You can easily send a line, the selection, the balance after the cursor or the whole script. I have recently decided to move this project to Python instead of R. However, I miss the interaction with the shell a la Tinn-R. Do any of the Python editors support this feature? I would be especially interested in using IPython as the shell. jab From Marshillboy at gmail.com Sun Feb 11 19:18:07 2007 From: Marshillboy at gmail.com (Marshillboy at gmail.com) Date: 11 Feb 2007 16:18:07 -0800 Subject: Hacking in python In-Reply-To: References: Message-ID: <1171239487.440891.254860@a34g2000cwb.googlegroups.com> On Feb 10, 5:25 pm, "Geoff Hill" wrote: > The word "hack" can be known as a "smart/quick fix" to a problem. Giving the benefit of the doubt here, perhaps Enes Naci saw this article: http://www.hetland.org/python/instant-hacking.php and got some strange idea about confusing programming with breaking into computer systems. Maybe. From dackze at gmail.com Tue Feb 6 11:44:43 2007 From: dackze at gmail.com (dackz) Date: Tue, 6 Feb 2007 11:44:43 -0500 Subject: Why does list.__getitem__ return a list instance for subclasses of the list type? Message-ID: <54c0a1810702060844q1f7b542dj73c381e09ff2f451@mail.gmail.com> >>> class ListyThing(list): pass ... >>> assert isinstance(ListyThing()[:], ListyThing) # I expect True! Traceback (most recent call last): File "", line 1, in AssertionError >>> type(ListyThing()[:]) # I expect ListyThing! I don't find this intuitive. Is this intentional? I believe this could be avoided if list.__getitem__ used "self.__class__()" to make a new instance, instead of "list()", but I don't know how that works under the hood in C. I believe this happens a lot of other cases too. Actually, I wrote up some test cases at http://brodierao.com/etc/listslice/ but I haven't taken a look at it in quite a while. I believe there's some other funky stuff going on there as well. Also, this happens with dict too: >>> class DictyThing(dict): pass ... >>> assert isinstance(DictyThing().copy(), DictyThing) # I expect True! Traceback (most recent call last): File "", line 1, in AssertionError >>> type(DictyThing().copy()) # I expect DictyThing! Any thoughts? From michele.simionato at gmail.com Mon Feb 12 13:56:15 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Feb 2007 10:56:15 -0800 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Message-ID: <1171306575.598386.14260@a34g2000cwb.googlegroups.com> On Feb 12, 4:48 pm, deviceran... at gmail.com wrote: > - is there a better way than using multiple inheritance to plug-in > dynamically commands in a Cmd command line? I had to solve the same problem recently, and I decided to avoid multiple inheritance by using delegation. My idea was to make the Cmd class a wrapper around an object with 'do_' methods. I give you the code as it is, without much explanations: just run it and give "help" on the command line. You can cut the part about the 'do_input' method which I needed in order to pass lists of strings to the inner object. Hope you can find some useful trick for solving your problem. Michele Simionato import sys, cmd, traceback, inspect try: # Python 2.5 from functools import update_wrapper except ImportError: def update_wrapper(wrapper, wrapped, assigned=('__module__', '__name__', '__doc__'), updated=('__dict__',)): for attr in assigned: setattr(wrapper, attr, getattr(wrapped, attr)) for attr in updated: getattr(wrapper, attr).update(getattr(wrapped, attr)) return wrapper def makewrapper(meth): if inspect.ismethod(meth): func = meth.im_func elif inspect.isfunction(meth): func = meth else: raise TypeError('%r must be a regular function or method' % meth) return update_wrapper(lambda self, arg: meth(arg), func) # dispatch the input dictionary to self.innerobj def do_input(self, arg): if arg.split(): # passed some argument of type 'name ' try: name, args = arg.split(' ', 1) except ValueError: print 'Wrong format: use the format input ' else: self.inputdict[name] = args.split(self.inputsep) else: self.innerobj.input(self.inputdict) self.inputdict = {} def copy_interface_methods(innerobj, _CLI): for attr in dir(innerobj): if attr.startswith('do_'): setattr(_CLI, attr, makewrapper(getattr(innerobj, attr))) elif attr == 'input': do_input.__doc__ = innerobj.input.__doc__ _CLI.do_input = do_input class CLI(cmd.Cmd, object): """ Wraps an object with 'do_' methods with a command line interface. """ def __new__(cls, innerobj, completekey='tab', stdin=None, stdout=None, nonblocking=False): class _CLI(cls): prompt = 'CLI> ' if stdin is not None: use_rawinput = False copy_interface_methods(innerobj, _CLI) return super(CLI, cls).__new__( _CLI, innerobj, completekey, stdin, stdout) def __init__(self, innerobj, completekey='tab', stdin=None, stdout=None): self.innerobj = innerobj if hasattr(self, 'do_input'): self.inputdict = {} self.inputsep = '|' cmd.Cmd.__init__(self, completekey, stdin, stdout) def onecmd(self, line): # enable comments if not line.startswith('#'): return super(CLI, self).onecmd(line) def emptyline(self): # does not repeat the last command pass def do_EOF(self, arg): "Called when you enter CTRL-D, it stops the command loop" return 1 if __name__ == '__main__': # test class PrintableObj(object): def __init__(self, x, y): self.x = x self.y = y def do_print(self, arg): "example" print self.x, self.y def input(self, dict_of_lists): 'just print the entered value' vars(self).update(dict_of_lists) print dict_of_lists cli = CLI(PrintableObj([], [])) cli.cmdloop() From hg at nospam.org Mon Feb 26 10:08:47 2007 From: hg at nospam.org (hg) Date: Mon, 26 Feb 2007 16:08:47 +0100 Subject: Python+Windows specific questions References: Message-ID: hg wrote: > Hi, > > Do I need the pywin32 extentions to: > > 1) change the pc system date ? > 2) launch a ppp connection ? > > Thanks, > > hg Yes to both I guess. hg From bapolis at gmail.com Thu Feb 1 20:04:45 2007 From: bapolis at gmail.com (Toine) Date: 1 Feb 2007 17:04:45 -0800 Subject: Calculating future dates In-Reply-To: <1170377690.176241.96590@p10g2000cwp.googlegroups.com> References: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> <1170377690.176241.96590@p10g2000cwp.googlegroups.com> Message-ID: <1170378285.708350.100830@s48g2000cws.googlegroups.com> On Feb 1, 4:54 pm, "Dan Bishop" wrote: > On Feb 1, 6:51 pm, "Toine" wrote: > > > Hello, > > > I'm new to Python so please bare with me... > > > I need to calculate a date that is exactly 31 days from the current > > date in YYYY-MM-DD format. I know that date.today() returns the > > current date, but how can I add 31 days to this result? I'm sure this > > task is simple, but I haven't been able to figure it out. > > > Thanks > > str(datetime.date.today() + datetime.timedelta(31)) Your example gave me a few errors but I was able to adapt it into this: str(date.today() + timedelta(31)) Thanks for your help From newsuser at stacom-software.de Thu Feb 1 13:05:15 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Thu, 01 Feb 2007 19:05:15 +0100 Subject: Heap problems in Mulithreaded Python extension In-Reply-To: References: Message-ID: ok, once more my "scheme" python extension ----------------------------------------------------- import extension extension.init() -> PyEval_InitThreads(); setup 3 threads (pthreads) and do a lot of things, but no python api calls while true: time.sleep(0.1) PyGILState_STATE gGILState; gGILState = PyGILState_Ensure(); (...) // Do python API calls PyGILState_Release(gGILState); From gagsl-py at yahoo.com.ar Mon Feb 12 13:01:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 15:01:46 -0300 Subject: Regular Expressions References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> <1171227036.789128.188720@q2g2000cwa.googlegroups.com> <1171275611.208401.212000@v33g2000cwv.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 07:20:11 -0300, deviantbunnylord at gmail.com escribi?: > The source of HTMLParser and xmllib use regular expressions for > parsing out the data. htmllib calls sgmllib at the begining of it's > code--sgmllib starts off with a bunch of regular expressions used to > parse data. So the only real difference there I see is that someone > saved me the work of writing them ;0). I haven't looked at the source > for Beautiful Soup, though I have the sneaking suspicion that most > processing of html/xml is all based on regex's. You can build a parser for SGML/HTML/XML documents using regexps AND python code. You can't do that with regexps only. By example, suppose you work hard to build a correct regexp for matching an opening
tag. You extract this from the document: "". Is it actually an tag? Maybe. But the text could be inside a comment. Or in a CDATA section. Or inside javascript code. Or... A regexp is good for recognizing tokens, and this can be used to build a parser. But regular expressions alone can't parse these kind of documents, just because their grammar is not regular. (Python re engine is stronger that "mathematical" regular expressions, in the sense that it can handle things like backreferences (?P=...) and lookahead (?=...) but anyway it can't handle HTML) -- Gabriel Genellina From nogradi at gmail.com Tue Feb 27 12:10:27 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 27 Feb 2007 18:10:27 +0100 Subject: gmpy moving to code.google.com In-Reply-To: References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> Message-ID: <5f56302b0702270910vc963414x6f8366f1ae086bf2@mail.gmail.com> > > Hi Alex, > > > > I did another test, this time with python 2.4 on suse and things are > > worse than in the previous case (which was python 2.5 on fedora 3), > > ouput of 'python gmp_test.py' follows: > > Interesting! gmpy interacts with decimal.Decimal by "monkey- > patching" that class on the fly; clearly the monkey-patching isn't > working with 2.4 on SuSE, so all the addition attempts are failing > (all 6 of them). > > So the issue is finding out why this strategy is failing there, while > succeeding on other Linux distros, Mac, and Windows. > > To that end, I have added a feature in the latest svn trunk (revision > 11) to set gmpy's own options.debug flag from an environment variable > named GMPY_DEBUG at startup (if that environment variable is set). > > If you could please svn up and rebuild, then running with GMPY_DEBUG > set in the environment should give something like: > > brain:~/gmpy alex$ GMPY_DEBUG=1 python -c 'import gmpy' 2>&1 | tail -5 > mp_allocate( 4->8 ) > mp_allocate( 4->8 ) ->0x60b8b0 > gmpy_module at 0x63390 > gmpy_module imported decimal OK > gmpy_module tweaked decimal OK > > This is the expected behavior when module decimal is present, while, > when it's absent, you should see something like: > > brain:~/gmpy alex$ GMPY_DEBUG=1 python2.3 -c 'import gmpy' 2>&1 | > tail -5 > Initing new not in zcache > mp_allocate( 4->8 ) > mp_allocate( 4->8 ) ->0x3017d0 > gmpy_module at 0x6de70 > gmpy_module could not import decimal > > In each case, what matters is the last line or two after "gmpy_module > at" -- the rest of the copious debugging output is irrelevant here. > > Module decimal is expected to be present from 2.4 forward (though it > could also be explicitly installed on 2.3). However, from the test > failures you report, it looks like SuSE's 2.4 does not have decimal > available for importing when gmpy is starting up -- so I'd like to > confirm that first. > > If it's confirmed, it will be interesting to discover how this > happens (but that requires a SuSE installation, which I don't have) > and secondarily what is gmpy to do about it -- maybe offer a warning > on startup when module decimal is unexpectedly not importable but > then skip the relevant unittests in that case? (Note that the tests > ARE already skipped if module decimal is not importable _at test > time_ -- what's really weird is that apparently on SuSE decimal CAN > be imported by the tests but CANNOT be imported earlier while gmpy is > loading, which is truly puzzling). > > I'd appreciate reports about this behavior on as many Python/Linux > installations as possible -- yours, of course (to check my guess that > the problem is that decimal can't be imported while gmpy is loading), > but also others' (to see how widespread the problem is, etc, etc). > > Thanks again for reporting this, and thanks in advance to anybody > who'll lend a hand in tracking down this little strangeness!!! Okay, here is a summary. The notation is: platform version python version debug unittest where debug will be either 'pass' or 'fail' if that particular platform and python version passes or fails the GMPY_DEBUG=1 importing/tweaking test. Unittest will also be 'pass' or 'fail' if the full unittesting passes or fails respectively. Fedora 3 python 2.5 pass pass Fedora 3 python 2.4 pass fail Fedora 3 python 2.3.4 fail pass Suse 9.3 python 2.4 pass fail Suse 10 python 2.4.1 pass pass Suse 10.2(64bit) python 2.5 pass fail The output from each test is zipped and you can grab it from here: http://lorentz.leidenuniv.nl/~nogradi/gmpy_test.zip HTH, Daniel From bayer.justin at googlemail.com Mon Feb 26 09:08:03 2007 From: bayer.justin at googlemail.com (bayer.justin at googlemail.com) Date: 26 Feb 2007 06:08:03 -0800 Subject: a=b change b a==b true?? In-Reply-To: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> References: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> Message-ID: <1172498883.061877.123340@k78g2000cwa.googlegroups.com> If you want to copy lists, you do it by using the [:] operator. e.g.: >>> a = [1,2] >>> b = a[:] >>> a [1, 2] >>> b [1, 2] >>> b[0] = 2 >>> a [1, 2] >>> b [2, 2] If you want to copy a list of lists, you can use a list comprehension if you do not want to use the copy module: >>> a = [[1,2],[3,4]] >>> b = [i[:] for i in a] >>> a [[1, 2], [3, 4]] >>> b [[1, 2], [3, 4]] >>> b[0][0] = "foo" >>> a [[1, 2], [3, 4]] >>> b [['foo', 2], [3, 4]] From troy.melhase at gmail.com Wed Feb 28 05:39:34 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Wed, 28 Feb 2007 01:39:34 -0900 Subject: Installing java2python (Newbie) In-Reply-To: <1172657553.589543.176850@v33g2000cwv.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172654566.960775.66080@j27g2000cwj.googlegroups.com> <1172657553.589543.176850@v33g2000cwv.googlegroups.com> Message-ID: > Did you think I was suggesting that you write a GUI version of > java2python? Please carefully (re)?read the documentation link that I > gave you. The idea is that with a simple variation of your setup.py > build comamnd, you create a Windows installer for your existing > package, and make it available for download. Then, all the Windows > user has to do is to double-click on it, and it guides them through > the installation. This would save wear'n'tear on you having to try to > explain to some newbie Windows user how to install your package. You're right, and what I didn't communicate was the thought process that was between "users need an installer" and "users need a gui". I jumped to the end and only typed that. Sorry for any confusion. From tiedon_jano at hotmail.com Tue Feb 27 11:25:20 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 27 Feb 2007 16:25:20 GMT Subject: How to use cmp() function to compare 2 files? In-Reply-To: <1172590629.400500.192670@q2g2000cwa.googlegroups.com> References: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> <1172550136.069527.103600@t69g2000cwt.googlegroups.com> <1172551987.182502.94000@p10g2000cwp.googlegroups.com> <1172553141.665287.65280@8g2000cwh.googlegroups.com> <1172590629.400500.192670@q2g2000cwa.googlegroups.com> Message-ID: samuel.y.l.cheung at gmail.com kirjoitti: > On Feb 27, 12:07 am, Marc 'BlackJack' Rintsch wrote: >> In <1172553141.665287.65... at 8g2000cwh.googlegroups.com>, ying... at gmail.com >> wrote: >> >>> File "./scripts/regressionTest.py", line 30, in getSnapShot >>> if (difflib.context_diff(f1.readlines(), f2.readlines()).len() == >>> 0): >>> # no difference >>> else: >>> # files are different >>> AttributeError: 'generator' object has no attribute 'len' >>> Can you please help? >> The function returns a generator/iterator over the differences which has >> no `len()` method. If you just want to know if two files are equal or not >> use `filecmp.cmp()`. Read the docs about the `shallow` argument of that >> function. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Thanks. I use that before, it does not work for me, since it always > return 1, regardless if the file content of 2 files are different or > not. > > I think you are mixing cmp and filecmp.cmp. They are two different beasts. Cheers, Jussi From nathan.shair at gmail.com Wed Feb 14 17:28:34 2007 From: nathan.shair at gmail.com (nathan.shair at gmail.com) Date: 14 Feb 2007 14:28:34 -0800 Subject: output to console and to multiple files Message-ID: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> Hello, I searched on Google and in this Google Group, but did not find any solution to my problem. I'm looking for a way to output stdout/stderr (from a subprocess or spawn) to screen and to at least two different files. eg. stdout/stderr -> screen stdout -> log.out stderr -> log.err and if possible stdout/stderr -> screen and log.txt 3 files from stdout/stderr From garrickp at gmail.com Wed Feb 14 10:24:45 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 14 Feb 2007 07:24:45 -0800 Subject: threading and multicores, pros and cons In-Reply-To: References: Message-ID: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> On Feb 13, 9:07 pm, Maric Michaud wrote: > I've heard of a bunch of arguments to defend python's choice of GIL, but I'm > not quite sure of their technical background, nor what is really important > and what is not. These discussions often end in a prudent "python has made a > choice among others"... which is not really convincing. Well, INAG (I'm not a Guru), but we recently had training from a Guru. When we brought up this question, his response was fairly simple. Paraphrased for inaccuracy: "Some time back, a group did remove the GIL from the python core, and implemented locks on the core code to make it threadsafe. Well, the problem was that while it worked, the necessary locks it made single threaded code take significantly longer to execute." He then proceeded to show us how to achieve the same effect (multithreading python for use on multi-core computers) using popen2 and stdio pipes. FWIW, ~G From bj_666 at gmx.net Sun Feb 25 04:23:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 25 Feb 2007 10:23:34 +0100 Subject: select which lib for iNet? References: Message-ID: In , Marco wrote: > I wanta know why (Py)Qt has its own lib on socket/ sql/ openGL,etc ? That's simply because Qt has these libraries. If you are programming in C++ this has the advantage that the application is platform independent if you write against the Qt APIs. As Python also has APIs for such things that work cross platform it might be better to use those, because you can separate GUI and logic better. It's hard to replace the Qt libraries with a Gtk, wxPython or web GUI if you still need Qt for networking or database access. Ciao, Marc 'BlackJack' Rintsch From gagsl-py at yahoo.com.ar Wed Feb 14 00:32:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 02:32:46 -0300 Subject: Is python2.5's Tix wrapper broken? References: Message-ID: En Tue, 13 Feb 2007 22:10:54 -0300, Ron Provost escribi?: > Under Python2.5, the empty root window is displayed but I also get a > Traceback: > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\lib-tk\Tix.py", line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix It's a bug, already reported: http://www.python.org/sf/1568240 -- Gabriel Genellina From zawrotny at sb.fsu.edu Tue Feb 27 08:13:07 2007 From: zawrotny at sb.fsu.edu (Michael Zawrotny) Date: 27 Feb 2007 13:13:07 GMT Subject: Curses sorely lacking an event loop? References: Message-ID: On Tue, 27 Feb 2007 12:27:17 GMT, James Stroud wrote: > > Is curses really lacking an event loop? Do I have to write my own? I > infer from the docs that this is the case. For example, I want the > screen to be updated with resize but I find myself waiting for getch() > if I want user input, and so the screen must remain ugly until the user > presses a key. What am I missing? I'm not a curses expert, but I can answer this part. When the screen is resized, SIGWINCH is sent to the process. You can use the normal signal handling apparatus to install a handler that updates the screen when that signal arrives. Mike -- Michael Zawrotny Institute of Molecular Biophysics Florida State University | email: zawrotny at sb.fsu.edu Tallahassee, FL 32306-4380 | phone: (850) 644-0069 From rrr at ronadam.com Sun Feb 4 15:10:35 2007 From: rrr at ronadam.com (Ron Adam) Date: Sun, 04 Feb 2007 14:10:35 -0600 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: <6eb8$45c5b41a$d443bb3a$2475@news.speedlinq.nl> References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> <87tzy2utjl.fsf@smsnet.pl> <6eb8$45c5b41a$d443bb3a$2475@news.speedlinq.nl> Message-ID: Stef Mientki wrote: >> Do you mean something like that? >> >>>>> import some_module >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: No module named some_module >>>>> import sys >>>>> sys.path.append("..") >>>>> import some_module > Rob, > thank you very much, > that's exactly what I want. > (Why is the obvious so often invisible to me ;-) > > cheers, > Stef Mientki Just a note, If you run the module from different location, it may not always work. The '..' is relative to the location you are running the module from, the current directory, and not relative to the location of the module is at. It won't be a problem for you if you can be sure the module is always ran from the location it is at. Cheers, Ron From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 15:45:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 21:45:52 +0100 Subject: Question about a single underscore. In-Reply-To: References: Message-ID: <45c24a89$0$19929$426a74cc@news.free.fr> Steven W. Orr a ?crit : > I saw this and tried to use it: > > ------------------><8------------------- const.py------------- > class _const: > class ConstError(TypeError): pass > def __setattr__(self,name,value): > if self.__dict__.has_key(name): > raise self.ConstError, "Can't rebind const(%s)"%name > self.__dict__[name]=value > > import sys > sys.modules[__name__]=_const() > ------------------><8------------------- const.py------------- > > Then when I go to try to use it I'm supposed to say: > > const.pi = 3.14159 > const.e = 2.7178 > > > Two questions: > > 1. Why do I not have to say > > _const.pi = 3.14159 > _const.e = 2.7178 Because of the last two lines of module const. sys.modules is a dict of already imported modules (yes, Python's modules are objects too), which avoids modules being imported twice or more. __name__ is a magic variable that is set either to the name of the module - when it's imported - or to '__main__' - when it's being directly executed as the main program. Here, when you first do 'import const', the module's code itself sets sys.modules['const'] to an instance of _const, so what you import in your namespace as 'const' is not the const module instance but a _const instance. > and is this in the tutorial? Hmmm... Not sure. FWIW, it's mostly a hack !-) > 2. Can I make this behave in such a way that I can create my constants > with a classname s/classname/name/ > that is different for different uses? e.g., > > irrational_const.pi = 3.14159 > irrational_const.e = 2.7178 > > even_const.first = 2 > even_const.firstPlus = 4 irrational_const = const.__class__() even_const = const.__class__() Now while I find this hack interesting, it's also totally unpythonic IMHO. The usual convention is to use ALL_UPPER names for (pseudo) symbolic constants, and I don't see any reason to forcefit B&D languages concepts into Python. My 2 cents... From lbates at websafe.com Tue Feb 27 18:30:34 2007 From: lbates at websafe.com (Larry Bates) Date: Tue, 27 Feb 2007 17:30:34 -0600 Subject: import parent In-Reply-To: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> References: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> Message-ID: Greg Hoover wrote: > How does one get access to the class that imported a module. For example: > foo imports bar -- how does bar access foo? > > Thanks. > I think we are having a problem understanding what you are asking. If you mean an instance of class foo contains an instance of class bar how would bar reference attributes or other data in foo then I think I'll tackle that one. The best way I've seen is the way that wxWindows does it. class bar: def __init__(self, parent) self.parent=parent def somemethod(self): print self.parent.somelist class foo: def __init__(self): self.somelist=['a','b','c'] self.bars=[] self.bars.append(bar(self)) At least that's the way I understand it and it seems to work. If this isn't what you are asking just disregard. -Larry From ah at hatzis.de Wed Feb 7 15:03:31 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Wed, 07 Feb 2007 21:03:31 +0100 Subject: distutils: renaming setup.py ok? In-Reply-To: References: Message-ID: <45CA3093.1000508@hatzis.de> Hello Benjamin Niemann wrote: > Hello, > > Anastasios Hatzis wrote: > >> I want to distribute Python site-packages. Is it okay to use other setup >> file names than setup.py, which is mentioned in any place I read in the >> doc? >> >> E.g., setupMySDK.py, setupMyLib.py >> >> It seems that it works with distutils at least - but probably doing so >> has side-effects with other tools which may expect exactly "setup.py" as >> file name. > > I'd say, it's mostly the user who is expecting "setup.py" as the filename. > > Perhaps 'setup.py --install-sdk' and 'setup.py --install-lib' would be more > approriate (which can be done with distutils). > Thank you for this hint. I think it will help. Regards, Anastasios From rshepard at nospam.appl-ecosys.com Tue Feb 27 20:47:22 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 28 Feb 2007 01:47:22 GMT Subject: Tuples from List References: Message-ID: On 2007-02-28, Robert Kern wrote: > No, that's a numpy array. Robert, That's where I went off. I forgot that I'm still dealing with a 1D NumPy array and not a list. No wonder I had such fits! > Those aren't tuples, but complex numbers. I have not seen the 'j' suffix before. That was throwing me. > # Extract the real components (since the imaginary components are all 0): > eigvals = eigvals.real That's so much easier than what I ended up doing, which was creating another variable and assigning to that an explicit cast to real of the array. > # Normalize the eigenvalues: > eigvals /= eigvals.sum() Now that's really nice! Thank you very much for today's lessons. I really appreciate them Rich From pavlovevidence at gmail.com Wed Feb 7 10:17:40 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 7 Feb 2007 07:17:40 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: References: <45C9A137.8090009@v.loewis.de> Message-ID: <1170861460.614883.108310@k78g2000cwa.googlegroups.com> On Feb 7, 8:51 am, Thomas Heller wrote: > Martin v. L?wis schrieb: > > > I'm happy to announce partial 1.0; a module to implement > > partial classes in Python. It is available from > > >http://cheeseshop.python.org/pypi/partial/1.0 > > > A partial class is a fragment of a class definition; > > partial classes allow to spread the definition of > > a class over several modules. One location serves > > as the original definition of the class. > > > To extend a class original_module.FullClass with > > an additional function, one writes > > > from partial import * > > import original_module > > > class ExtendedClass(partial, original_module.FullClass): > > def additional_method(self, args): > > body > > more_methods > > > This module is licensed under the Academic Free License v3.0. > > > Please send comments and feedback to mar... at v.loewis.de > > Nice idea. Indeed. I was going to make a post asking for advice on high-level delegation (basically you have a generic mostly-OO framework, which the user extends mostly by subclassing, but how do the generic classes know about the user-extened classes?). I knew of many solutions, but all had significant drawbacks. But this seems like it'd work great, maybe with a few minor inconveniences but nothing like the icky hacks I've been using. Ironic, since I myself posted a very simple example of how to do this with a class hook here on c.l.python a while back. But I'll have to review the license and see how it works with what I have. Carl Banks From martin at v.loewis.de Thu Feb 22 12:58:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 22 Feb 2007 18:58:57 +0100 Subject: when will python 2.5 take in mainstream? In-Reply-To: <7xtzy0wp83.fsf@ruckus.brouhaha.com> References: <7xtzy0wp83.fsf@ruckus.brouhaha.com> Message-ID: <45DDD9E1.6010809@v.loewis.de> Paul Rubin schrieb: > Laurent Pointal writes: >> IMHO trying to have a binary compatibility with older compiled modules >> by maintaining an ad-hoc layer to switch between 2.4/2.5 engines make >> Python code more complex. And more complex code have generally more >> bugs. This is the reason for my KISS hope about Python. > > I haven't heard of other languages that seriously try to do that, > though maybe some do. Languages typically achieve this by specifying an ABI (in addition to the API), and then sticking to that. The most prominent example is the language C, where you normally can upgrade the C library on most current systems without having to recompile all applications. Today, there is machinery to still allow evolution of the C library. E.g. on Linux, there really is a layer in the C library to provide binary compatibility with earlier versions. Another example is Java and JNI, which is an interface that just won't change (AFAIK). Similar to Python, Tcl has a layer of function pointers that is designed to be version-indepdendent - whether this actually works, I don't know. There are many more examples. Regards, Martin From grante at visi.com Sun Feb 25 21:06:04 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 26 Feb 2007 02:06:04 -0000 Subject: getting terminal display size? References: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> Message-ID: <12u4g4ci5gqu46c@corp.supernews.com> On 2007-02-26, jeff wrote: > I looked around a lot on the internet and couldn't find out how to do > this, how do I get the sizer (in rows and columns) of the view? You use the TIOCGWINSZ ioctl() call on the tty device in question. import termios, fcntl, struct, sys s = struct.pack("HHHH", 0, 0, 0, 0) fd_stdout = sys.stdout.fileno() x = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s) print '(rows, cols, x pixels, y pixels) =', print struct.unpack("HHHH", x) -- Grant Edwards grante at visi.com From silverbeach06 at gmail.com Sun Feb 11 23:46:51 2007 From: silverbeach06 at gmail.com (susan) Date: 11 Feb 2007 20:46:51 -0800 Subject: No module named pyExcelerator Error In-Reply-To: <1171242994.102776.69730@s48g2000cws.googlegroups.com> References: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> <1171242994.102776.69730@s48g2000cws.googlegroups.com> Message-ID: <1171255611.853011.118970@s48g2000cws.googlegroups.com> On Feb 11, 8:16 pm, "John Machin" wrote: > On Feb 12, 11:55 am, "susan" wrote: > > > Hi, > > I'm new of Python, and this problem stucked me whole day but can't be > > solved. > > > I use python 2.4.3, which is download from cygwin packages. > > Is your Python installation working properly for you with other > things, or is installingpyExceleratorthe first thing that you have > tried? > > > Then I > > downloadedpyexcelerator-0.5.3a, unzip it, > > Is that "5" a typo? The latest version is 0.6.3a > > > > > $ python ./pyExcelerator/setup.py install > > Try this instead: > $ cdpyExcelerator > $ python ./setup.py install > > i.e. do what thepyExceleratorREADME tells you to do. > """ > 0x0003. Installation. > -------------------- > As usually: python ./setup.py install > """ > This may make a positive difference; it can't be worse. > > HTH, > John Dear John, Thank you so much! I tried as you said, finally it works. You are right, the version should be 0.6.3a. I still wonder why my way didn't work. I think maybe there's some hard code of installation directory, hence, installation won't be succesful if the directory is not exactly the same as the one in README. cheers, From bj_666 at gmx.net Sat Feb 17 04:23:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 17 Feb 2007 10:23:21 +0100 Subject: WHAT IS THIS? References: Message-ID: In , Shadab Sayani wrote: > --- Captain wrote: > >> Just bought a new PC with Windows XP Media Edition. I gather Python is >> a programming language, but I am wondering why it was installed on my >> PC, and is it safe to remove it? I have no intention of learning the >> program. Thanks in advance > > I think it is safe to remove it.As far as I know no windows OS core > programs use python But there must be a reason why the vendor installed Python. So removing it might break any service program preinstalled by the vendor of that machine. A good advice about installing an uninstalling software is: If you don't know what it does and? 1. ?it is not installed then don't install it. 2. ?it is installed then don't uninstall it. Or things may break. Ciao, Marc 'BlackJack' Rintsch From dudaraster at gmail.com Wed Feb 28 14:45:20 2007 From: dudaraster at gmail.com (Aviroce) Date: 28 Feb 2007 11:45:20 -0800 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** In-Reply-To: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> References: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Message-ID: <1172691920.663009.111260@j27g2000cwj.googlegroups.com> On Feb 24, 11:22 am, stj... at rock.com wrote: > Canada anti-terror law is struck down>From the Associated Press > > February 24, 2007 > > OTTAWA - Canada's Supreme Court on Friday unanimously declared it > unconstitutional to detain foreign terrorism suspects indefinitely > while the courts review their deportation orders. > > Five Arab Muslim men have been held for years under the "security > certificate" program, which the Justice Department has said is a key > tool in the fight against global terrorism and essential to Canada's > security. > > The court found that the system violated the Charter of Rights and > Freedoms, Canada's bill of rights. However, it suspended its ruling > for a year to give Parliament time to rewrite the part of the > Immigration and Refugee Protection Act that covers the certificate > process. > > The security certificates were challenged by three men from Morocco, > Syria and Algeria - all alleged by the Canadian Security Intelligence > Service to have ties to terrorist networks. > > The men have spent years in jail while fighting deportation orders. > > They risk being labeled terrorists and sent back to their native > countries, where they say they could face torture. > > The court said the treatment of the suspects was a violation of their > rights. > > "The overarching principle of fundamental justice that applies here is > this: Before the state can detain people for significant periods of > time, it must accord them a fair judicial process," Chief Justice > Beverley McLachlin wrote in a ruling for all nine justices. > > "The secrecy required by the scheme denies the person named in a > certificate the opportunity to know the case put against him or her, > and hence to challenge the government's case," she said. > > The challenged law allows sensitive intelligence to be heard behind > closed doors by a federal judge, with only sketchy summaries given to > defense attorneys. > > The court said the men and their lawyers should have a right to > respond to the evidence used against them by intelligence agents. > > Stockwell Day, the minister of public safety, noted that because the > ruling does not take effect for a year, the certificates would remain > in place. He said the government would address the court's ruling "in > a timely and decisive fashion." > > Two of the men are out on bail and remain under house arrest. Three > others are being held in a federal facility in Ontario. <<<<<<<<<<<"The court said the treatment of the suspects was a violation of their rights. "The overarching principle of fundamental justice that applies here is this: Before the state can detain people for significant periods of time, it must accord them a fair judicial process," Chief Justice Beverley McLachlin wrote in a ruling for all nine justices. "The secrecy required by the scheme denies the person named in a certificate the opportunity to know the case put against him or her, and hence to challenge the government's case," she said. ">>>>>>>>>>>>>>>> THAT IS CALLED PROTECTING CIVIL RIGHTS. IN THE UNITED STATES OF AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE NOT PROTECTED BY THE GENEVA CONVENTION. DR. EVIL, V.P. CHENEY, AND MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION. THIS MEANS ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO. WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER. From steve at REMOVE.THIS.cybersource.com.au Tue Feb 20 08:22:20 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 00:22:20 +1100 Subject: file io (lagged values) newbie question References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> Message-ID: On Mon, 19 Feb 2007 22:17:42 -0800, hiro wrote: > Hey there, I'm currently doing data preprocessing (generating lagged > values for a time series) and I'm having some difficulties trying to > write a file to disk. A friend of mine, wrote this quick example for > me: If that's a quick example (well over 100 lines), I'd hate to see your idea of a long example. Can you cut out all the irrelevant cruft and just show: (1) the actual error you are getting (2) the SMALLEST amount of code that demonstrates the error Try to isolate if the problem is in *writing* the file or *generating* the time series. Hint: instead of one great big lump of code doing everything, write AT LEAST two functions: one to read values from a file and generate a time series, and a second to write it to a file. That exercise will probably help you discover what the problem is, and even if it doesn't, you'll have narrowed it down from one great big lump of code to a small function. To get you started, here's my idea for the second function: (warning: untested) def write_series(data, f): """Write a time series data to file f. data should be a list of integers. f should be an already opened file-like object. """ # Convert data into a string for writing. s = str(data) s = s[1:-1] # strip the leading and trailing [] delimiters s = s.replace(',', '') # delete the commas # Now write it to the file object f.write(s) f.write('\n') And this is how you would use it: f = file('myfile.txt', 'w') # get some time series data somehow... data = [1, 2, 3, 4, 5] # or something else write_series(data, f) # get some more data data = [2, 3, 4, 5, 6] write_series(data, f) # and now we're done f.close() Hope this helps. -- Steven. From paddy3118 at googlemail.com Sun Feb 25 15:41:35 2007 From: paddy3118 at googlemail.com (Paddy) Date: 25 Feb 2007 12:41:35 -0800 Subject: Referencing Items in a List of Tuples In-Reply-To: References: <1172424046.323933.85250@q2g2000cwa.googlegroups.com> Message-ID: <1172436095.476848.14430@z35g2000cwz.googlegroups.com> On Feb 25, 5:44 pm, Jussi Salmela wrote: > Paddy kirjoitti: > > > > > On Feb 25, 2:01 am, rshep... at nospam.appl-ecosys.com wrote: > >> While working with lists of tuples is probably very common, none of my > >> five Python books or a Google search tell me how to refer to specific items > >> in each tuple. I find references to sorting a list of tuples, but not > >> extracting tuples based on their content. > > >> In my case, I have a list of 9 tuples. Each tuple has 30 items. The first > >> two items are 3-character strings, the remaining 28 itmes are floats. > > >> I want to create a new list from each tuple. But, I want the selection of > >> tuples, and their assignment to the new list, to be based on the values of > >> the first two items in each tuple. > > >> If I try, for example, writing: > > >> for item in mainlist: > >> if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': > >> ec.Append(mainlist[item][2:]) > > >> python doesn't like a non-numeric index. > > >> I would really appreciate a pointer so I can learn how to manipulate lists > >> of tuples by referencing specific items in each tuple (string or float). > > >> Rich > > > You might also use list comprehensions to accumulate the values you > > need: > > > ec = [ item[2:] for item in mainlist if item[:2] == ['eco','con'] ] > > > - Paddy. > > I'm nitpicking, but the OP has a list of tuples: > > ec = [ item[2:] for item in mainlist if item[:2] == ('eco','con') ] > > Cheers, > Jussi Of course. Ta. - paddy. From grante at visi.com Wed Feb 21 22:52:31 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 22 Feb 2007 03:52:31 -0000 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172103048.160783.309470@l53g2000cwa.googlegroups.com> Message-ID: <12tq4rvmb0ke0a4@corp.supernews.com> On 2007-02-22, Ganesan Rajagopal wrote: >> I am hoping to have it show up some weird un-readable text. >> And then of course be able to convert it right back to a >> string. Is this even possible? > > Looks like you just want to obfuscate the string. How about > this? > > import base64 > text = 'supercalifragilisticexpialidocius' > open('sambleb.conf', 'w').write(base64.encodestring(text)) > > print base64.decodestring(open('sambleb.conf', 'r').read()) It'll only remain obfuscated for about 30 seconds after even a mildly curious user looks at the file. -- Grant Edwards grante Yow! INSIDE, I have the at same personality disorder visi.com as LUCY RICARDO!! From naima.mans at gmail.com Wed Feb 28 12:00:17 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 28 Feb 2007 09:00:17 -0800 Subject: spawnl and waitpid In-Reply-To: <1172658208.202787.195510@j27g2000cwj.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> <1172600050.794986.47140@m58g2000cwm.googlegroups.com> <1172658208.202787.195510@j27g2000cwj.googlegroups.com> Message-ID: <1172682013.565315.116390@h3g2000cwc.googlegroups.com> On 28 f?v, 11:23, naima.m... at gmail.com wrote: > On 27 f?v, 19:32, Thinker wrote: > > > > > > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > naima.m... at gmail.com wrote: > > > On 27 f?, 18:54, Thinker wrote: > > > hello > > > ha ok... > > > i tried this one and the browser don't write the message at once... > > > I have alos tried with thread and have the same result... :( > > > Does child-process terminate it-self in a very short time ? > > It can be a race condition, here. > > You can try to sleep for a while in child-process to make sure parent > > being executed. Parent process may not schedule to run immediately > > after spawn. And, you can print some thing before os.spawnl() to make > > sure that message can be delivered successfully. > > > - -- > > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > > -----BEGIN PGP SIGNATURE----- > > Version: GnuPG v1.4.6 (FreeBSD) > > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > > iD8DBQFF5Hkp1LDUVnWfY8gRAtDdAKCKy8/ap5VJvZV14nhSCWYfLZdyYACffJ+Y > > 0sHMgyaQBmsOMwq/rxEvm1Q= > > =qjTU > > -----END PGP SIGNATURE----- > > hello > > oki, i have test a simple script that only wait... > when i tun the script without the server it write on 2 time which is > normal: > ================================================ > Content-Type: text/html > wait > The main program continues to run in foreground. > [[[[(((then after 5 second ))]]]]]]] > Fin background > Main program waited until background was done. > ================================================== > > BUT when i call it under the server web it write after 5 second all > the message in 1 time : > =================================================== > wait The main program continues to run in foreground. Fin background > Main program waited until background was done. > =================================================== > > -----------------------THE SCRIPT --------------------------- > import cgitb; cgitb.enable() > import os,sys > import threading, zipfile,time,Main > > print "Content-Type: text/html" > print > print "wait" > sys.stdout.flush() > > class AsyncZip(threading.Thread): > ? ? def __init__(self, infile): > ? ? ? ? threading.Thread.__init__(self) > ? ? ? ? self.infile = infile > ? ? def run(self): > ? ? ? ? time.sleep(5.0) > ? ? ? ? print 'Fin background' > > background = AsyncZip('Main.py') > background.start() > print 'The main program continues to run in foreground.' > sys.stdout.flush() > background.join() ? ?# Wait for background task to finish > print 'Main program waited until background was done.' > sys.stdout.flush() > ---------------------------------------------------------------- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - hello The pb seems to be solve but no idee why as i have done lot of changes :/ (may be the last flush or the "\n".. i'm gone investigate..) THANKSSSSSSSSSSSSSSSSS for helping :) for information here the code ---------------------------------------------------------- #! C:/Python25/python.exe -u # -*- coding: cp1252 -*- import cgitb; cgitb.enable() import os, commands, time,Parser,config import cgi import sys,Function sys.stderr = sys.stdout print "Content-Type: text/html" print pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python","Main.py") print "please wait...\n" print """Le fichier de log est consultable sur \\\\fr9033256d \execute\%s \n""" %config.nom_log sys.stdout.flush() ret = os.waitpid(pid,0) if ret[1]: print "Non-zero exit code: %s %s" % (ret[1], ret[0]) else: print "Successful exit" sys.stdout.flush() From systemguards at gmail.com Tue Feb 20 22:39:19 2007 From: systemguards at gmail.com (Jaime Casanova) Date: Tue, 20 Feb 2007 22:39:19 -0500 Subject: outlook bar like widget Message-ID: Hi, i'm trying to make an outlook bar like widget basically buttons that when pressed extends to lists... any idea where to start? -- regards, Jaime Casanova "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs and the universe trying to produce bigger and better idiots. So far, the universe is winning." Richard Cook From miki.tebeka at gmail.com Wed Feb 21 12:52:11 2007 From: miki.tebeka at gmail.com (Miki) Date: 21 Feb 2007 09:52:11 -0800 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: References: Message-ID: <1172080331.451996.76980@t69g2000cwt.googlegroups.com> Hello Joanne, > ... [float problem] ... > I get True returned. Can anyone tell me whats going on and how I can > avoid the problem. Thanks If you want to be truly accurate, you can use gmpy.mpq (http:// gmpy.sourceforge.net/). >>> a = [0.2, 0.2, 0.2, 0.1, 0.2, 0.1] >>> b = [0.2, 0.2, 0.2, 0.2, 0.1, 0.1] >>> qa = [gmpy.mpq(int(i * 10), 10) for i in a] >>> qb = [gmpy.mpq(int(i * 10), 10) for i in b] >>> sum(qa) mpq(1) >>> sum(qb) mpq(1) >>> sum(qa) == sum(qb) True HTH, -- Miki http://pythonwise.blogspot.com From rintaromasuda at gmail.com Sun Feb 18 23:02:35 2007 From: rintaromasuda at gmail.com (Rintaro Masuda) Date: Mon, 19 Feb 2007 13:02:35 +0900 Subject: What is more efficient? In-Reply-To: References: Message-ID: Hi Karlo, Now if I have hundreds of thousands (or even more) of instances of that > class - is it more efficient to remove those methods and make them > separate functions, or it doesn't matter? I can't get your idea from your text. Could you give us an example? Thanks... > > -- > _______ Karlo Lozovina - Mosor > | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 > | || _ | _ | Parce mihi domine quia Dalmata sum. > |__|_|__||_____|_____| > -- > http://mail.python.org/mailman/listinfo/python-list > -- Rintaro Masuda rintaromasuda at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kirk at nospam.jobsluder.net Sat Feb 10 23:26:07 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Sun, 11 Feb 2007 04:26:07 GMT Subject: Best Free and Open Source Python IDE References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> <1171047698.558376.160500@v33g2000cwv.googlegroups.com> <6fd78$45ccd1c1$d443bb3a$15713@news.speedlinq.nl> Message-ID: In article <6fd78$45ccd1c1$d443bb3a$15713 at news.speedlinq.nl>, Stef Mientki wrote: > Which brings me to some other questions on waste: > - isn't it a pitty so many people are involved in writing another editor / > IDE ? I don't know about that. Most of the new editor development appears to involve one of the following: 1: Taking advantage of a specific graphical toolkit or interface, such as KDE, Gnome, Cocoa, MS Foundation, SWING, and terminals. 2: Building around a specific language for macro and script programming. 3: Adding features that are useful for specific development models. Web/HTML authoring requires upload tools, C/C++ requires make, Java might use Ant, lisp and python can use shells. > - isn't it a waste for newbies to evaluate a dozen editors / IDE's ? I think that in many cases, the choices are constrained to two or three depending on what the _newbie_ wants to do, and what Desktop Environment they use. For general editors on OS X, I'd suggest Smultron, or TextWrangler. For KDE, kick the tires on Kate a bit. Cross-platform and portable? jEdit. Text consoles? Emacs, vim or jed. And if the newbie has some specific itch that needs to be scratched, there again the choices usually boil down to two or three best of breed IDEs, many of which are segregated by platform. > just some thoughts, > of a some months old newbie, > Stef Mientki From no at nospam.com Sat Feb 10 17:19:04 2007 From: no at nospam.com (icester) Date: Sat, 10 Feb 2007 23:19:04 +0100 Subject: Stereo 3D photography capture stereoscopic still and motion images Message-ID: http://www.tyrell-innovations-usa.com/shack3d/productinfo/jpsBrown/jpsBrownInfo.htm http://tyrell-innovations-usa.com/shack3d/ From vithi99 at hotmail.com Thu Feb 1 20:22:54 2007 From: vithi99 at hotmail.com (vithi) Date: 1 Feb 2007 17:22:54 -0800 Subject: win32com.client In-Reply-To: References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> Message-ID: <1170379374.589869.158610@p10g2000cwp.googlegroups.com> On Jan 31, 6:35 pm, rzed wrote: > "vithi" wrote innews:1170278964.738118.219600 at k78g2000cwa.googlegroups.com: > > > Hi > > Any one tell me where I can get (or download) python modules > > win32com or win32com.client because I have to use "Dispatch" > > thanks > > What distribution are you using? If you are using Windows and have > downloaded the Python.org one, then, as Gary has told you: > "You want the "python for windows" extension, available from http://sourceforge.net/projects/pywin32/" > > I think the ActiveState distro includes it as part of its package. > > I don't know if any of this applies if you are using Linux, VMS, etc. > > -- > rzed From Matthew.Cahn at gmail.com Wed Feb 21 10:43:06 2007 From: Matthew.Cahn at gmail.com (Matthew.Cahn at gmail.com) Date: 21 Feb 2007 07:43:06 -0800 Subject: starship.python.net is down In-Reply-To: <1171634223.13643@sj-nntpcache-2.cisco.com> References: <1171634223.13643@sj-nntpcache-2.cisco.com> Message-ID: <1172072586.601115.304110@s48g2000cws.googlegroups.com> Hi, Any news on starship.python.net? It still seems to be down. Matthew On Feb 16, 8:57 am, Tom Bryan wrote: > One of the system administrators had to reboot starship.python.net last > night, but it appears that the machine did not come back up properly. > starship.python.net is currently down while we investigate. > > ---Tom From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 18:01:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 00:01:12 +0100 Subject: Parameter lists In-Reply-To: References: Message-ID: <45c7b021$0$21550$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Sun, 04 Feb 2007 17:45:04 +0100, Mizipzor wrote: > > >>Consider the following snippet of code: >> >>class Stats: >> def __init__(self, speed, maxHp, armor, strength, attackSpeed, imagePath): >> self.speed = speed >> self.maxHp = maxHp >> self.armor = armor >> self.strength = strength >> self.attackSpeed = attackSpeed >> self.originalImage = loadTexture(imagePath) >> >> >>I little container for holding the stats for some rpg character or >>something. Now, I dont like the looks of that code, there are many >>function parameters to be sent in and if I were to add an attribute, i >>would need to add it in three places. Add it to the function >>parameters, add it to the class and assign it. >> >>Is there a smoother way to do this? There usually is in python, hehe. > > (snip) > > def __init__(self, **kwargs): > for key in kwargs: > if hasattr(self, key): > # key clashes with an existing method or attribute > raise ValueError("Attribute clash for '%s'" % key) > self.__dict__.update(kwargs) > > > === Advantages === > (snip) > > === Disadvantages === > (snip) > (2) Typos can cause strange bugs which are hard to find: > > Stats(armour="chainmail", stealth=2, stregnth=4, ...) > > Now your character is unexpectedly strong because it inherits the default, > and you don't know why. > (3) Easy to break your class functionality: > > Stats(name_that_clashes_with_a_method="something else", ...) > How to overcome these two problem - just overcomplexifying things a bit: class StatsAttribute(object): def __init__(self, default=None): self._default = default self._attrname = None # set by the StatType metaclass def __get__(self, instance, cls): if instance is None: return self return instance._stats.get(self._attrname, self._default) def __set__(self, instance, value): instance._stats[self._attrname] = value class StatsType(type): def __init__(cls, name, bases, attribs): super(StatsType, cls).__init__(name, bases, attribs) statskeys = getattr(cls, '_statskeys', set()) for name, attrib in attribs.items(): if isinstance(attrib, StatsAttribute): # sets the name to be used to get/set # values in the instance's _stats dict. attrib._attrname = name # and store it so we know this is # an expected attribute name statskeys.add(name) cls._statskeys = statskeys class Stats(object): __metaclass__ = StatsType def __init__(self, **stats): self._stats = dict() for name, value in stats.items(): if name not in self._statskeys: # fixes disadvantage #2 : we won't have unexpected kw args msg = "%s() got an unexpected keyword argument '%s'" \ % (self.__class__.__name__, name) raise TypeError(msg) setattr(self, name, value) # just a dummy object, I didn't like the # idea of using strings litterals for things # like armors or weapons... And after all, # it's supposed to be overcomplexified, isn't it ? class _dummy(object): def __init__(self, **kw): self._kw = kw def __getattr__(self, name): return self._kw[name] class Leather(_dummy): pass class Sword(_dummy): pass class FullPlate(_dummy): pass class MagicTwoHanded(_dummy): pass # let's go: class Warrior(Stats): # fixes disatvantage 3 : we won't have name clash strength = StatsAttribute(default=12) armour = StatsAttribute(default=Leather()) weapon = StatsAttribute(default=Sword()) bigBill = Warrior( strength=120, armour=FullPlate(), weapon=MagicTwoHanded(bonus=20) ) try: wontDo = Warrior( sex_appeal = None ) except Exception, e: print "got : %s" % e Did I won a MasterProgrammer (or at least a SeasonnedPro) award ?-) http://sunsite.nus.sg/pub/humour/prog-evolve.html Err... me go to bed now... > If you've got lots of attributes, you're better off moving them to > something like a INI file and reading from that: > > class Stats: > defaults = "C:/path/defaults.ini" > def __init__(self, filename=None, **kwargs): > if not filename: > filename = self.__class__.defaults > self.get_defaults(filename) # an exercise for the reader > for key in kwargs: > if not self.__dict__.has_key(key): > raise ValueError("Unknown attribute '%s' given" % key) > self.__dict__.update(kwargs) And then allow for Python source code in the INI file (that will be used to create methods) to specify behaviour ?-) Ok, this time I really go to bed !-) From http Thu Feb 22 17:29:13 2007 From: http (Paul Rubin) Date: 22 Feb 2007 14:29:13 -0800 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Message-ID: <7x4ppdhlmu.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Arrays don't support XOR any more than strings do. What's the advantage to > using the array module if you still have to jump through hoops to get it > to work? It's a lot faster. Sometimes that matters. From yves.delalande at gmail.com Wed Feb 7 07:40:33 2007 From: yves.delalande at gmail.com (yvesd) Date: 7 Feb 2007 04:40:33 -0800 Subject: ps tkinter Message-ID: <1170852030.522393.267140@v33g2000cwv.googlegroups.com> For a bit more help about my previous message (outlook bar) does anybody know how to reparent or change a widget(button)'s owner in tkinter ? here's my code that doesn't work : def inverse(self): if (self.texte=="top"): self.texte="bottom" btn = self btn.pack_forget() btn.configure(parent = self.top, text=self.texte) btn.pack(side=TOP,fill=X,expand=1) else: self.texte="top" btn = self btn.pack_forget() btn.configure(parent=self.bottom, text=self.texte) btn.parent = None btn.pack(side=BOTTOM,fill=X,expand=1) From horpner at yahoo.com Wed Feb 7 08:00:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 7 Feb 2007 14:00:33 +0100 Subject: Vim search under cursor References: <1170846259.673825.26420@a34g2000cwb.googlegroups.com> Message-ID: On 2007-02-07, jm.suresh at no.spam.gmail.com wrote: > Hi, I am using gvim to edit python source files. When I press "*" or > "#", I would want to search for the attribute name under the cursor > and not the entire string. > For example, If I have os.error and pressing * on top of error > searches for os.error rather than error. How to set this, any Idea? It's will to break things, but you can do this by editing the iskeyword string and adding in the '.'. :h 'iskeyword'. -- Neil Cerutti From jstroud at mbi.ucla.edu Fri Feb 16 15:57:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 16 Feb 2007 20:57:42 GMT Subject: Tkinter __call__ In-Reply-To: References: <65gBh.76610$qO4.45156@newssvr13.news.prodigy.net> Message-ID: Gigs_ wrote: > James Stroud wrote: >> Gigs_ wrote: >>> def printit(self, name): >>> print name, 'returns =>', demos[name]() >>> >>> >>> I have tried but cant get it to work properly. >>> I want to instead printit method to put __call__ and call it like that >>> Can someone help me, please? > I understand lambda, and I know that code is working. But want to do for > exercise with __call__. This coed is from programming python 2ed boo You want to use a function factory that itself defines "__call__"? This requires creating a class and not a function. class printit(object): def __init__(self, name): self.name = name def __call__(self): print self.name, 'returns =>', demos[self.name]() class Demo(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack() Label(self, text="Basic demos").pack() for (key, value) in demos.items(): func = printit(key) Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) However, the functional way (as with lambda) is the most widely used way to do this. Another functional way is with closure: def printit(key): def _f(): print key, 'returns =>', demos[key]() return _f Which behaves identically to the class above. Even more ways to do this exist in python, including partial functions--which are also a functional approach. James From duncan.booth at invalid.invalid Wed Feb 7 16:34:26 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Feb 2007 21:34:26 GMT Subject: string.find for case insensitive search References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: "Don Morrison" wrote: > lower() is also deprecated :) oh well > > On 7 Feb 2007 21:06:08 GMT, Duncan Booth > wrote: >> "Johny" wrote: >> >> > Is there a good way how to use string.find function to find a >> > substring if I need to you case insensitive substring? >> >> s.lower().find(substring.lower()) >> No. RTFM and don't top post. The functions such as lower() and find() in the string *module* are deprecated. The methods are what you should use. From jura.grozni at gmail.com Wed Feb 7 20:13:19 2007 From: jura.grozni at gmail.com (azrael) Date: 7 Feb 2007 17:13:19 -0800 Subject: Array delete In-Reply-To: References: <45BC84B6.9080505@riddergarn.dk> Message-ID: <1170897199.005278.259190@p10g2000cwp.googlegroups.com> if you are new to python then this will be easier to understand. if you change this a liitle bit (depending on syntax) it should work in any language. just copy and paste to a .py file def main(): list, temp = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10], [] for i in range(len(list)): if Check(list[i], temp) == 1: temp.append(list[i]) print temp # print the new list where duplicates are removed def Check(listItem,temp): for i in range(len(temp)): if listItem == temp[i]: return 0 return 1 if __name__=="__main__": main() On Feb 7, 10:35 pm, "Jerry Hill" wrote: > On 1/28/07, Scripter47 wrote: > > > Can someone plz make a function for that takes a array, and then search > > in it for duplicates, if it finds 2 or more items thats the same string > > then delete all except 1. > > >>> myList = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10] > >>> myList = list(set(myList)) > >>> print myList > [8, 1, 2, 4, 10] > > Maintaining sort order is left as an exercise for the reader. > > -- > Jerry From duncan.booth at invalid.invalid Sun Feb 25 12:12:55 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Feb 2007 17:12:55 GMT Subject: Are weak refs slower than strong refs? References: Message-ID: John Nagle wrote: > Are weak refs slower than strong refs? I've been considering > making the "parent" links in BeautifulSoup into weak refs, so the > trees will release immediately when they're no longer needed. In > general, all links back towards the root of a tree should be weak > refs; this breaks the loops that give reference counting trouble. Yes, weak references are slower, but that may not be significant unless people are following the parent links a lot: I would expect other processing to make the overhead fairly insignificant. Why not do a few timing tests with some typical use cases? Here's an example which does nothing much but create and follow. Typical output: Using proxy 100 loops, best of 3: 5.6 msec per loop Call to dummy proxy 100 loops, best of 3: 3.11 msec per loop Without proxy call 100 loops, best of 3: 2.71 msec per loop ------ timetest.py -------------------------------------------------------- from timeit import Timer, default_timer as timer from weakref import proxy class C: '''Use a weak proxy (or whatever 'proxy' returns)''' def __init__(self, parent=None): self.parent = proxy(parent) if parent is not None else parent self.child = None def show_parents(self): while self is not None: # print "show_parents", id(self) self = self.parent def show_children(self): while self is not None: # print "show_children", id(self) self = self.child def t1(n): base = C() current = base for i in range(n): current.child = C(current) current = current.child base.show_children() current.show_parents() class D: '''Strong parent reference''' def __init__(self, parent=None): self.parent = parent if parent is not None else parent self.child = None def show_parents(self): while self is not None: # print "show_parents", id(self) self = self.parent def show_children(self): while self is not None: # print "show_children", id(self) self = self.child def t2(n): base = D() current = base for i in range(n): current.child = D(current) current = current.child base.show_children() current.show_parents() def timetest(stmt): repeat = 3 precision = 3 t = Timer(stmt, 'import __main__', timer) # determine number so that 0.2 <= total time < 2.0 for i in range(1, 10): number = 10**i try: x = t.timeit(number) except: t.print_exc() return 1 if x >= 0.2: break try: r = t.repeat(repeat, number) except: t.print_exc() return 1 best = min(r) print "%d loops," % number, usec = best * 1e6 / number if usec < 1000: print "best of %d: %.*g usec per loop" % (repeat, precision, usec) else: msec = usec / 1000 if msec < 1000: print "best of %d: %.*g msec per loop" % (repeat, precision, msec) else: sec = msec / 1000 print "best of %d: %.*g sec per loop" % (repeat, precision, sec) if __name__=='__main__': print "Using proxy" timetest('__main__.t1(1000)') print "Call to dummy proxy" def proxy(x): return x timetest('__main__.t1(1000)') print "Without proxy call" timetest('__main__.t2(1000)') ------------------------------------------------------------------------- From __peter__ at web.de Sat Feb 3 09:20:04 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 15:20:04 +0100 Subject: strange test for None References: <1170510459.804204.311760@v33g2000cwv.googlegroups.com> Message-ID: karoly.kiripolszky wrote: > in my server i use the following piece of code: > > ims = self.headers["if-modified-since"] > if ims != None: > t = int(ims) > > and i'm always getting the following error: > > t = int(ims) > ValueError: invalid literal for int(): None > > i wanna know what the hell is going on... first i tried to test using > is not None, but it makes no difference. > > sorry i forgot, it's interpreter 2.4.4. Instead of the None singleton... >>> int(None) Traceback (most recent call last): File "", line 1, in ? TypeError: int() argument must be a string or a number ...you seem to have the /string/ "None" in your dictionary >>> int("None") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): None While the immediate fix would be if ims != "None": t = int(ims) there is probably an erroneous self.header["if-modified-since"] = str(value) elsewhere in your code that you should replace with if value is not None: self.header["if-modified-since"] = str(value) The quoted portion would then become if "if-modified-since" in self.header: t = int(self.headers["if-modified-since"]) Peter From mau.conte at vodafone.it Wed Feb 28 04:40:21 2007 From: mau.conte at vodafone.it (Konte) Date: Wed, 28 Feb 2007 10:40:21 +0100 Subject: msvcr71.dll Message-ID: Are there news about the impossibility of redistributing msvcr71.dll with own stand-alone application written in python, without having MSVC7 license? From larry.bates at websafe.com Fri Feb 9 17:29:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 09 Feb 2007 16:29:50 -0600 Subject: interacting with shell - another newbie question In-Reply-To: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> References: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> Message-ID: James wrote: > Hello, > > I work in this annoying company where I have to autheticate myself to > the company firewall every 30-50 minutes in order to access the > internet. (I think it's a checkpoint fw). > > I have to run "telnet what.ever.ip.address 259" then it prompts me > with userid, then password, then I have to select "1". Then the > program closes itself and the internet is enabled. > > I would like to automate this process with Python and run it every 30 > miniutes so I don't have to keep typing in these userid/password > everytime. How can this be done? Is there a module I can use to > interact with the shell? (I'm running linux) > > Thank you. > > James > You shouldn't have to work through the shell. Just connect directly via telnetlib. Here is an example that you should be able to modify easily to meet your needs. http://docs.python.org/lib/telnet-example.html -Larry From mfmdevine at gmail.com Wed Feb 14 09:53:04 2007 From: mfmdevine at gmail.com (amadain) Date: 14 Feb 2007 06:53:04 -0800 Subject: multi processes Message-ID: <1171464784.419065.149140@v45g2000cwv.googlegroups.com> Hi Heres a poser. I want to start a program 4 times at exactly the same time (emulating 4 separate users starting up the same program). I am using pexpect to run the program from 4 separate locations accross the network. How do I start the programs running at exactly the same time? I want to time how long it takes each program to complete and to show if any of the program initiations failed. I also want to check for race conditions. The program that I am running is immaterial for this question - it could be mysql running queries on the same database for example. Using threading, you call start() to start each thread but if I call start on each instance in turn I am not starting simultaneously. A From paul at boddie.org.uk Thu Feb 1 11:24:07 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Feb 2007 08:24:07 -0800 Subject: Ubunu - Linux - Unicode - encoding In-Reply-To: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> References: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> Message-ID: <1170347047.711706.48020@a34g2000cwb.googlegroups.com> On 1 Feb, 16:02, Franz Steinhaeusler wrote: > > The case: > I have a file on a WindowsXP partition which has as contents german > umlauts and the filename itself has umlauts like i????k.txt > > If I want to append this file to a list, I get somehow latin-1, cannot > decode 'utf-8'. You mean that you expect the filename in UTF-8, but it arrives as ISO-8859-1 (Latin1)? How do you get the filename? Via Python standard library functions or through a GUI toolkit? What does sys.getfilesystemencoding report? [...] > Why is this setdefaultencoding otherwise not working on linux? My impression was that you absolutely should not change the default encoding. Instead, you should react to encoding information provided by your sources of data. For example, sys.stdin.encoding tells you about the data from standard input. > (Also Filemanagers like Nautilus or Krusader cannot display the files > correctly). This sounds like a locale issue... > Is there a system wide linux language setting (encoding), which I have > to install and adjust? I keep running into this problem when installing various distributions. Generally, the locale needs to agree with the encoding of the filenames in your filesystem, so that if you've written files with UTF-8 filenames, you'll only see them with their proper names if the locale you're using is based on UTF-8 - things like en_GB.utf8 and de_AT.utf8 would be appropriate. Such locales are often optional packages, as I found out very recently, and you may wish to look at the language-pack-XX and language-pack-XX-base packages for Ubuntu (substituting XX for your chosen language). Once they are installed, typing "locale -a" will let you see available locales, and I believe that changing /etc/environment and setting the LANG variable there to one of the available locales may offer some kind of a solution. Another thing I also discovered very recently, after doing a debootstrap installation of Ubuntu, was that various terminals wouldn't reproduce non-ASCII characters without an appropriate (UTF-8) locale being set up, even though other desktop applications were happy to accept and display the characters. I thought this was a keyboard issue, compounded by the exotic nested X server plus User Mode Linux solution I was experimenting with, but I think locales were the main problem. Paul From grante at visi.com Mon Feb 19 21:58:41 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 20 Feb 2007 02:58:41 -0000 Subject: Checking for EOF in stream References: <12tkgeh32duee72@corp.supernews.com> Message-ID: <12tkov17806vf76@corp.supernews.com> On 2007-02-20, GiBo wrote: >>> stream = sys.stdin >>> while True: >>> data = stream.read(1024) >> if len(data) == 0: >> break #EOF >>> process_data(data) > > Right, not a big difference though. Isn't there a cleaner / > more intuitive way? A file is at EOF when read() returns ''. The above is the cleanest, simplest, most direct way to do what you specified. Everybody does it that way, and everybody recognizes what's being done. It's also the "standard, Pythonic" way to do it. > Like using some wrapper objects around the streams or > something? You can do that, but then you're mostly just obfuscating things. -- Grant Edwards grante Yow! Vote for ME at -- I'm well-tapered, visi.com half-cocked, ill-conceived and TAX-DEFERRED! From philippe.dalet at ac-toulouse.fr Sat Feb 17 05:30:25 2007 From: philippe.dalet at ac-toulouse.fr (pdalet) Date: 17 Feb 2007 02:30:25 -0800 Subject: Output to a text window In-Reply-To: <1171671545.951006.160420@k78g2000cwa.googlegroups.com> References: <1171671545.951006.160420@k78g2000cwa.googlegroups.com> Message-ID: <1171708225.480494.224660@l53g2000cwa.googlegroups.com> Hi, http://spinecho.ifrance.com/frmouterr-py242-wxpy2621.zip I use this gui windows written by jean marie fauth, which is very easy: printing to stdout or stderr (gui windows written in wxpython). You have only to translate frmouterr in pygtk. ph DALET FRANCE On 17 f?v, 01:19, goo... at orcon.net.nz wrote: > Hi, > > I'm going around in circles so I'm asking for help. I want to read a > simple text file and output the contents to a GUI window when I click > on a button. I have written a small python program to read the > contents of a file when a button is clicked but can only output this > to a console window. I'm using the pygtk binding with glade for the > gui. > > I know it must be quiet simple but a mental block has rapidly > descended. > > Any help would be appreciated. From deets at nospam.web.de Mon Feb 19 03:11:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Feb 2007 09:11:10 +0100 Subject: How do I create an array of functions? In-Reply-To: References: Message-ID: <53t4deF1tb9pgU1@mid.uni-berlin.de> Steven W. Orr schrieb: > I have a table of integers and each time I look up a value from the > table I want to call a function using the table entry as an index into > an array whose values are the different functions. I haven't seen > anything on how to do this in python. def f(): pass fmap = { key: f } fmap[key]() Diez From nogradi at gmail.com Fri Feb 16 11:30:53 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 16 Feb 2007 17:30:53 +0100 Subject: Approaches of interprocess communication In-Reply-To: <1171631180.776312.258100@v33g2000cwv.googlegroups.com> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <45d5a499$0$5995$b9f67a60@news.newsdemon.com> <1171631180.776312.258100@v33g2000cwv.googlegroups.com> Message-ID: <5f56302b0702160830p78a639feq2fba302adab25e38@mail.gmail.com> > About "Linda": Am I right that it looks very similar to "JavaSpaces"? > If yes, are there any funcdamental differences between those two? Yes, they are both linda implementations, but I have no idea what so ever how they compare. A local java expert maybe? From rupole at hotmail.com Mon Feb 26 13:13:02 2007 From: rupole at hotmail.com (Roger Upole) Date: Mon, 26 Feb 2007 13:13:02 -0500 Subject: NetUseAdd mystery References: <1172508987.854983.162370@j27g2000cwj.googlegroups.com> Message-ID: <1172513667_19595@sp6iad.superfeed.net> king kikapu wrote: > Is anyone see any error in the following code: > > mapDrive = "\\\\MyServer\\C$" > data = {'remote' : mapDrive, 'local' : 'M:', 'password' : > 'mypassword', 'user' : 'Administrator', 'asg_type' : 0} > win32net.NetUseAdd(None, 1, data) > > It gives me "pywintypes.error: (1326, 'NetUseAdd', 'Logon failure: > unknown user name or bad password.')" and i cannot figured out why...I > searched the forum about the syntax of NetUseAdd command and i think > that the syntax is correct and also are the data that i pass to it. > (the same data can give me a connection if i use "net use ..." from a > command line" > > So, what am i doing the wrong way (and keeps me on this the last 2 > hours??...) > > > Thanks for a any enlightenment... You need to use level 2 info to pass the username. Level 1 is for the old-style share with its own password. Also, it should be 'username': instead of just 'user':. hth Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-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 jura.grozni at gmail.com Thu Feb 8 09:44:22 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 06:44:22 -0800 Subject: python linux distro Message-ID: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Hy guys last night i was lying in my bed and thinking about something. is there any linux distro that is primary oriented to python. you know what i mean. no need for php, java, or something like this. pure python and containig all the funky modules like scipy, numpy, boaconstructor (wx of course). something like the python enthought edition, but all this on a distro included. maybe psql but persistant predered, zope of course. everything a developer is ever going to need. So i stood up, sat down on my ugly acer notebook with a python stiker on it and made a huge list of cool modles i would prefer. I would like to make such a distro but i am not a linux pro. so this is going to stay just a idea. i thouht it should be realy user fredly like sabayon or ubuntu (without xgel). if this were a live distro it would be amazing. I know, dont expet someone else to do your work, but is there anyone who likes the idea and has the knowledge i dont have. I also know for quantian (cool distro), but for me, there is too much other crap and not enough python. i even got the nam of it. maybee not the best but it fits the context. PyTux ----------------------------------------------- and no, I am not a junkee, I'm addicted to Python From jeremit0 at gmail.com Tue Feb 6 10:23:08 2007 From: jeremit0 at gmail.com (jeremito) Date: 6 Feb 2007 07:23:08 -0800 Subject: How can I use __setitem__ method of dict object? Message-ID: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> Please excuse me if this is obvious to others, but I can't figure it out. I am subclassing dict, but want to prevent direct changing of some key/value pairs. For this I thought I should override the __setitem__ method as such: class xs(dict): """ XS is a container object to hold information about cross sections. """ def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): """ """ x = {} x['xS'] = xS x['xF'] = xF x['nu'] = nu x['xG'] = xG x['xA'] = x['xG'] + x['xF'] x['xT'] = x['xA'] + x['xS'] return x def __setitem__(self, key, value): """ I have overridden this method to prevent setting xT or xA outside the class. """ print "I am in __setitem__" if key == 'xT': raise AttributeError("""Can't change xT. Please change, xF, xS, or xG""") But I can't even get __setitem__ to run. Example: Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import xs >>> cs = xs.xs() >>> cs {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0} >>> cs['xT'] = 3.1415 >>> cs {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.1415000000000002} Is this what the __setitem__ method is for? If not, how can I do what I want to do? Thanks in advance, Jeremy From mcfletch at vrplumber.com Sun Feb 18 13:08:22 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 18 Feb 2007 13:08:22 -0500 Subject: Dlls In-Reply-To: <1ea031080702180356p2c1a8167jd5470832b5c6315f@mail.gmail.com> References: <1ea031080702180356p2c1a8167jd5470832b5c6315f@mail.gmail.com> Message-ID: <45D89616.3010204@vrplumber.com> Jason Ward wrote: > Hi. I am interested to know why python can't access DLL files directly. > It seems to me that because python can't access DLL's directly we have to > waste our time and write wrappers around libraries that have already > been written. > > So if the python developers were to implement say this. > > import MYDLL.dll > > Then we would be able to do everything with that library that we can > do in other languages. > > For eg. I want to use PyOpenGL. But the problem is the library hasn't > got all the opengl functions implemented. > So I can either develop quickly with an incomplete library or develop > slowly in assembler. > I mean really, in asm we just call the dll function directly. > > Why must python be different? Hi again, Jason, As we pointed out to you, ctypes *does* allow you to just load the DLL and start calling functions. In fact, that's how development tends to happen in the ctypes implementation. Someone just loads the DLL, hacks up a demo, I look at it and factor their code into the code-base. If there's some function missing that you need, do something like this: from OpenGL.platform import GL GL.myFunction( myParameter, myOtherParameter ) and if the parameters are of simple types, it will often "just work". If you want to pass arrays or similar data-types you'll need to make them ctypes arrays or pointers to use those "raw" functions, but they should work perfectly well. That is, you have to pass the right data-type, but then you'd have to do that in assembler too. Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From robin at reportlab.com Thu Feb 8 05:07:56 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 08 Feb 2007 10:07:56 +0000 Subject: Calling J from Python In-Reply-To: <2ZKdnYNMboxxS1fYRVnzvA@telenor.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> <1170796103.766866.18320@a34g2000cwb.googlegroups.com> <1170861935.779969.52980@v33g2000cwv.googlegroups.com> <1170874782.600836.210670@a34g2000cwb.googlegroups.com> <2ZKdnYNMboxxS1fYRVnzvA@telenor.com> Message-ID: <45CAF67C.1080905@chamonix.reportlab.co.uk> Tina I wrote: ...... > It's also a village in Norway: http://en.wikipedia.org/wiki/Hell,_Norway In German it's bright -- Robin Becker From bj_666 at gmx.net Thu Feb 1 16:45:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 01 Feb 2007 22:45:07 +0100 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> Message-ID: In <1170361512.204099.191740 at a75g2000cwd.googlegroups.com>, Krypto wrote: > The correct answer as told to me by a person is > > (N>>3) + ((N-7*(N>>3))>>3) How could it be correct if it uses `-`? You ruled out `-` and `/` in your first post. Ciao, Marc 'BlackJack' Rintsch From grflanagan at yahoo.co.uk Thu Feb 15 07:45:39 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 15 Feb 2007 04:45:39 -0800 Subject: basic jython question Message-ID: <1171543539.339651.319480@m58g2000cwm.googlegroups.com> Hello all I have a 'logger' module which is essentially just a facade over the 'logging' standard module. Can this be called from jython, and how is this acheived? This is a colleague's question but I have no knowledge of jython or java, and I can't install them at present in order to figure it out. It appears that the CPython logging builtin is not implemented in Jython, is this correct? The source for CPython's logging says that it should work with Python >1.5.2, so given everything from Python2.4/Lib/Logging and my own facade module, is there any way to get it working from a jython script? I presume they just can't be dropped in to a "site-packages" directory? I'm completely in the dark, any help? Gerard From hayes.tyler at gmail.com Wed Feb 28 08:44:57 2007 From: hayes.tyler at gmail.com (Tyler) Date: 28 Feb 2007 05:44:57 -0800 Subject: f2py and Fortran90 gfortran_filename error In-Reply-To: References: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> Message-ID: <1172670297.565383.303830@z35g2000cwz.googlegroups.com> On Feb 28, 12:40 am, Robert Kern wrote: > Tyler wrote: > > Hello All: > > > Since my last post I have attempted to use the f2py program which > > comes with numpy. > > It's better to ask these questions on numpy-discussion, instead. There are more > f2py users per capita there. > > http://www.scipy.org/Mailing_Lists > > > > > I am able to create a .so file fine; > > however, when I import it into Python, I receive the following > > message: > > >>>> import matsolve2 > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: ./matsolve2.so: undefined symbol: _gfortran_filename > > > The steps I used to create the matsolve2.so file are as follows: > > > (1) Created a Fortran90 program matsolve.f90 > > > Note: The program compiles fine and prints the proper output for the > > simple matrix specified. I have also attached below the file > > matsolve.f90 if it helps at all. > > > (2) f2py matsolve.f90 -m matsolve2 -h matsolve2.pyf > > (3) f2py -c matsolve2.pyf --f90exec=/usr/bin/gfortran matsolve.f90 > > > Note: I had to specify the f90 path as f2py did not automatically find > > it. > > You want to specify the *kind* of Fortran compiler such that f2py knows what > compile/link flags to use. Only use the --f90exec option to inform f2py that the > actual executable is named something odd or is in an unexpected place, like > /opt/gfortran/bin/gfortran-4.3, for example. The correct option to use is > > --fcompiler=gnu95 > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco Hi Robert: Thanks for the advice and I'll try posting to the mailing list you mentioned. For what it's worth, the option, --fcompiler=gnu95 yileds the following error in the second calling of f2py: error: don't know how to compile Fortran code on platform 'posix' with 'gnu95' compiler. Supported compilers are: compaq,absoft,intel,gnu,sun,f,vast,ibm,lahey,intelv,intele,pg,compaqv,mips,hpux,intelev,nag) Cheers, t. From wolf_tracks at invalid.com Thu Feb 8 09:01:50 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 08 Feb 2007 14:01:50 GMT Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: Robert Kern wrote: > W. Watson wrote: >> Robert Kern wrote: >>> W. Watson wrote: >>>> For some reason Python 2.2.4 cannot find the Numeric module. It's been >>>> suggested that I should re-install the Numeric file. How do that? Also the >>>> PIL. The three install files are: >>>> python-2.4.4.msi >>>> PIL-1.1.5.win32-py2.4.exe >>>> Numeric-24.2.win32-py2.4.exe >>> The latter two are executable installers. Run them. >>> >> I have re-run Numeric. The python program still cannot detect the Numeric >> module. > > Well, check to make sure that the Python executable is the one that you think it > is. You can look at sys.executable to find the actual .exe of the running Python > interpreter. With Python 2.4.4 and a standard installation, it should be > c:\Python24\python.exe I believe. Then check to make sure that Numeric and PIL > are actually installed in c:\Python24\Lib\site-packages\ . > This may be a good clue. I'm not the author of the sentuser.py program that I'm using 2.4 for. It's an application meant for another PC. On that machine, I only have 2.4 installed. I decided to learn Python a few weeks ago and installed 2.5.It's quite possible there's some confusion with the just installed application. I have not yet started my education on python, so know little about it. I did a search in the python24 folder for sys.exec* (in c:\python24), but came up with nothing. [nothing in a search of c:--sys.exec*] I have two python folders, c:\python24 and c:\python25. The contents of both folders look fairly similar and each have a python.exe. I do not use a PIL or Numeric in 2.5. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet 'I think it not improbable that man, like the grub that prepares a chamber for the winged thing it has never seen but is to be, may have... destinies that he does not understand." -- Oliver Wendell Holmes -- Web Page: From metaperl at gmail.com Mon Feb 5 14:47:43 2007 From: metaperl at gmail.com (metaperl) Date: 5 Feb 2007 11:47:43 -0800 Subject: "flushing"/demanding generator contents - implications for injection of control Message-ID: <1170704863.646629.156310@h3g2000cwc.googlegroups.com> For this program: def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] r = reverse("golf") for char in r: print char I'm wondering if the line: r = reverse("golf") "demands" the contents of the function reverse() all at once and if I must write for char in reverse("golf"): print char if I want the results streamed instead of generated complely. ** CONTEXT ** The simple example above is not what I am really doing. My real program parses very large data files using pyparsing. Pyparsing can generate incremental/yielded results with no problem: http://pyparsing.wikispaces.com/message/view/home/248539#248852 but because I believe in injection of control (pushing data around as opposed to having the target pull it), I get the parse and then inject it into the generator: parse = parsing.parse(fp.read()) txt = textgen.generate(self.storage.output, patent_key, parse, f.basename(), debug=False) From jeff at taupro.com Sat Feb 17 22:46:23 2007 From: jeff at taupro.com (Jeff Rush) Date: Sat, 17 Feb 2007 21:46:23 -0600 Subject: Game Programming Clinic and Online Gaming at PyCon Message-ID: <45D7CC0F.7020105@taupro.com> At PyCon this year we're going to have a multi-day game programming clinic and challenge. This is a first-time event and an experiment to find those in the Python community who enjoy playing and creating games. Python has several powerful modules for the creation of games among which are PyGame and PyOpenGL. On Friday evening, Phil Hassey will give an introduction to his game Galcon, an awesome high-paced multi-player galactic action-strategy game. You send swarms of ships from planet to planet to take over the galaxy. Phil will be handing out free limited-time licenses to those present. He will also be glad to talk about the development of Galcon using PyGame. After the Friday PSF Members meeting lets out around 8:40pm, Richard Jones will give his 30-60 minute introduction to the PyGame framework so you too can get started writing games. On Saturday evening, Lucio Torre and Alejandro J. Cura, who have come from Argentina to give the talk "pyweek: making games in 7 days" Friday afternoon, will help people develop their games in the clinic room with mini-talks on various game technologies. On Sunday evening Lucio and Alejandro will be around to help with further development issues, and Richard Jones will be back to present more about PyGame and help reach a group concensus on what to work on during the GameSprint. Richard also runs PyWeek, a bi-annual python game programming challenge online. Phil will also be back helping people get into playing Galcon and everyone can get into multiplayer challenges against those who show up. And then during the four days of sprinting, the group will compete to produce a working game meeting agreed upon requirements and then decide who has best achieved those. This overall gaming track is informal, with people coming and going, and others are welcome to get involved in giving mini-talks or showing off their creations. Specific rooms and times can be found on the birds-of-a-feature wiki page at: http://us.pycon.org/TX2007/BoF The wiki page for collecting game clinic ideas is at: http://us.pycon.org/TX2007/GamingClinic And the wiki page for the game sprint is at: http://us.pycon.org/TX2007/GameSprint --- Want to get a head start? Follow the online lectures about PyGame at: http://rene.f0o.com/mywiki/PythonGameProgramming And to get your laptop ready, check out the installation and testing instructions about half way down the page at: http://rene.f0o.com/mywiki/LectureOne#line-50 You can also check out the game Galcon at: http://www.imitationpickles.org/galcon/index.html See you later this week, Jeff Rush Co-Chair PyCon 2007 From aleaxit at gmail.com Mon Feb 26 14:02:02 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 26 Feb 2007 11:02:02 -0800 Subject: Rational numbers In-Reply-To: References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> <1172432910.457442.232480@s48g2000cws.googlegroups.com> Message-ID: <1172516522.491585.117160@a75g2000cwd.googlegroups.com> On Feb 25, 3:09 pm, Fernando Perez wrote: > alea... at gmail.com wrote: > > gmpy itself is or should be pretty trivial to build on any platform > > (and I'll always happily accept any fixes that make it better on any > > specific platform, since it's easy to make them conditional so they'll > > apply to that platform only), but the underlying GMP is anything but:- > > (. > > Alex, have you had a look at SAGE? > > http://modular.math.washington.edu/sage/ > > it uses GMP extensively, so they've had to patch it to work around these > issues. You can look at the SAGE release (they package everything as the > original tarball + patches) for the GMP-specific stuff you need, though I > suspect you'll still want to play with SAGE a little bit :). It's a mighty > impressive system. Thanks Fernando, I will take a look at that. Alex From wolf_tracks at invalid.com Wed Feb 7 22:19:25 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 07 Feb 2007 19:19:25 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: <1170896151.334753.113130@l53g2000cwa.googlegroups.com> Message-ID: BTW, I found a RemoveNumeric.exe and RemovePIL.exe in the C/Python24 folder, but when I try to execute them, they produce a message about only being able to use them at start-up. From http Thu Feb 15 00:20:31 2007 From: http (Paul Rubin) Date: 14 Feb 2007 21:20:31 -0800 Subject: threading and multicores, pros and cons References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> Message-ID: <7xzm7gt2sg.fsf@ruckus.brouhaha.com> Maric Michaud writes: > > "Some time back, a group did remove the GIL from the python core, and > > implemented locks on the core code to make it threadsafe. Well, the > > problem was that while it worked, the necessary locks it made single > > threaded code take significantly longer to execute." > > Very interesting point, this is exactly the sort of thing I'm > looking for. Any valuable link on this ? I think it was a long time ago, Python 1.5.2 or something. However it really wasn't that useful, since as Garrick said, it slowed Python down. The reason was CPython's structures weren't designed for thread safety so it needed a huge amount of locking/releasing. For example, adjusting any reference count required setting and releasing a lock, and CPython does this all the time. Getting rid of the GIL in a serious way requires radically changing the interpreter, not just sticking some locks here and there. From google at orcon.net.nz Fri Feb 16 19:19:06 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 16 Feb 2007 16:19:06 -0800 Subject: Output to a text window Message-ID: <1171671545.951006.160420@k78g2000cwa.googlegroups.com> Hi, I'm going around in circles so I'm asking for help. I want to read a simple text file and output the contents to a GUI window when I click on a button. I have written a small python program to read the contents of a file when a button is clicked but can only output this to a console window. I'm using the pygtk binding with glade for the gui. I know it must be quiet simple but a mental block has rapidly descended. Any help would be appreciated. From theller at ctypes.org Wed Feb 28 06:35:54 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 28 Feb 2007 12:35:54 +0100 Subject: py2exe, library.zip and python.exe In-Reply-To: References: Message-ID: Martin Evans schrieb: > I have converted a Python script using py2exe and have it set to not bundle > or compress. The result is my exe and all the support files including > library.zip (exactly as planned - nice job py2exe). > > Question: My py2exe application needs to be able to execute extra copies of > python.exe. I have placed python.exe in the same directory. It obviously > picks up the main python24.dll but how can I configure things so that it > would use the same library.zip for all the library files? This would save > me having two sets of files. > > (The py2exe application happens to be a twisted server app running as a > service which has the ability to launch python scripts as a logged on user) > > Thanks, Martin. > > You have to put library.zip on sys.path. Maybe you could create a site.py file in that directory which can do this, I assume the python.exe will try to load that. There may be other possibilities as well. Thomas From jeff at jmcneil.net Thu Feb 22 13:22:18 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 22 Feb 2007 13:22:18 -0500 Subject: How to covert ASCII to integer in Python? In-Reply-To: <6OkDh.177594$IL1.143903@newsfe13.lga> References: <6OkDh.177594$IL1.143903@newsfe13.lga> Message-ID: <82d28c40702221022o60de9552g9376d18dd693a725@mail.gmail.com> Or perhaps... >>> ord ("a") 97 >>> chr (97) 'a' >>> On 2/22/07, hg wrote: > > John wrote: > > > Is there any built in function that converts ASCII to integer or vice > > versa in Python? > > > > Thanks! > >>> int('10') > 10 > >>> str(10) > '10' > >>> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric_brunel at despammed.com Mon Feb 26 03:50:01 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 26 Feb 2007 09:50:01 +0100 Subject: Having multiple instances of a single application start a single instance of another one References: <45df6400$0$489$cc7c7865@news.luth.se> Message-ID: On Fri, 23 Feb 2007 23:39:03 +0100, Troy Melhase wrote: >> The first time A starts, it should open a B process and start >> communicating with it. All other times an A instance starts it should >> simply talk with the B that already is open. > > B should write its process id to a location known by both > applications. When A starts, it should read that PID from the file > and attempt to communicate with the process having that PID. > > When B starts, it should also check for the file. If it's found and > if the PID in it is present in the process table, then B should exit. > Otherwise, it should start normally and write its own PID to the file. You have a race condition here: if another instance of B is created between the check and the creation of the file, you'll have two instances running. And remember Murphy's law: yes, it will happen, and quicker than you can imagine ;-) To prevent this from happening, I usually create a special directory for the PID file, and I delete both the file and the directory when the process exits. The advantage is that os.mkdir is basically a "test and set" in a single operation: if two of these are attempted at "the same time", only one can succeed. It is also cross-platform and even works on shared file systems. So the code would be something like: ## Try to create directory try: os.mkdir(os.path.join(common_directory, "B_lock")) except OSError: ## Failed: another instance is running sys.exit() ## Create the PID file # (...) try: ## Application code # (...) finally: ## Remove the PID file # (...) ## Delete directory os.rmdir(os.path.join(common_directory, "B_lock")) HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From duncan.booth at invalid.invalid Thu Feb 15 14:21:31 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Feb 2007 19:21:31 GMT Subject: reference data in a dictionary References: <1115a2b00702141226i4f23dc17x1360d87ed253dd3e@mail.gmail.com> <87ps8c79tv.fsf@benfinney.id.au> Message-ID: "Wensui Liu" wrote: > I know dict['row1'] will always work. but it will only get 1 row out > of the dict. is there anyway i can get multiple (>1) rows out of dict > by directly refeencing them, something like dict[['row1', 'row2']]. > [d[x] for x in ('row1', 'row2')] From steve at holdenweb.com Sun Feb 18 18:24:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 18 Feb 2007 18:24:05 -0500 Subject: Dlls In-Reply-To: <1ea031080702180725x5584aed9w4bec1f440a0a3f89@mail.gmail.com> References: <1ea031080702180356p2c1a8167jd5470832b5c6315f@mail.gmail.com> <1ea031080702180725x5584aed9w4bec1f440a0a3f89@mail.gmail.com> Message-ID: <45D8E015.6040106@holdenweb.com> Jason Ward wrote: > But in Assembler I can access any dll. Doesn't matter what language it > was written in. So this teaches us that Python isn't assembler language. > A dll contains machine code, so shouldn't any language be able to read > the functions. > Machine is the native language of a pc. > > btw, what's with the car analogies? They were an attempt to educate you. Never mind. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From davecook at nowhere.net Sun Feb 18 19:35:32 2007 From: davecook at nowhere.net (Dave Cook) Date: Mon, 19 Feb 2007 00:35:32 GMT Subject: Help Required for Choosing Programming Language References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: On 2007-02-16, ifti_crazy at yahoo.com wrote: > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net You might take a look at http://dabodev.com Dave Cook From venky at nospam.com Mon Feb 26 21:52:03 2007 From: venky at nospam.com (Venky) Date: Tue, 27 Feb 2007 02:52:03 GMT Subject: classobj? References: <1172542760.288738.72550@8g2000cwh.googlegroups.com> Message-ID: ... > > Do you mean that you want to add it to globals()? > > globals()['SomeClass'] = cl > > myinst = SomeClass() > print isinstance(myinst, SomeClass) > print isinstance(myinst, BaseClass) > > -- > Hope this helps, > Steven > > > Thanks. That's what I was looking for. From steven.bethard at gmail.com Sat Feb 24 13:11:42 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 24 Feb 2007 11:11:42 -0700 Subject: [ANN] argparse 0.6 - Command-line parsing library Message-ID: Announcing argparse 0.6 ----------------------- argparse home: http://argparse.python-hosting.com/ argparse single module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw argparse bundled downloads at PyPI: http://www.python.org/pypi/argparse/ About this release ================== This release adds support for argument groups, and fixes a bug in the display of required options. Also, the source distribution of this release should now include the tests. Note that the 'outfile' type is still deprecated and will likely be removed in the next release. Please update your code to use the new FileType factory. New in this release =================== * Required options are no longer displayed with brackets (so that they no longer look optional). * The source distribution includes ``test_argparse.py``, argparse's test suite. * Arguments can now be grouped into user-defined sections instead of the default "positional arguments" and "optional arguments" sections:: >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) >>> xgroup = parser.add_argument_group('xxxx') >>> xgroup.add_argument('-x', help='x help') >>> ygroup = parser.add_argument_group('yyyy') >>> ygroup.add_argument('y', help='y help') >>> parser.print_help() usage: PROG [-x X] y xxxx: -x X x help yyyy: y y help About argparse ============== The argparse module is an optparse-inspired command line parser that improves on optparse by: * handling both optional and positional arguments * supporting parsers that dispatch to sub-parsers * producing more informative usage messages * supporting actions that consume any number of command-line args * allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS as well as including a number of other more minor improvements on the optparse API. To whet your appetite, here's a simple program that sums its command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', nargs='+', type=int) parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w')) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() From gagsl-py at yahoo.com.ar Wed Feb 14 20:52:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 22:52:52 -0300 Subject: output to console and to multiple files References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> Message-ID: En Wed, 14 Feb 2007 19:28:34 -0300, nathan.shair at gmail.com escribi?: > I'm looking for a way to output stdout/stderr (from a subprocess or > spawn) to screen and to at least two different files. Look at the tee command. If you control the subprocess, and it's written in Python, using the Python recipes would be easier and perhaps you have more control. But if you can't modify the subprocess, you'll have to use tee. -- Gabriel Genellina From facundo at taniquetil.com.ar Tue Feb 27 07:36:24 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Tue, 27 Feb 2007 12:36:24 +0000 (UTC) Subject: finding out the precision of floats References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > (and I don't want the standard Decimal class :) Why? -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From gagsl-py at yahoo.com.ar Wed Feb 21 04:47:07 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Feb 2007 06:47:07 -0300 Subject: converting u'11\xa022' to '11\xa022' References: Message-ID: En Wed, 21 Feb 2007 06:24:55 -0300, Laurent Pointal escribi?: > Gabriel Genellina a ?crit : >> En Wed, 21 Feb 2007 00:31:32 -0300, alf escribi?: > >>> 2-list of supported encodings? >> I don't know how to query the list, except by reading the documentation >> for the codecs module. > >>>> from encodings import aliases Nice to know! But would be nicer if this feature were documented. In fact, I can't find any documentation about the encodings package, except for encodings.idna -- Gabriel Genellina From gagsl-py at yahoo.com.ar Wed Feb 14 01:45:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 03:45:30 -0300 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: En Wed, 14 Feb 2007 03:09:37 -0300, jm.suresh at no.spam.gmail.com escribi?: > Hi, > I have a program which literately finds the object that overlapping a > point. The horizontal and vertical search are called recursively from > inside each other. > Is this way of implementation fill the stack space with the local > variables inside each call. If this is not good, is there a better way > to implement? Or python itself will understand that the calls happen > in the last line, so local variables need not be pushed into the > stack? I'm afraid not, the calls will be stacked until some object is found. Python does not do "tail recursion optimization" (at least, I'm not aware of that). But even if it could do that, in this case you have recursive calls between two functions, and that's a bit harder. Going back to your original problem, maybe you can use some known algorithms from computational geometry; start with http://www.faqs.org/faqs/graphics/algorithms-faq/ -- Gabriel Genellina From jairodsl at gmail.com Mon Feb 12 23:03:07 2007 From: jairodsl at gmail.com (jairodsl) Date: 12 Feb 2007 20:03:07 -0800 Subject: how to compare... Message-ID: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> Hello everybody ! I have two list, they are, S1=['A','B','C','D','E'], and S2=['F','G','H','I','J'], but i have to compare both in this way: A vs J A vs I, B vs J A vs H, B vs I, C vs J A vs G, B vs H, C vs I, D vs J A vs F, B vs G, C vs H, D vs I, E vs J B vs F, C vs G, D vs H, E vs I C vs F, D vs G, E vs H D vs F, E vs G E vs F Perhaps, you should understand better in this way: A J A B I J A B C H I J A B C D G H I J A B C D E F G H I J B C D E F G H I C D E F G H D E F G E F Could someone give me any idea how to compare(or print) both list in this way ??? Thanks a lot !!! jDSL From rmcore at gmail.com Sat Feb 3 12:29:09 2007 From: rmcore at gmail.com (Michael Bentley) Date: Sat, 3 Feb 2007 11:29:09 -0600 Subject: strange test for None In-Reply-To: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> References: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> Message-ID: <5D1929E7-8807-4E1C-B482-13E26E264089@gmail.com> On Feb 3, 2007, at 7:47 AM, karoly.kiripolszky wrote: > in my server i use the following piece of code: > > ims = self.headers["if-modified-since"] > if ims != None: > t = int(ims) > > and i'm always getting the following error: > > t = int(ims) > ValueError: invalid literal for int(): None > > i wanna know what the hell is going on... first i tried to test using > is not None, but it makes no difference. Sounds like ims == 'None'. Try changing: if ims != None: to if ims: and you might also wrap your call to int(ims) in a try block. HTH, Michael From dingbat at codesmiths.com Tue Feb 6 13:48:45 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 6 Feb 2007 10:48:45 -0800 Subject: How can I access data from MS Access? In-Reply-To: References: Message-ID: <1170787725.436946.33030@h3g2000cwc.googlegroups.com> On 5 Feb, 19:40, "Sells, Fred" wrote: > Years ago we used to get our FORTRAN card decks back from the DP center > with a piece of scrap paper saysing "She No Work". top that. I used to use a cross-compiler (targetting some obscure single-chip hardware) that had just a single error message "Diddley-squat somewhere near here" From ziga.seilnacht at gmail.com Wed Feb 7 12:12:02 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 7 Feb 2007 09:12:02 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: References: <45C9A137.8090009@v.loewis.de> <1170861460.614883.108310@k78g2000cwa.googlegroups.com> <1170862664.972024.322260@a75g2000cwd.googlegroups.com> Message-ID: <1170868322.560426.149920@p10g2000cwp.googlegroups.com> Thomas Heller wrote: > > Do you have a pointer to that post? > I think that he was refering to this post: http://mail.python.org/pipermail/python-list/2006-December/416241.html If you are interested in various implementations there is also this: http://mail.python.org/pipermail/python-list/2006-August/396835.html and a module from PyPy: http://mail.python.org/pipermail/python-dev/2006-July/067501.html which was moved to a new location: https://codespeak.net/viewvc/pypy/dist/pypy/tool/pairtype.py?view=markup Ziga From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 7 20:47:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 08 Feb 2007 02:47:31 +0100 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com><1170872694.018720.301410@m58g2000cwm.googlegroups.com> Message-ID: <52vdp2F1qp2n6U2@mid.individual.net> S.Mohideen wrote: > There is a dictionary on which I store/read data values. I want to > seperate the send and recv functionality on two different > processes so that the parallel execution becomes fast. What makes you think that'll be faster? Remember: - If you have one CPU, there is no parallelity at all. - If you do have multiple CPUs but only one network device, there is no parallel networking. Regards, Bj?rn -- BOFH excuse #188: ..disk or the processor is on fire. From gagsl-py at yahoo.com.ar Sun Feb 11 00:15:21 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 02:15:21 -0300 Subject: os.tmpfile() -> permission denied (Win XP) References: <1171169872.507298.196990@j27g2000cwj.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 01:57:52 -0300, John Machin escribi?: > | >>> os.tmpfile() > Traceback (most recent call last): > File "", line 1, in > OSError: [Errno 13] Permission denied > > 1. Before I start checking what permissions who has to do what to > which, what directory is it likely to be trying to open the temp file > in? C:\WINDOWS\TEMP....? You could analyze the source, but usually I find easier to use FILEMON: http://www.sysinternals.com -- Gabriel Genellina From h at realh.co.uk Sat Feb 3 19:24:13 2007 From: h at realh.co.uk (Tony Houghton) Date: Sun, 4 Feb 2007 00:24:13 +0000 (UTC) Subject: Is Python Right for Me? References: Message-ID: In , Stuart D. Gathman wrote: > On Fri, 02 Feb 2007 15:09:20 -0500, Mister Newbie wrote: > >> I want to make small, 2D games. I have no programming experience. Is >> Python a good choice? > > Definitely. I teach a class for 7th to 12th grade where I use this > tutorial to introduce programming: > > http://www.livewires.org.uk/python/ > http://www.livewires.org.uk/python/pdfsheets.html > > As an adult, just skip rapidly through the elementary material. The final > module (Games sheets) walks you through creating 3 2D games with pygame! The OP should also look at pygame if that isn't what the livewires module is based on. And if it is based on pygame he should look at pygame anyway. -- TH * http://www.realh.co.uk From sjmachin at lexicon.net Tue Feb 6 17:47:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Feb 2007 14:47:33 -0800 Subject: Help reading binary data from files In-Reply-To: <1170801241.730109.23110@h3g2000cwc.googlegroups.com> References: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> <1170801241.730109.23110@h3g2000cwc.googlegroups.com> Message-ID: <1170802053.841303.31370@k78g2000cwa.googlegroups.com> On Feb 7, 9:34 am, "jeff" wrote: > On Feb 6, 4:01 pm, "jeff" wrote: > > > > > I am stumped trying to read binary data from simple files. Here is a > > code snippet, where I am trying to simply print little-endian encoded > > data from files in a directory. > > > for name in os.listdir(DOWNLOAD_DIR): > > filename = s.path.join(DOWNLOAD_DIR, name) > > if os.path.isfile(filename): > > f = open(filename, 'rb') > > while True: > > ele = unpack(' > print ele > > > When the code runs, 0 is always the data printed, but the data files > > are not all zero. > > > Any quick tips? > > > thanks > > Wow, supreme stupidity on my part. It turns out that there were a lot > of zeros at the beginning of the file, and the slowness of the console > just showed me the zero data during the test time of ~ 10 seconds. That's a rather severe case of premature emailisation :-) > If > I throw away the zeros, I see my real data....sorry for the time waste Some further suggestions (not mutually exclusive): 1. redirect the console to a file 2. write more per line 3. download a free or shareware gadget that will show you the contents of a file in hex and char 4. You may want/need to write yourself a better dumper that's tailored to the type of files that you are loooking at, e.g. 498: 0031 FONT len = 001e (30) 502: b4 00 00 00 08 00 90 01 00 00 00 00 00 a5 07 01 ?~~~?~?? ~~~~~??? 518: 56 00 65 00 72 00 64 00 61 00 6e 00 61 00 V~e~r~d~a~n~a~ 532: 041e FORMAT len = 001e (30) 536: 05 00 19 00 00 23 2c 23 23 30 5c 20 22 44 4d 22 ?~? ~~#,##0\ "DM" 552: 3b 5c 2d 23 2c 23 23 30 5c 20 22 44 4d 22 ;\-#,##0\ "DM" 566: 041e FORMAT len = 0023 (35) 570: 06 00 1e 00 00 23 2c 23 23 30 5c 20 22 44 4d 22 ?~? ~~#,##0\ "DM" 586: 3b 5b 52 65 64 5d 5c 2d 23 2c 23 23 30 5c 20 22 ;[Red]\- #,##0\ " 602: 44 4d 22 DM" HTH, John From __peter__ at web.de Sat Feb 3 03:50:40 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 09:50:40 +0100 Subject: from __future__ import absolute_import ? References: Message-ID: Ron Adam wrote: > Peter Otten wrote: >> Ron Adam wrote: >> >>> from __future__ import absolute_import >>> >>> Is there a way to check if this is working? I get the same results with >>> or without it. >>> >>> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) >>> [MSC v.1310 32 bit (Intel)] on win 32 >> >> If there are two modules 'foo', one at the toplevel and the other inside >> a package 'bar', >> >> from __future__ import absolute_import >> import foo >> >> will import the toplevel module whereas >> >> import foo >> >> will import bar.foo. A messy demonstration: >> >> $ ls bar >> absolute.py foo.py __init__.py relative.py >> $ cat bar/absolute.py >> from __future__ import absolute_import >> import foo >> $ cat bar/relative.py >> import foo >> $ cat foo.py >> print "toplevel" >> $ cat bar/foo.py >> print "in bar" >> $ python2.5 -c 'import bar.absolute' >> toplevel >> $ python2.5 -c 'import bar.relative' >> in bar >> >> >> Another example is here: >> >> http://mail.python.org/pipermail/python-list/2007-January/422889.html >> >> Peter > > Thanks, that helped, I see why I was having trouble. > > > work > | > |- foo.py # print "foo not in bar" > | > `- bar > | > |- __init__.py > | > |- foo.py # print "foo in bar" > | > |- absolute.py # from __futer__ import absolute_import > | # import foo > | > `- relative.py # import foo > > > * Where "work" is in the path. > > > (1) > > C:\work>python -c "import bar.absolute" > foo not in bar > > C:\work>python -c "import bar.relative" > foo in bar > > > (2) > > C:\work>python -m "bar.absolute" > foo not in bar > > C:\work>python -m "bar.relative" > foo not in bar > > > (3) > > C:\work>python > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] > on win 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import bar.absolute > foo not in bar > >>> import bar.relative > foo in bar > > > (4) > > C:\work>cd bar A path below the package level is generally a good means to shoot yourself in the foot and should be avoided with or without absolute import. > C:\work\bar>python -c "import bar.absolute" > foo in bar > > C:\work\bar>python -c "import bar.relative" > foo in bar > > > (5) > > C:\work\bar>python > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] > on win 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import bar.absolute > foo in bar > >>> import bar.relative > foo in bar > >>> > > > > Case (2) seems like it is a bug. I think so, too. > Why not also have (4), and (5) do the same as cases (1) and (3)? The work/bar directory is the current working directory and occurs in the path before the work directory. When bar.absolute imports foo python is unaware that work/bar/foo.py is part of the bar package. > in cases (4) and (5), that is the result I would expect if I did: > > import absolute # with no 'bar.' prefix. > import relative > > > From what I understand, in 2.6 relative imports will be depreciated, and > in 2.7 > they will raise an error. (providing plans don't change) > > Would that mean the absolute imports in (4) and (5) would either find the > 'foo not in bar' or raise an error? No, in 1, 3 -- and 2 if the current behaviour is indeed a bug. This is only for the relative import which would have to be spelt from . import foo in an absolute-import-as-default environment; import foo would always be an absolute import. > If so, is there any way to force (warning/error) behavior now? I don't know. Peter From jstroud at mbi.ucla.edu Thu Feb 15 07:00:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 15 Feb 2007 04:00:52 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: BJ?rn Lindqvist wrote: > On 2/15/07, James Stroud wrote: >> I guess we differ on what is obvious. This seems obvious to me: >> >> [1] + (1,) => [1, 1] >> (1,) + [1] => (1, 1) > > I agreed with you up to this point. But this seems more obvious to me: > > [1] + (1,) => [1, 1] > (1,) + [1] => [1, 1] > > In other languages and situations, types are widened, 1 + 1.0 = 1.0 + > 1.0. And list is "wider" than tuple. > They are widened by information content, not functionality. Tuples don't have any more information content than lists. From vithi99 at hotmail.com Thu Feb 1 20:28:02 2007 From: vithi99 at hotmail.com (vithi) Date: 1 Feb 2007 17:28:02 -0800 Subject: win32com.client In-Reply-To: <1170379374.589869.158610@p10g2000cwp.googlegroups.com> References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170379374.589869.158610@p10g2000cwp.googlegroups.com> Message-ID: <1170379682.386807.99880@a34g2000cwb.googlegroups.com> Hi, I use python for window. If you are saying win32com in part of the python then you are wrong. Here is a prove:- IDLE 1.2 >>> import win32com Traceback (most recent call last): File "", line 1, in import win32com ImportError: No module named win32com >>> you try in your computer vithi From rbonvall at alumnos.inf.utfsm.cl Thu Feb 8 12:58:33 2007 From: rbonvall at alumnos.inf.utfsm.cl (Roberto Bonvallet) Date: Thu, 8 Feb 2007 17:58:33 +0000 (UTC) Subject: Convert from unicode chars to HTML entities References: Message-ID: Steven D'Aprano wrote: > I have a string containing Latin-1 characters: > > s = u"? and many more..." > > I want to convert it to HTML entities: > > result => > "© and many more..." [...[ > Is there a "batteries included" solution that doesn't involve > reinventing the wheel? recode is good for this kind of things: $ recode latin1..html -d mytextfile It seems that there are recode bindings for Python: $ apt-cache search recode | grep python python-bibtex - Python interfaces to BibTeX and the GNU Recode library HTH, cheers. -- Roberto Bonvallet From mccredie at gmail.com Thu Feb 15 11:51:46 2007 From: mccredie at gmail.com (Matimus) Date: 15 Feb 2007 08:51:46 -0800 Subject: output to console and to multiple files In-Reply-To: <1171554821.510472.313950@s48g2000cws.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171498259.757320.127100@q2g2000cwa.googlegroups.com> <1171554821.510472.313950@s48g2000cws.googlegroups.com> Message-ID: <1171558306.121792.169430@h3g2000cwc.googlegroups.com> On Feb 15, 7:53 am, "nathan.sh... at gmail.com" wrote: > On Feb 14, 5:10 pm, "goodwolf" wrote: > > > > > like this? > > > class Writers (object): > > > def __init__(self, *writers): > > self.writers = writers > > > def write(self, string): > > for w in self.writers: > > w.write(string) > > > def flush(self): > > for w in self.writers: > > w.flush(): > > > import sys > > > logfile = open('log.txt', 'w') > > sys.stdout = Writers(aya.stdout, file('log.out', 'w'), logfile) > > sys.stderr = Writers(aya.stdout, file('log.err', 'w'), logfile) > > i've tried simliar methods to this and to what Matimus wrote. I know > it works great when using print statements. > However, I'm looking to find something that will work with the output > from a subprocess, such as from spawn, os.system, os.popen, etc. I think you should be able to use my or goodwolf's solution with the subprocess module. Something like this (untested): [code] class TeeFile(object): def __init__(self,*files): self.files = files def write(self,txt): for fp in self.files: fp.write(txt) if __name__ == "__main__": import sys from subprocess import Popen command = "whatever you want to run" outf = file("log.out","w") errf = file("log.err","w") allf = file("log.txt","w") Popen( command, stdout = TeeFile(sys.__stdout__,outf,allf), stderr = TeeFile(sys.__stderr__,errf,allf) ) [/code] From gnewsg at gmail.com Mon Feb 12 08:26:27 2007 From: gnewsg at gmail.com (billie) Date: 12 Feb 2007 05:26:27 -0800 Subject: WindowsNT user authentication Message-ID: <1171286787.091120.4190@p10g2000cwp.googlegroups.com> Hi there, I would like to submit a username/password pair to a Windows NT workstation and find out if it's valid. Moreover I would like to get the user's home directory given the username. Does it is possible to do that by using pywin32 extension? Could someone point me in the right direction? Best regards From jimmy at retzlaff.com Thu Feb 15 05:28:38 2007 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Thu, 15 Feb 2007 02:28:38 -0800 Subject: ANN: EasyDialogs for Windows version 46691.0 Message-ID: EasyDialogs for Windows is available at: http://www.averdevelopment.com/python/ EasyDialogs for Windows is a ctypes based emulation of the EasyDialogs module included in the Python distribution for Mac. It attempts to be as compatible as possible. Code using the Mac EasyDialogs module can often be run unchanged on Windows using this module. The module has been tested on Python 2.3 running on Windows NT, 98, XP, and 2003. EasyDialogs is written in pure Python using Thomas Heller's ctypes module to call Windows APIs directly. No Python GUI toolkit is used. This means that relatively small distributions can be made with py2exe (or its equivalents). A simple test of all the dialogs in EasyDialogs bundled up using py2exe results in a distribution that is about 1.25MB. Using py2exe in concert with NSIS as shown here allows the same test to run as a single file executable that is just under 500KB. Requires: Microsoft Windows, Python 2.3 or higher, and ctypes 0.6.3 or higher (ctypes is included with Python 2.5 and higher, so it is not a separate requirement there). License: MIT Change history: Version 46691.0 - Fixed a bug that caused warnings with newer version of ctypes (including the version included in Python 2.5) - The edit box in AskString now scrolls horizontally if the entered text does not otherwise fit - AskFileForOpen(multiple=True) will allow multiple files to be selected and a list of strings will be returned. If multiple is False (the default if not specified) then only a single file can be selected and a string is returned. This no longer seems to work on the Mac, but it's useful enough to add it to the Windows version anyway. This change is based on a patch contributed by Waldemar Osuch. - Made minor changes to bring inline with SVN revision 46691 for Mac Version 1.16.0 - Removed resource DLL, resources are now in a Python source file which simplifies distribution of apps with py2exe - Spelling corrections - File open/save dialogs did not display on Windows 98 - AskString edit boxes were too short on Windows 98 - Improved display of drop down lists on Windows 98 and NT - Made minor changes to bring inline with CVS version 1.16 for Mac Version 1.14.0 - Initial public release Jimmy From mccredie at gmail.com Tue Feb 6 19:13:00 2007 From: mccredie at gmail.com (Matimus) Date: 6 Feb 2007 16:13:00 -0800 Subject: Coordinate Grid Points In-Reply-To: <1170804943.418026.243480@q2g2000cwa.googlegroups.com> References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> <1170727428.120082.47690@a75g2000cwd.googlegroups.com> <1170804943.418026.243480@q2g2000cwa.googlegroups.com> Message-ID: <1170807179.954320.92600@v33g2000cwv.googlegroups.com> [code] #classify "Point" class Point(object): def _init_(self, x, y): <--- This is your problem self.x = x self.y = y [/code] That should be '__init__'. Two underscores before and after. But, IMHO, I don't think a class is really necessary unless you are going to build in compare facilities. You might as well just use a tuple: [code] from random import randint pt = (randint(1,20),randint(1,20)) ... x,y = pt x = pt[0] y = pt[1] [/code] From beliavsky at aol.com Wed Feb 28 08:55:15 2007 From: beliavsky at aol.com (Beliavsky) Date: 28 Feb 2007 05:55:15 -0800 Subject: f2py and Fortran90 gfortran_filename error In-Reply-To: References: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> Message-ID: <1172670915.478334.48510@j27g2000cwj.googlegroups.com> On Feb 28, 12:40 am, Robert Kern wrote: > Tyler wrote: > > Hello All: > > > Since my last post I have attempted to use the f2py program which > > comes with numpy. > > It's better to ask these questions on numpy-discussion, instead. There are more > f2py users per capita there. > > http://www.scipy.org/Mailing_Lists I wish the Google Groups interface to the list http://groups.google.com/group/Numpy-discussion worked. When I use it to post my messages bounce, but messages from the list do show up on Google Groups. The "bounces" say "This mailing list is now defunct. Please use numpy-discussion at scipy.org to discuss NumPy, Numeric, and numarray. http://projects.scipy.org/mailman/listinfo/numpy-discussion" Yes, I know I could follow these instructions, but I prefer to use Google Groups. From Art at Arthurian.com Sun Feb 4 14:46:05 2007 From: Art at Arthurian.com (Frank Arthur) Date: Sun, 4 Feb 2007 14:46:05 -0500 Subject: It is good to blow up a marketplace full of people buying and selling food References: <1170611125.519656.144410@m58g2000cwm.googlegroups.com> Message-ID: <_Jqxh.46014$jA.34196@bignews1.bellsouth.net> It is good to blow up a marketplace full of people buying and selling food in Iraq. This is how Muslim insurgents will drive "the enemy" out of their country. By killing and maiming fellow Iraqis! The traditional Muslim way. The way of Allah! The way of the Quaran! The way of Mohammed! They don't need any democracy. They don't need free elections. They are true believers! Suicide truck bomber kills at least 130 in Baghdad By Tina Susman, Times Staff Writer 11:23 AM PST, February 3, 2007 BAGHDAD -- A suicide bomber posing as a trucker hauling food drove into a busy market in central Baghdad today and blew himself up, killing at least 130 people, injuring more than 300, and capping a particularly volatile day in Iraq's sectarian war. Seven car bombs also tore through the northern city of Kirkuk, leaving two dead in attacks that underscored tensions enveloping the oil-rich region as Arabs and Kurds vie for power. Another person died south of Baghdad in a separate car bombing. The incidents illustrated the breadth of polarization plaguing Iraq as U.S. and Iraqi officials prepare for what they vow will be a decisive crackdown on insurgents. The Interior Ministry said the blast in the market in Sadriya killed at least 130 people and injured 305. It came in the early evening as shoppers thronged the stalls and tiny shops to stock up for the evening meal. Hamed Majed, a butcher, was tending to customers when he saw a large yellow truck trying to navigate down the narrow, alley-like street leading through the market. wrote in message news:1170611125.519656.144410 at m58g2000cwm.googlegroups.com... > First the tiny hezbollah destroyed merkevas one after another using > precision anti-tank weapons reducing the israelis to madness of > indiscriminate cluster bombing. > > But the Iranians are the smartest of these Islamics. Grand chess > masters ... who once saved the ass of jews under Cyrus the Great from > Nebuchadnezzer > > ================= > > Open house at Iranian nuclear site > > Isfahan, Iran > February 5, 2007 > AdvertisementAdvertisement > > Iran has opened one of its nuclear sites to local and international > reporters and ambassadors to show the transparency of its program > before a UN Security Council deadline this month. > > Tehran has kept up efforts to give the site at Isfahan more publicity. > A tourism official said late last year that Iran planned to open it > and other nuclear plants to foreign tourists. > > Iran's ambassador to the International Atomic Energy Agency, Ali > Asghar Soltanieh, said the purpose of the tour was to assure the world > that Iran's program was peaceful. > > "In fact we have representatives from all over the world," Mr > Soltanieh said. "We decided to have them come here and see for > themselves," he said. > > He made a point of emphasising the IAEA surveillance cameras at > Isfahan. > > Photographers and video camera operators were not allowed to take > pictures in the outside area of the compound. > > Uranium ore is converted into yellowcake and gas at Isfahan. The gas > is transferred to the more sophisticated plant at Natanz, where it > could be enriched with centrifuges. > > Reporters at the weekend passed the Natanz site but were not allowed > inside, where Iran recently said it was installing 3000 centrifuges. > > NEW YORK TIMES > From steve at holdenweb.com Sat Feb 10 03:28:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 08:28:28 +0000 Subject: pycallgraph 0.1.0 In-Reply-To: <108b15f0702090719i170c76b9jd17770b4afb53a25@mail.gmail.com> References: <108b15f0702090719i170c76b9jd17770b4afb53a25@mail.gmail.com> Message-ID: Gerald Kaszuba wrote: > On 2/10/07, Stef Mientki wrote: >> ... but isn't "__main__." non-information ? > > Good point -- I'll consider removing it in the next version. > Does the 404 error on http://pycallgraph.slowchop.com/files/examples/mongballs-client.png indicate you are subject to the slashdot effect? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From darren112uk at yahoo.co.uk Sun Feb 11 14:40:45 2007 From: darren112uk at yahoo.co.uk (darren112) Date: 11 Feb 2007 11:40:45 -0800 Subject: help please!! Message-ID: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Hi Im new to python and I desperately need help with this task.... This is everything of what I need to do....... The program to be written in Python obviously...... The program should support brute-forcing of the authentication process for a Telnet server via a dictionary attack. The python program is required to take four parameters: a) the IP address of a Computer, b) the port number that the Telnet server is running on the computer , c) the name of a file containing a list if usernames, and b) the name of a file containing a list of word/phrases to be used as passwords. The program should then attempt to authenticate itself to the Telnet server via trying every password for every username. The program should report when it is successful. Please help me.... And as I am new to all this please post step by step instructions... From ironfroggy at gmail.com Sat Feb 10 17:38:22 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 10 Feb 2007 17:38:22 -0500 Subject: Something like the getattr() trick. In-Reply-To: References: Message-ID: <76fd5acf0702101438q19484482qa37c37bbc81f9aed@mail.gmail.com> This is a really common question. What you really need here is to lookup some value (one of the two classes) by a key (the names of the classes). Does that sound like something familiar? You seem to need a dictionary, where you think you want lookup some global objects by name. Alternatively, if you use new-style classes (by`inheriting the object class in your base class), you could perhaps add a method such as getSubClass() like: class Vuln(object): ... @classmethod def getSubClass(cls, name): for c in cls.__subclasses__(): if c.__name__ == name: return c raise ValueError("No subclass named '%s' found." % name) Of course, this only makes sense if you needs dont extend outside the pattern of looking up subclasses by name. It has the advantage that you can also put the subclasses in other modules and still look them up from one place. On 2/10/07, Ayaz Ahmed Khan wrote: > I'm working with the following class heirarchy (I've snipped out the code > from the classes): > > class Vuln: > def __init__(self, url): > pass > > def _parse(self): > pass > > def get_link(self): > pass > > class VulnInfo(Vuln): > pass > > class VulnDiscuss(Vuln): > pass > > def main(url): > vuln_class = ['Info', 'Discuss'] > vuln = Vuln(url) > vuln._parse() > for link in vuln.get_link(): > i = VulnInfo(link) > i._parse() > d = VulnDiscuss(link) > d._parse() > > > Is there a way to get references to VulnInfo and VulnDiscuss objects using > something like the getattr trick? For example, something like: > > for _class in vuln_class: > class_obj = getattr('Vuln%s' % (_class,) ..) > a = class_obj(link) > a._parse() > > getattr() takes an object as its first argument. I can't seem to figure > out how to make it work here. > > -- > Ayaz Ahmed Khan > > A witty saying proves nothing, but saying something pointless gets > people's attention. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From rubic88 at gmail.com Thu Feb 1 06:19:16 2007 From: rubic88 at gmail.com (Rubic) Date: 1 Feb 2007 03:19:16 -0800 Subject: ctypes error on exit of win32 application In-Reply-To: References: <1170281053.423976.85890@j27g2000cwj.googlegroups.com> Message-ID: <1170328756.482606.205540@s48g2000cws.googlegroups.com> On Jan 31, 8:49 pm, "Gabriel Genellina" wrote: > Maybe process_record expects some minimum buffer size? The cpp example > uses char record[100], but you are allocating only a few bytes with the > string "My Record" No, I've already tried padding record out to the full size. But thank you for the suggestion. -- Jeff Bauer Rubicon, Inc. From jeffrey.aylesworth at gmail.com Mon Feb 26 19:51:29 2007 From: jeffrey.aylesworth at gmail.com (jeff) Date: 26 Feb 2007 16:51:29 -0800 Subject: getting terminal display size? In-Reply-To: <12u4gbepet1ek62@corp.supernews.com> References: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> <12u4g4ci5gqu46c@corp.supernews.com> <12u4gbepet1ek62@corp.supernews.com> Message-ID: <1172537489.610807.288630@p10g2000cwp.googlegroups.com> I don't really understand any of that; can you right me a function that'll return the size as a tuple? From lbates at websafe.com Thu Feb 22 09:47:44 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 22 Feb 2007 08:47:44 -0600 Subject: How to test whether a host is reachable? In-Reply-To: References: Message-ID: Fabian Steiner wrote: > Hello! > > As the subject says I need to test whether a host computer in our > network is reachable or not. At the moment I simply attempt to connect > to a given port that is open when the machine is online: > > [...] > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > try: > sock.connect(('192.168.0.100', 80)) > except socket.error: > print >>sys.stderr "Server offline" > sock.close() > [...] > > Now I am wondering if there isn't any better method which would be more > general. In fact, I think of something like a python version of ping > which only tries to send ICMP packets. However, I don't know what the > code has to look like then. Any ideas or suggestions? > > Thanks, > Fabian Just because you could ping with ICMP packets doesn't mean you could do anything with the machine. I assume that you are connecting to do something on the machine. Just wrap what you are trying to do in try: block. It will either succeed or fail. Handle the exeption. -Larry From mensanator at aol.com Fri Feb 23 17:15:55 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 23 Feb 2007 14:15:55 -0800 Subject: Rational numbers In-Reply-To: <1172260810.779025.135670@j27g2000cwj.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> Message-ID: <1172268954.974348.93540@q2g2000cwa.googlegroups.com> On Feb 23, 2:00 pm, cas... at comcast.net wrote: > On Feb 23, 10:34 am, "mensana... at aol.com" wrote: > > > > > > > On Feb 23, 10:39 am, Martin Manns wrote: > > > > On Fri, 23 Feb 2007 09:52:06 -0600 > > > > Larry Bates wrote: > > > > I quick search of Google turned up: > > > > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p... > > > >http://calcrpnpy.sourceforge.net/clnum.html > > > >http://gmpy.sourceforge.net/ > > > > Sorry that I did not point these out initially. > > > > + clnum seems to be slower and for speed may be compiled to wrap gmp so > > > that it is just an additional layer between python and gmp . > > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of > > > cvs 10 months ago). > > I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex > has not updated cvs with the fix. > > gmpy 1.04a compiles cleanly with the latest releases of Python and > GMP, so I consider it stable. Am I hallucinating? Didn't I see at least some version of gmpy for Python 2.5 on SourceForge awhile back? I distinctly remember thinking that I don't have to direct people to your site, but SourceForge is not showing anything beyond vesion 1.01 for Python 2.4. > > > Actually, gmpy is being maitained even if SourceForge isn't up to > > date. > > > I got my gmpy 1.04a for Python 2.5 Windows binary from > > > > > > I haven't used the rationals all that much, but been very > > happy with them when I have. > > casevh From millerdev at gmail.com Tue Feb 27 23:01:18 2007 From: millerdev at gmail.com (Daniel) Date: 27 Feb 2007 20:01:18 -0800 Subject: boolean flag vs threading.Event In-Reply-To: References: <1172612232.442199.29720@s48g2000cws.googlegroups.com> Message-ID: <1172635278.183187.84350@8g2000cwh.googlegroups.com> > But what are you gaining, really [by using a boolean flag instead of an Event]? I agree Chris, the Event is better and it certainly does not add much if any overhead. Thanks for the response. ~ Daniel From horpner at yahoo.com Fri Feb 2 10:14:29 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 16:14:29 +0100 Subject: newbie/ merging lists of lists with items in common References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: On 2007-02-02, Laurent Pointal wrote: > Neil Cerutti a ?crit : >> On 2007-02-02, ardief wrote: > > >> This is a job for... duhn-duhn-DAAAAH! Captain CHAOS! >> >> Er... I mean itertools.groupby. >> > >> def key_func(t): >> return t[0] > > Not needed: --> from operator import itemgetter I agree. But I used it anyway, to make it easier to see that the sort and the groupby must be and are using the same key function. In this case I admit it's a not a huge readability win, but I was also following the "Do Not Repeat Yourself Rule", which makes the key function easier to refactor. > See in the example: > http://docs.python.org/lib/itertools-example.html > > So much stuff in libraries, so few we know. Thanks to doc > writers, Usenet contributors & Google search engines. Yup. -- Neil Cerutti From broek at cc.umanitoba.ca Thu Feb 8 14:20:03 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 08 Feb 2007 13:20:03 -0600 Subject: doctests for interactive functions Message-ID: <45CB77E3.3040108@cc.umanitoba.ca> Hi all, I have a module of classes for getting input from the user that satisfies various constraints. For instance, one class is created with a menu of option, presents them to the user, and rejects any input other than a menu option; another ensures that the user's input is interpretable as an integer between specified bounds, etc. It is a module I wrote up when in the early stages of learning Python. It's a bit ugly :-) So, I am rewriting it, and this time also am putting in unit tests (I am using doctest). Since the classes are for getting input interactively, a straightforward use of doctest is not going to work. (The tests won't run automatically.) I've come up with a way to make it work, but I would like to know from more experienced people if there are better ways that I am overlooking. All classes take an optional argument input_function that determines how the class instance gets its input. If this is not provided, it defaults to raw_input. doctest tests reassign it so that they can be run automatically. So, an actual interactive session might look like: >>> yn = IG.YesNo() >>> yn.get() Yes or no? What about? You have entered 'What about?'. You must enter a value in ['n', 'no', 'y', 'yes']. (Case does not matter.) Please try again. Yes or no? N >>> yn.data False >>> The corresponding doctest I've constructed looks like: >>> inputs = ['NO', 'What about?'] >>> yn = IG.YesNo() >>> yn.get(input_function=lambda: inputs.pop()) Yes or no? You have entered 'What about?'. You must enter a value in ['n', 'no', 'y', 'yes']. (Case does not matter.) Please try again. Yes or no? >>> yn.data False That works fine as a unit test. But, it doesn't score too well on the `executable documentation' metric, as there is the inputs.pop() in the way, and the user input doesn't make it on to the screen. Is there any way to make the doctests look more like actual interactive sessions, while preserving their automatic runability? Thanks and best, Brian vdB From zefirek at Speacock.Pau.Apoznan.Mpl Tue Feb 27 09:53:41 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Tue, 27 Feb 2007 15:53:41 +0100 Subject: os.system and quoted strings In-Reply-To: <1172586281.606903.79990@s48g2000cws.googlegroups.com> References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> Message-ID: svata wrote: > Hello, > > as I'm new to python I've stumbled accros os.system and its not very > well documented usage. > > I use Win XP Pro and Python 2.5. > > Here is the code snippet: > > -------------------------------------------------------------------------------------------------- > > import time > import os > > dir = "C:\\Documents and Settings\\somepath\\" > fileName = time.strftime("%d%m%Y") > os.system('gvim dir+fileName+".txt"') > > --------------------------------------------------------------------------------------------------- > > The problem is that concatenated variable dir+fileName doesn't get > expanded as expected. > > Is there anything I omitted? > > svata > The way you write it, Python has no idea that dir and fileName are variables, not literal parts of the string. You should put those names outside the quotation marks, or better us the % format operator as Sriram showed you, or even better use os.path module. Here is the reference: http://docs.python.org/lib/module-os.path.html zefciu From mike.klaas at gmail.com Thu Feb 8 21:29:27 2007 From: mike.klaas at gmail.com (Klaas) Date: 8 Feb 2007 18:29:27 -0800 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: Message-ID: <1170988167.356729.187920@v33g2000cwv.googlegroups.com> On Feb 6, 11:07 am, Jean-Paul Calderone wrote: > On Tue, 06 Feb 2007 08:40:40 -0700, Steven Bethard wrote: > >Jean-Paul Calderone wrote: > > > Huge amounts of my pure Python code was broken by Python 2.5. > > >Interesting. Could you give a few illustrations of this? (I didn't run > >into the same problem at all, so I'm curious.) > > There are about half a dozen examples linked from here: > > http://twistedmatrix.com/trac/ticket/1867 > > Check out the closed ticket linked from there or the changesets for more > detail. The changes listed dont' seem particularly huge considering the size, complexity, and boundary-pushingness of Twisted, coupled with the magnitude of the 2.5 release. -Mike From phil at riverbankcomputing.co.uk Thu Feb 8 10:35:33 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 8 Feb 2007 15:35:33 +0000 Subject: Linux-Signal VS QT In-Reply-To: <5c62a320702080708v19f9d5ke3707167c326f7c1@mail.gmail.com> References: <5c62a320702080708v19f9d5ke3707167c326f7c1@mail.gmail.com> Message-ID: <200702081535.33641.phil@riverbankcomputing.co.uk> On Thursday 08 February 2007 3:08 pm, Marco wrote: > Can I use LinuX signal as a tool for commuction with a QT(PyQt4) programme? > > The follow code didNOT work... > > > from PyQt4 import QtCore,QtGui > import signal > import sys > import os > > try: > import psyco > psyco.full() > except: > pass > > class Main(QtGui.QWidget): > def __init__(self): > QtGui.QWidget.__init__(self) > > self.frame = QtGui.QFrame(self) > self.label = QtGui.QLabel(str(os.getpid()), self.frame) > signal.signal(15, self.sig_handler) > print signal.getsignal(15) > > def sig_handler(self, signum, sframe): > print 'received!' > self.label.setText('haha') > self.show() > > ######################## > # main routine # > ######################## > if __name__ == '__main__': > app = QtGui.QApplication(sys.argv) > > main = Main() > main.show() > app.exec_() The problem is that Python only delivers the signal when the interpreter is running but your program is sat in the Qt event loop. You need to force Qt to hand back to the interpreter from time to time. The easiest way is to use the object timer. Add "self.startTimer(500)" to your __init__() method and add the following dummy timer event handler... def timerEvent(self, e): pass Phil From deets at nospam.web.de Fri Feb 23 12:54:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Feb 2007 18:54:55 +0100 Subject: Local class variables? (mod_python problem) References: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> <20070222154239.GA12709@campbell-lange.net> <548ageF1u22afU1@mid.uni-berlin.de> Message-ID: <548o3fF202cd0U1@mid.uni-berlin.de> > > Many thanks for your reply. The use case is per request, and I would be > grateful to learn more about thread-local storage. There are several ways. I'm not familiar with mod_python, but I guess you get a dict-like object for the request parameters. In python, this is usually writable (in contrast to the darn J2EE-spec'ed HttpRequest) So just add a new key, e.g. "working_state", to it. Under that, file those variables. Alternatively, there are recipes out there (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302088 ) that give you basically a dictionary keyed with the current thread. That is helpful if you have computations deeper in code that can't get a hold on the request object. Might be the case in mod_python - in cherrypy, the request itself is thread-locally stored, so you can get it whereever you need. Diez From steve at holdenweb.com Sat Feb 10 06:50:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 11:50:52 +0000 Subject: Wait for keypress In-Reply-To: <1171107456.651569.101680@q2g2000cwa.googlegroups.com> References: <1171107456.651569.101680@q2g2000cwa.googlegroups.com> Message-ID: TheOneRedDragon at gmail.com wrote: > At the moment, I have a command-line application which prints out > quite a lot of text to the screen. > However, when Windows users run it, the prompt disappears before they > can read any of it. > Is there any simple way to make a script wait for a keypress before > completing? > Thanks for any help. > At the end of your program just add: raw_input("Press Enter to terminate") regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From http Wed Feb 28 02:00:50 2007 From: http (Paul Rubin) Date: 27 Feb 2007 23:00:50 -0800 Subject: Yet another unique() function... References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <7x8xej80a5.fsf@ruckus.brouhaha.com> <7xzm6z6lf4.fsf@ruckus.brouhaha.com> <1172643281.565788.12380@8g2000cwh.googlegroups.com> Message-ID: <7xslcqwyu5.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > Any reason not to use a set for the 'seen' variable? Yes, the sequence can contain non-hashable elements. See the test vectors for examples. From duncan.booth at invalid.invalid Mon Feb 5 13:12:59 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Feb 2007 18:12:59 GMT Subject: Python compiled on Windows References: Message-ID: Franz Steinhaeusler wrote: > Hello, I'm only curious. > > Why is Python and most extension (also wxPython) not built using an > open source compiler like gcc or g++ on Windows? > > I'm always wondering, why Microsoft is still supported > in that way, using VC++ 7.1, if I'm not wrong. > > Ok, maybe the compiled assembler code could be better, but > this cannot be the reason, or? > > It would be wonderful (from the principle) if this could be possible. > From the standpoint of open source. > > What are your opinions? Practicality beats purity. To maximise the interoperability of Python with other software on the platform it makes sense to use the best supported compiler environment for the platform. From arkanes at gmail.com Tue Feb 20 10:26:24 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 20 Feb 2007 09:26:24 -0600 Subject: wxPython: non-GUI thread launching new frame? Delegates? In-Reply-To: <5405fnF1upuuoU1@mid.uni-berlin.de> References: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> <5405fnF1upuuoU1@mid.uni-berlin.de> Message-ID: <4866bea60702200726k5d43b805h29211be19a8b2924@mail.gmail.com> On 2/20/07, Diez B. Roggisch wrote: > cyberco wrote: > > > In my wxPython app a non-GUI thread (that reads info from the network) > > tries to open a frame to show the new info. This results in my app > > hanging (which is not too surprising). Coming from a C# environment I > > wonder if there is some sort of delegate mechanism in wxPython to do > > this sort of thing. > > Not sure how wx deals with this, but one thing you might explore is the > possibility to add a timer in the GUI-thread, that polls a thread-filled > queue. > > Other toolkits as Qt have means to insert an extra event in the event queue > of the gui-thread in a thread-agnostic way, maybe wx has that too. > > Googling... > ... > ... > ... > > ... finished > > http://mail.python.org/pipermail/python-list/2005-August/335467.html > > """ > You need another way to pass completion information between the downloader > thread and the main thread; the simplest way is to define a custom wx > Event, and wxPostEvent from the downloader thread when it completes ( > and when the gauge should be updated). wxPostEvent is safe to call from > non-eventloop threads. > The main thread's wx event loop just spins, properly updating all other > parts of the GUI, and receiving events from the downloader thread. > > ANother approach is to have a thread-safe Queue and have the main > thread/event loop > poll the queue with queue.get_nowait() periodically (typically 0.1-1 sec). > The downloader thread shares the queue object and puts data structures > (typically > class instances, strings, or ints) that indicate status updates. > """ > > So - both options a viable. And read to the end, the twisted-approach > certainly is the most clean one. > This is rather out of date. wxPython provides a wx.CallAfter function, which will call the passed callable on the next spin through the event loop. It's essentially a wrapper around the custom event mechanism described above. > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From morpheus at spamhater.too Mon Feb 19 02:03:27 2007 From: morpheus at spamhater.too (Morpheus) Date: Mon, 19 Feb 2007 08:03:27 +0100 Subject: How to detect closing of wx.Panel? References: Message-ID: On Mon, 19 Feb 2007 01:18:11 +0000, Jacol wrote: > Hi everybody, > > I have poblem with detecting closing of wx.Panel by user. How to detect that > event? > Don't know why you want to do that, but you could register with the enclosing (hosting) widget. > The wx.EVT_CLOSE event concerns wx.Frame class only. Neither Close() nor > Destroy() aren't executed if the event occurs (if user close a panel). Thus > extanding these both methods doesn't make sens (I've tested that). > > With many thanks & > Best wishes, > Jacek Cheers Morpheus From jura.grozni at gmail.com Fri Feb 9 01:43:18 2007 From: jura.grozni at gmail.com (azrael) Date: 8 Feb 2007 22:43:18 -0800 Subject: Thanks for the help In-Reply-To: References: Message-ID: <1171003398.302212.232790@m58g2000cwm.googlegroups.com> On Feb 9, 4:06 am, "Reid" wrote: > Hello All > > Thanks for taking the time to answer my question. I do not need 3d stuff. > Just a couple of buttons and menu's. The reason I am looking at python is it > is free to download. I cannot afford VB or other commercial languages. > > Reid there is also other free stuff. c, c++, c#, java,...... i also prefere python. i don't want to bring you to stupid ideas, but what about illegal software. if there is a will to use something there is also a way to do it From elgrandchignon at gmail.com Mon Feb 26 21:44:17 2007 From: elgrandchignon at gmail.com (elgrandchignon at gmail.com) Date: 26 Feb 2007 18:44:17 -0800 Subject: Probably somewhat silly newbie question Message-ID: <1172544257.686173.180650@p10g2000cwp.googlegroups.com> Hi all-- Trying to learn Python w/little more than hobbyist (bordering on pro/ am, I guess) Perl as a background. My problem is, I have a list of departments, in this instance, things like "Cheese", "Bakery", et al. (I work @ a co-op health food store). I've populated a list, 'depts', w/these, so that their indexes match our internal indexing (which skips a few #'s). Now, I'd like to simply generate-- and be able to refer to-- a bunch of other lists-sets (for subdepartments) by iterating through this list, and naming each of these subdepartment lists "categoryx", where x is the index # from the master 'depts' list. And then be able to populate & refer to these lists by accessing their variable-including name. In Perl, it's a fairly trivial matter to use a string variable in naming some other kind of variable-- not sure about Python though. My initial, very weak stab at it (don't laugh!) went something like this: for i in range(len(depts)): if depts[i]: categorylistdeptname = 'category' + str(i) categorylistdeptname = [] Not sure what that wound up doing, but it sure didn't seem to work. I'm mean, it's trivial enough to just set up the lists manually; 'category1 = []', 'category2 = []' -- but then, when I'm cycling through the item file-- which contains one field that's a list of subdepartments for the item, & another field w/the item's dept #, I would like to be able to just append new subdept's into whichever categorylist is indicated by the files department #. Hope that's sorta clear. Maybe I'm just SOL, but I thought I'd try asking around before I go crawling back to Perl w/my tail tucked between my legs.... From sjmachin at lexicon.net Sat Feb 10 09:54:19 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 11 Feb 2007 01:54:19 +1100 Subject: ANN: Cheesecake Service launched and Cheesecake 0.6.1 released In-Reply-To: <1171064065.620129.25630@j27g2000cwj.googlegroups.com> References: <1171064065.620129.25630@j27g2000cwj.googlegroups.com> Message-ID: <45CDDC9B.6000908@lexicon.net> On 10/02/2007 10:34 AM, Grig Gheorghiu wrote: > Thanks to the hard work of Michal Kwiatkowski, I'm proud to announce > the launch of the Cheesecake Service ( pypi/>) and the release of Cheesecake 0.6.1 (). It appears to be missing (1) a Python 2.5 egg (2) a Windows installer Regards, John From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 15:49:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 21:49:40 +0100 Subject: Object type check In-Reply-To: <1170867552.247093.198800@j27g2000cwj.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> Message-ID: <45ca3444$0$18985$426a74cc@news.free.fr> king kikapu a ?crit : >>Dont restrict them to particular types. You would >>not restrict them to a particular class in C#. Instead, you define the >>interfaces simply by how you use the objects. > > > Of cource i restrict them to particular types! In C# you cannot pass > something bad > this way because the compiler will just catch it! This won't prevent some stupid to implement the interface with a totally different semantic (what about some getter wiping out your hard drive ?). FWIW, in Python, you can't pass something bad because it will raise an exception. Well, to be true, there's *one* gotcha : passing a string where a list or tuple is expected may in some occasions yield strange results (strings being sequences too). > I see what you mean by "duck typing". So you suggest the "do nothing > at all" direction, > better document my code so other can see what is expected, right ? Exactly. From jonc at icicled.net Sun Feb 11 15:27:33 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sun, 11 Feb 2007 14:27:33 -0600 Subject: help please!! In-Reply-To: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> References: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Message-ID: <200702111427.33143.jonc@icicled.net> On Sunday 11 February 2007 13:40, darren112 wrote: > Hi Im new to python and I desperately need help with this task.... > This is everything of what I need to do....... > > The program to be written in Python obviously...... > > The program should support brute-forcing of the authentication process > for a Telnet server via a dictionary attack. > > The python program is required to take four parameters: a) the IP > address of a Computer, b) the port number that the Telnet server is > running on the computer , c) the name of a file containing a list if > usernames, and b) the name of a file containing a list of word/phrases > to be used as passwords. > > The program should then attempt to authenticate itself to the Telnet > server via trying every password for every username. The program > should report when it is successful. > > Please help me.... And as I am new to all this please post step by > step instructions... /me points and laughs at you. Hahahahaha, stupid script kiddie. Get a life. From apardon at forel.vub.ac.be Tue Feb 13 10:24:29 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Feb 2007 15:24:29 GMT Subject: can't find a way to display and print pdf through python. References: Message-ID: On 2007-02-11, krishnakant Mane wrote: > hello all, > I am stuck with a strange requirement. > I need a library that can help me display a pdf file as a report and > also want a way to print the same pdf file in a platform independent > way. > if that's not possible then I at least need the code for useing some > library for connecting to acrobat reader and giving the print command > on windows and some thing similar on ubuntu linux. > the problem is that I want to display reports in my application. the > user should be able to view the formatted report on screen and at his > choice click the print button on the screen to send it to the printer. > I have reportlab installed and that is sufficient to generate pdf reports. > but I still can't fine the way to display it directly and print it directly. > Please help me. > Krishnakant. I think the best way to handle this under a unix like system is by using the mailcap module, something like the following: import mailcap import os mc = mailcap.getcaps() cmd = mailcap.findmatch(mc, 'image/pdf' , filename='/tmp/dummy')[0] os.system(cmd) -- Antoon Pardon From djbclark at gmail.com Fri Feb 9 15:55:46 2007 From: djbclark at gmail.com (Daniel Clark) Date: 9 Feb 2007 12:55:46 -0800 Subject: Sending CTRL-C event to console application In-Reply-To: <1171030321.710838.187470@k78g2000cwa.googlegroups.com> References: <1170960845.457806.27260@p10g2000cwp.googlegroups.com> <1171030321.710838.187470@k78g2000cwa.googlegroups.com> Message-ID: <1171054546.786383.318080@a34g2000cwb.googlegroups.com> On Feb 9, 9:12 am, "Daniel Clark" wrote: > I'm going to try taking a different approach by using a GUI Automation > tool like WATSUP [1] or pywinauto[2] next. This works: AutoIT [1] code (compiled to an executable): Run(@ComSpec & ' /k ' & $CmdLineRaw ) This was necessary because other means of starting cmd.exe didn't actually spawn a new window. Syntax is just like: C:\> autoitrun.exe "cd c:\Program Files\Tivoli\TSM & dir /s/p" And that will pop up a new cmd.exe window with a dir /s/p listing of cd c:\Program Files\Tivoli\TSM Python code (changes service to be able to interact with desktop and then runs the above): import win32service import os, sys def EnsureInteractiveService(servicename): scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: svc = win32service.OpenService(scm, servicename, win32service.SC_MANAGER_ALL_ACCESS) except: print '''Error: Couldn't open service with name "''' + servicename + '''"''' sys.exit(1) oldsvccfg = win32service.QueryServiceConfig(svc) win32service.ChangeServiceConfig(svc, # scHandle oldsvccfg[0] | win32service.SERVICE_INTERACTIVE_PROCESS, # serviceType oldsvccfg[1], # startType oldsvccfg[2], # errorControl oldsvccfg[3], # binaryFile oldsvccfg[4], # loadOrderGroup oldsvccfg[5], # bFetchTag oldsvccfg[6], # serviceDeps oldsvccfg[7], # acctName '', # password oldsvccfg[8]) # displayName win32service.CloseServiceHandle(svc) win32service.CloseServiceHandle(scm) EnsureInteractiveService("TSM for WPLC") os.chdir("c:\\Program Files\\WPLC-TSM\\updates") os.system("autoitrun.exe dir /s/p") [1] AutoIt v3 - Automate and Script Windows Tasks http://www.autoitscript.com/autoit3/ From jamiebohr at gmail.com Thu Feb 15 22:16:34 2007 From: jamiebohr at gmail.com (Jamie Bohr) Date: Thu, 15 Feb 2007 20:16:34 -0700 Subject: PIL problems Message-ID: I am trying to allow JPEG's to be used for portraits inside of Plone. I have Googled and found I need to install the Pytphon Imaging Library (PIL); after that all should be good. I did that, but I an error that tells me there is a missing library. The below is a log of what I did. From what I can tell Python sees the library but .. (I'm used to Perl so I have no idea). I am working on a RHEL v4 x64 system. Thank you in advance for your time. Error Value decoder jpeg not availableHere is the log of me installing PIL: $ sudo /opt/python/bin/python setup.py install running install running build running build_py running build_ext -------------------------------------------------------------------- PIL 1.1.6 BUILD SUMMARY -------------------------------------------------------------------- version 1.1.6 platform linux2 2.4.3 (#1, Jan 30 2007, 15:38:40) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] -------------------------------------------------------------------- *** TKINTER support not available --- JPEG support ok --- ZLIB (PNG/ZIP) support ok *** FREETYPE2 support not available *** Warning: zlib 1.2.1.2 may contain a security vulnerability. *** Consider upgrading to zlib 1.2.3 or newer. *** See: http://www.kb.cert.org/vuls/id/238678 http://www.kb.cert.org/vuls/id/680620 http://www.gzip.org/zlib/advisory-2002-03-11.txt -------------------------------------------------------------------- To add a missing option, make sure you have the required library, and set the corresponding ROOT variable in the setup.py script. To check the build, run the selftest.py script. running build_scripts running install_lib running install_scripts changing mode of /opt/python/bin/pilprint.py to 755 changing mode of /opt/python/bin/pilconvert.py to 755 changing mode of /opt/python/bin/pilfont.py to 755 changing mode of /opt/python/bin/pildriver.py to 755 changing mode of /opt/python/bin/pilfile.py to 755 creating /opt/python/lib/python2.4/site-packages/PIL.pth $ $ sudo /opt/python/bin/python selftest.py ***************************************************************** Failure in example: _info(Image.open("Images/lena.jpg")) from line #24 of selftest.testimage Exception raised: Traceback (most recent call last): File "./doctest.py", line 499, in _run_examples_inner exec compile(source, "", "single") in globs File "", line 1, in ? File "./selftest.py", line 22, in _info im.load() File "PIL/ImageFile.py", line 180, in load d = Image._getdecoder( self.mode, d, a, self.decoderconfig) File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. $ $ /opt/python/bin/python -vv -c "import PIL._imaging" 2>&1 | less .... # PIL/__init__.pyc matches PIL/__init__.py import PIL # precompiled from PIL/__init__.pyc # trying PIL/_imaging.so dlopen("PIL/_imaging.so", 2); import PIL._imaging # dynamically loaded from PIL/_imaging.so # clear __builtin__._ # clear sys.path .... -- Jamie Bohr -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncanm255 at hotmail.com Fri Feb 2 14:29:05 2007 From: duncanm255 at hotmail.com (D) Date: 2 Feb 2007 11:29:05 -0800 Subject: Tkinter Scrolling In-Reply-To: References: <1170333328.141317.275130@q2g2000cwa.googlegroups.com> <2007020112161316807-bob@passcalnmtedu> <1170357968.405171.14410@h3g2000cwc.googlegroups.com> Message-ID: <1170444545.239660.286280@s48g2000cws.googlegroups.com> > Here you are: > > ----------------------------------------------------------- > from Tkinter import * > > ## Main window > root = Tk() > ## Grid sizing behavior in window > root.grid_rowconfigure(0, weight=1) > root.grid_columnconfigure(0, weight=1) > ## Canvas > cnv = Canvas(root) > cnv.grid(row=0, column=0, sticky='nswe') > ## Scrollbars for canvas > hScroll = Scrollbar(root, orient=HORIZONTAL, command=cnv.xview) > hScroll.grid(row=1, column=0, sticky='we') > vScroll = Scrollbar(root, orient=VERTICAL, command=cnv.yview) > vScroll.grid(row=0, column=1, sticky='ns') > cnv.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll.set) > ## Frame in canvas > frm = Frame(cnv) > ## This puts the frame in the canvas's scrollable zone > cnv.create_window(0, 0, window=frm, anchor='nw') > ## Frame contents > for i in range(20): > b = Button(frm, text='Button n#%s' % i, width=40) > b.pack(side=TOP, padx=2, pady=2) > ## Update display to get correct dimensions > frm.update_idletasks() > ## Configure size of canvas's scrollable zone > cnv.configure(scrollregion=(0, 0, frm.winfo_width(), frm.winfo_height())) > ## Go! > root.mainloop() > ----------------------------------------------------------- > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" Thanks, Eric - exactly what I needed! From horpner at yahoo.com Thu Feb 15 15:44:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Feb 2007 21:44:28 +0100 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: On 2007-02-15, Gabriel Genellina wrote: >> I'm not sure what you mean. The above support is enough for >> tail recursion, mutual recursion, and any other tail call to >> be "optimized." > > I only want to say that tail *recursion* can be eliminated > trivially transforming the code into a while loop, and that > can be done by the programmer, and doesn't require compiler > support. Head *recursion* can be eliminated too by using some > storage as temporary stack, and that doesn't require external > support either. Mutual recursion (and generic tail call > elimination) require some sort of external support: one can't > eliminate the call just by transforming the program. Ah, I see now. Had my blinders on. -- Neil Cerutti Low Self-Esteem Support Group will meet Thursday at 7 to 8:30 p.m. Please use the back door. --Church Bulletin Blooper From jonc at icicled.net Sun Feb 11 14:33:22 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sun, 11 Feb 2007 13:33:22 -0600 Subject: Pyhton script In-Reply-To: <8912801.post@talk.nabble.com> References: <8912801.post@talk.nabble.com> Message-ID: <200702111333.22677.jonc@icicled.net> On Sunday 11 February 2007 11:47, soussou97 wrote: > Hi; > > I would like to automatically delivery, I seek a script in python which > will be excecute from a Windows station to allows via sftp: > > 1- to connect to a Linux server for storing of the files > 2- Next execute on the Linux server, some actions: Copy, gzip, mv etc... > 3- to use a config file for the parameters: server name, login, password... > > Regards; > -- > View this message in context: > http://www.nabble.com/Pyhton-script-tf3209528.html#a8912801 Sent from the > Python - python-list mailing list archive at Nabble.com. Just joking with the last message, though I hope that you weren't looking for someone to just send it to you. Take a look at Paramiko, it's exactly the library you need to do these things. - Jonathan From cyberco at gmail.com Tue Feb 20 06:19:45 2007 From: cyberco at gmail.com (cyberco) Date: 20 Feb 2007 03:19:45 -0800 Subject: wxPython: non-GUI thread launching new frame? Delegates? Message-ID: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> In my wxPython app a non-GUI thread (that reads info from the network) tries to open a frame to show the new info. This results in my app hanging (which is not too surprising). Coming from a C# environment I wonder if there is some sort of delegate mechanism in wxPython to do this sort of thing. 2B From bj_666 at gmx.net Fri Feb 23 13:41:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 23 Feb 2007 19:41:04 +0100 Subject: Finding non ascii characters in a set of files References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> <1172243566.906121.189930@h3g2000cwc.googlegroups.com> Message-ID: In , Tim Arnold wrote: > Here's what I do (I need to know the line number). > > import os,sys,codecs > def checkfile(filename): > f = codecs.open(filename,encoding='ascii') > > lines = open(filename).readlines() > print 'Total lines: %d' % len(lines) > for i in range(0,len(lines)): > try: > l = f.readline() > except: > num = i+1 > print 'problem: line %d' % num > > f.close() I see a `NameError` here. Where does `i` come from? And there's no need to read the file twice. Untested: import os, sys, codecs def checkfile(filename): f = codecs.open(filename,encoding='ascii') try: for num, line in enumerate(f): pass except UnicodeError: print 'problem: line %d' % num f.close() Ciao, Marc 'BlackJack' Rintsch From jeff.templon at gmail.com Wed Feb 21 15:59:33 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 21 Feb 2007 12:59:33 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: <1172084764.953839.238660@s48g2000cws.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> <1172084764.953839.238660@s48g2000cws.googlegroups.com> Message-ID: <1172091572.962804.317940@v33g2000cwv.googlegroups.com> On Feb 21, 8:06 pm, olso... at verizon.net wrote: > I don't know the specifics of your app, but why does everyone insist > that they need to use the 'system' python? Hey Grant, don't worry it's not a rant. A completely valid question. Again it's a problem of dependency management ... one of the things we've had to deal with is one of the applications : they have a framework largely built in python, and I think they were indeed at one point shipping their own python because they used features not present in the "system" python. However, they did use the middleware installed on the system, and this middleware is also partially written in python ... except it was expecting the system python. So you get into very tricky things having to sanity check the PYTHONPATH, that the "user" python path is not getting exported into middleware land, nor is the application's desired PYTHONPATH being destroyed by middleware. We had just such an issue here last week, we had solved the problem for bourne shell users, but csh for some reason had a different behavior, and the user app could not longer find its python modules. About the only code for which we don't seem to have these issues is compiled C. C++ is nasty because the compilers are still catching up to the standard; the last I heard, a big segment of C++ code was stuck because it was full of apparently illegal constructs that the previous compiler (the g++ shipped stock with RHEL3) accepted, but the RHEL-4 native version refused to compile. A colleague of mine pointed out today that this is an old problem, and used to be handled by automake at compile time, with code full of ifdefs ... now we've moved the problem to run time. Which I think is harder, because sometimes we don't find the problem until our binary is halfway across the world ... JT From gagsl-py at yahoo.com.ar Mon Feb 19 19:49:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 21:49:53 -0300 Subject: search cursor in pythonwin 2.1 References: <1171815140.829723.87940@a75g2000cwd.googlegroups.com> <1171898487.585051.125470@q2g2000cwa.googlegroups.com> Message-ID: En Mon, 19 Feb 2007 12:21:27 -0300, GISDude escribi?: > Thanks for the reply. After looking at the docs again, you are correct > "NAMES" IS NOT NULL would be the correct syntax. > > I thought it was "NAMES" <> NULL Python has some gotchas like default mutable arguments, that will catch the novice. SQL has its NULL behavior on expressions... -- Gabriel Genellina From grante at visi.com Tue Feb 20 15:22:03 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 20 Feb 2007 20:22:03 -0000 Subject: wxPython: non-GUI thread launching new frame? Delegates? References: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> <5405fnF1upuuoU1@mid.uni-berlin.de> <1172001661.882918.193600@l53g2000cwa.googlegroups.com> Message-ID: <12tmm3b4jeoss92@corp.supernews.com> On 2007-02-20, cyberco wrote: > Ah! Great tip, thanks! > Now instead of calling: > > parent.onRequest(param) > > I call: > > wx.CallAfter(lambda x: parent.onRequest(x), param) How does that differ from this? wx.CallAfter(parent.onRequest, param) -- Grant Edwards grante Yow! .. Everything at is....FLIPPING AROUND!! visi.com From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 15:57:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 28 Feb 2007 21:57:27 +0100 Subject: class declaration shortcut In-Reply-To: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> Message-ID: <45e5e4eb$0$9541$426a74cc@news.free.fr> Luis M. Gonz?lez a ?crit : > I've come across a code snippet in www.rubyclr.com where they show how > easy it is to declare a class compared to equivalent code in c#. > I wonder if there is any way to emulate this in Python. > > The code is as follows: > > Person = struct.new( :name, :birthday, :children) s/struct/Struct/ > I tried something like this, but it's nothing close to what I'd like: > > def klass(table, *args): > cls = new.classobj(table, (), {}) > for i in args: > setattr(cls, i, i) > return cls > > But this above is not what I want. > I guess I should find a way to include the constructor code inside > this function, but I don't know if this is possible. > Also, I wonder if there is a way to use the variable name in order to > create a class with the same name (as in "Person"above). > > Well, if anyone has an idea, I'd like to know... Here's a *very* Q&D attempt - that doesn't solve the name problem: def Struct(name, *attribs): args = ", ".join("%s=None" % attr for attr in attribs) body = "\n ".join("self.%s = %s" % (attr, attr) \ for attr in attribs) source = (""" class %s(object): def __init__(self, %s): %s """.strip()) % (name, args, body) #print source code = compile(source, 'dummy', 'single') exec code return locals()[name] But note that I'd immediatly fire anyone using such an abomination in production code. From danielkleinad at gmail.com Sun Feb 18 07:58:32 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Sun, 18 Feb 2007 12:58:32 GMT Subject: Getting a class name References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <_DJBh.20322$K8.18088@news.edisontel.com> <1171801487.767555.14150@v33g2000cwv.googlegroups.com> Message-ID: <2ajgt25h04etmlou1fpq3phemt9de4sr7n@4ax.com> On 18 Feb 2007 04:24:47 -0800, "Fuzzyman" wrote: >On Feb 17, 8:33 pm, deelan wrote: >> Harlin Seritt wrote: >> > Hi, >> >> > How does one get the name of a class from within the class code? I >> > tried something like this as a guess: >> >> > self.__name__ >> >> Get the class first, then inspect its name: >> >> >>> class Foo(object): pass >> ... >> >>> f = Foo() >> >>> f.__class__.__name__ >> 'Foo' >> >>> >> > > >Why is the __name__ attribute not available to the instance? Why don't >normal lookup rules apply (meaning that a magic attribute will be >looked up on the class for instances) ? Good question! >>> f = Foo() >>> dir(f) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> dir(f.__class__) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> Where is '__name__' ? Dan From fccoelho at gmail.com Thu Feb 22 08:50:36 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 05:50:36 -0800 Subject: plugin development best practices In-Reply-To: References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> Message-ID: <1172152236.733508.233470@q2g2000cwa.googlegroups.com> On Feb 22, 11:01 am, Jean-Paul Calderone wrote: > On 22 Feb 2007 04:53:02 -0800, Flavio wrote: > > >Hi, > > >Nowadays the addition of functionality to programs by means of > >plugins is very frequent. > > >I want to know the opinions of experienced Python developers about the > >best practices when it comes to developing a plugin system for a > >Python package. > > >Should plugins be modules in a separate package? > >Should there be a registry of available plugins? how would such a > >registry be implemented? etc. > > >thanks, > > Best practice may be to not develop a new plugin system. There are quite a > few available already. Most likely, at least one of them is suitable for your > application. > > Here are a couple starting points: > > http://twistedmatrix.com/projects/core/documentation/howto/plugin.html > > http://peak.telecommunity.com/DevCenter/setuptools#dynamic-discovery-... > > Jean-Paul The plugin system provided by twisted looks interesting (though not as simple as it could be, IMHO). Its main problem is that it introduces two dependencies : Twisted plugin and ZopeInterface. I think a functional plugin system could(and should) be done using only the standard library. Fl?vio From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 17:49:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 23:49:15 +0100 Subject: LDAP/LDIF Parsing In-Reply-To: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> Message-ID: <45c26772$0$4272$426a74cc@news.free.fr> Cruelemort a ?crit : > All, > > I am hoping someone would be able to help me with a problem. I have an > LDAP server running on a linux box, this LDAP server contains a > telephone list in various groupings, the ldif file of which is - > (snip) > > I am creating a python client program that will display the telephone > list in the same directory structure as is on the LDAP server (i.e. it > starts with buttons of all the groups, when you click on a group it > comes up with buttons of all the numbers or groups available, and you > can continually drill down). > > I was wondering the best way to do this? I have installed and used the > python-ldap libraries and these allow me to access and search the > server, but the searches always return a horrible nesting of lists, > tuples and dictionaries, below is an example of returning just one > record - > > ('dc=example,dc=com', {'objectClass': ['top', 'dcObject', > 'organization'], 'dc': ['example'], 'o': ['Example Organisation']}) What's your problem ? That's exactly what your ldap record should look like. A (base_dn, record) tuple, where the record is a dict of attribute_name:[values, ...] > Basically i think i need to parse the search results to create objects Q&D wrapper: class LdapObject(object): def __init__(self, ldapentry): self.dn, self._record = ldapentry def __getattr__(self, name): try: data = self._record[name] except KeyError: raise AttributeError( "object %s has no attribute %s" % (self, name) ) else: # all LDAP attribs are multivalued by default, # even when the schema says they are monovalued if len(data) == 1: return data[0] else: return data[:] def isa(self, objectClass): return objectClass in self.objectClass: root = LdapObject( ('dc=example,dc=com', {'objectClass': ['top', 'dcObject','organization'], 'dc': ['example'], 'o': ['Example Organisation']} )) root.o => 'Example Organisation' root.objectClass => ['top', 'dcObject','organization'] root.isa('organization') => True FWIW, I once started writing an higher-level LDAP api (kind of an Object-LDAP Mapper...) using descriptors for ldap attribute access, but I never finished the damned thing, and it's in a very sorry state. I'll have to get back to it one day... > and build the python buttons around this, but i was hoping someone > would be able to point me in the correct direction of how to do this? > Is there a parser available? cf above. From ms at cerenity.org Fri Feb 2 05:37:29 2007 From: ms at cerenity.org (Michael) Date: Fri, 02 Feb 2007 10:37:29 +0000 Subject: Python design project References: <1170337417.236975.44070@l53g2000cwa.googlegroups.com> Message-ID: <45c313d5$0$8726$ed2619ec@ptn-nntp-reader02.plus.net> solrick51 at hotmail.com wrote: .. > I'm a Dutch student, and graduating this year on my graphic design > study. For my graduating study, I want to do some Python work and i'm > lokking for a partner wich can help/ cooperate me in programming > python. > > The project > In short: The project subject is type, and i want to create a self > generating type. At the risk of asking a stupid question, what do you mean by a self generating type? (Indeed, what do you mean by "type" here?) Given the phrases "python" and "graphic design" in the same post I can think of at least two definitions of "type" that are relevant, and not sure how you'd view either as self-generating :-) Curiously, Michael. From sergey at fidoman.ru Wed Feb 14 15:58:18 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Wed, 14 Feb 2007 23:58:18 +0300 Subject: f---ing typechecking Message-ID: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> (1,)+[1] Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate tuple (not "list") to tuple >>> [1]+(1,) Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate list (not "tuple") to list >>> Its ugly and boring. From mfmdevine at gmail.com Wed Feb 14 07:08:38 2007 From: mfmdevine at gmail.com (amadain) Date: 14 Feb 2007 04:08:38 -0800 Subject: replacing substrings within strings Message-ID: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> Hi I was wondering if there was a nicer way to swap the first 2 characters in a string with the 4th and 5th characters other than: darr=list("010203040506") aarr=darr[:2] barr=darr[4:6] darr[:2]=barr darr[4:6]=aarr result="".join(darr) The above code works fine but I was wondering if anybody had another way of doing this? A From duncan.booth at invalid.invalid Wed Feb 28 05:28:29 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Feb 2007 10:28:29 GMT Subject: os.system and quoted strings References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> <1172627614.008588.176800@p10g2000cwp.googlegroups.com> Message-ID: "Dan Bishop" wrote: > Windows system calls treat / and \ interchangeably, but the command > prompt insists on backslashes. No. Commands built-in to the command prompt and certain other programs (mostly but not exclusively from Microsoft) insist on backslashes. Most programs, especially those originating from the unixverse, will accept backslashes and forward slashes interchangeably from the command prompt. Even a lot of Microsoft's own programs are happy to accept backslashed command line arguments. If in doubt just call os.path.normpath() on a path string before using it. Also it is usually worth putting command line arguments inside " marks to avoid problems with spaces or other special characters in path names. From jstroud at mbi.ucla.edu Sat Feb 17 13:03:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 17 Feb 2007 18:03:31 GMT Subject: WHAT IS THIS? In-Reply-To: References: Message-ID: Captain wrote: > Just bought a new PC with Windows XP Media Edition. I have two entries in > the "Add or Remove Programs" section of Control Panel, but there is no > corresponding item in the Start Menu. One entry says: Python 2.2.3 and the > other says: Python 2.2 pywin32 extensions (build203).. The size for each is > 29.28mb. I gather Python is a programming language, but I am wondering why > it was installed on my PC, and is it safe to remove it? I have no intention > of learning the program. Thanks in advance > > Better would be to remove windows xp and get another operating system. James From http Thu Feb 8 03:29:23 2007 From: http (Paul Rubin) Date: 08 Feb 2007 00:29:23 -0800 Subject: Referencing vars, methods and classes by name References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> Message-ID: <7xbqk52gt8.fsf@ruckus.brouhaha.com> "Sagari" writes: > $a = ''b'; > $$a = $something; // assign to $b > $$a($p1); // call function b($p1) > $obj->$a(); // call method b() of the instance $obj > > What is the Python way of performing the same indirections? We would not do that. We don't (usually) use the interpreter symbol table as a dictionary (what in perl would be called a hash). Instead we use an actual dictionary. We might say d = {} # make an empty dictionary a = 'b' d[a] = something # assign to d['b'] some_functab[a](p1) # look up 'b' in some function table and call it For your last example we could say obj.getattr(a)() but even that is a bit ugly, depending. For your other examples there are gross hacks using the dictionaries that represent the local and global symbol tables, so we translate your examples fairly directly, but stylistically we'd usually stay away from that kind of thing. From http Sun Feb 11 12:43:53 2007 From: http (Paul Rubin) Date: 11 Feb 2007 09:43:53 -0800 Subject: randomly generate n of each of two types References: Message-ID: <7x64a8vbc6.fsf@ruckus.brouhaha.com> "Alan Isaac" writes: > I need access to 2*n random choices for two types > subject to a constraint that in the end I have > drawn n of each. I first tried:: You mean you basically want to generate 2*n bools of which exactly half are True and half are False? Hmm (untested): from random import random def random_types(n): total = 2*n trues_needed = n for i in xrange(total): if random() < float(trues_needed) / float(total): trues_needed -= 1 yield True else: yield False total -= 1 From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Feb 27 19:19:57 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 28 Feb 2007 01:19:57 +0100 Subject: how to convert an integer to a float? References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Message-ID: <54k05cF218n10U1@mid.individual.net> yinglcs at gmail.com wrote: > def compareValue(n1, n2): > i1 = int(n1) > i2 = int(n2) > > dx = abs(i2 - i1)/min(i2, i1) > print dx > return dx < 0.05 You could also prepend from __future__ import division Regards, Bj?rn -- BOFH excuse #237: Plate voltage too low on demodulator tube From http Mon Feb 5 10:54:07 2007 From: http (Paul Rubin) Date: 05 Feb 2007 07:54:07 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> <1168189375.843789.306180@51g2000cwl.googlegroups.com> <7xps9q19wf.fsf@ruckus.brouhaha.com> <1168248244.134804.138050@51g2000cwl.googlegroups.com> Message-ID: <7xbqk8iork.fsf@ruckus.brouhaha.com> Steve Holden writes: > >> class A(B): > >> def bar(self): > >> self.__x = 5 # clobbers private variable of earlier class named A > > Has this ever been reported as a bug in Python? I could imagine more > > sophisticated "name mangling": something to do with the identity of the > > class might be sufficient, although that would make the tolerated > > "subversive" access to private attributes rather difficult. > > > It would also force the mangling to take place at run-time, which > would probably affect efficiently pretty adversely (thinks: should > really check that mangling is a static mechanism before posting this). I think it could still be done statically. For example, the mangling could include a random number created at compile time when the class definition is compiled, that would also get stored in the class object. I guess there are other ways to create classes than class statements and those would have to be addressed too. From bj_666 at gmx.net Sun Feb 11 07:46:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 11 Feb 2007 13:46:49 +0100 Subject: How to access an absolute address through Python? References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> <1171197574.776135.96980@k78g2000cwa.googlegroups.com> Message-ID: In <1171197574.776135.96980 at k78g2000cwa.googlegroups.com>, volcano wrote: > On Feb 11, 2:21 pm, Ma?l Benjamin Mettler wrote: >> volcano schrieb: >> >> > Can it be done, and if yes - how? >> >> Define address. Are you talking about URLs? File paths? Postal >> addresses? Memory addresses? Whatever addresses? >> I'm afraid the people on this list can't read your thoughts... > > I presumed that "absolute" address somehow qualifies my question. If > it is not - I was talking about physical computer memory, on PC - to > be more specific. In pure Python it's not possible and even in C it might be difficult to get an absolute *physical* memory address unless you run DOS. Modern operating systems tend to use some virtualisation of memory. :-) What's your goal? What do you expect at the memory address you want to access? Ciao, Marc 'BlackJack' Rintsch From robin at NOSPAMreportlab.com Sun Feb 4 06:18:11 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sun, 04 Feb 2007 11:18:11 +0000 Subject: ctypes.com.IUnknown In-Reply-To: <1170585495.897502.148500@v45g2000cwv.googlegroups.com> References: <45C4F24C.7060204@jessikat.plus.net> <1170585495.897502.148500@v45g2000cwv.googlegroups.com> Message-ID: <45C5C0F3.9050308@jessikat.plus.net> Giles Brown wrote: >........ > > What about downloading the spin-off library? > http://sourceforge.net/projects/comtypes/ > > (I think this was created to move the com stuff out of ctypes?) ....... Thanks I didn't know that; I'll give it a whirl. -- Robin Becker From elrondrules at gmail.com Tue Feb 6 20:59:40 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 6 Feb 2007 17:59:40 -0800 Subject: need help to kill a process Message-ID: <1170813580.163486.219190@l53g2000cwa.googlegroups.com> Hi Am new to python and need your help!! this is my code snip. within my python script I have the following commands.. import os ... os.system ("cd /home; ./TestTool &") os.system ("cd /usr/; sh run.sh load.xml &") I need to kill these 2 process after a particular job is done.. is there any way to get the pids of these process and if so how do i invoke the kill command through os.system.. or else is there anyother way to do this... thanks From smusnmrNOSPAM at yahoo.com Sat Feb 10 02:29:05 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Sat, 10 Feb 2007 08:29:05 +0100 Subject: pygame and python 2.5: switch to linux? References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> Message-ID: "Ben Sizer" wrote: [snip] > Hopefully in the future, some of those convoluted steps will be fixed, > but that requires someone putting in the effort to do so. As is often > the case with Python, and indeed many open source projects, the people > who are knowledgeable enough to do such things usually don't need to > do them, as their setup already works just fine. > > -- > Ben Sizer > Thank you, and all those putting in their comments to my thread. As a python newbie, I conclude now that I will be better off to drop Windows and install Linux on my next PC, to be able to reap the full benefits of Python. Thanks, siggi From bruno.desthuilliers at gmail.com Fri Feb 9 07:47:20 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 9 Feb 2007 04:47:20 -0800 Subject: resolve environment variables in string - regular expression In-Reply-To: <1171020642.655125.164880@p10g2000cwp.googlegroups.com> References: <1171020642.655125.164880@p10g2000cwp.googlegroups.com> Message-ID: <1171025240.340881.49130@a34g2000cwb.googlegroups.com> On 9 f?v, 12:30, "Kai Rosenthal" wrote: > Hello, > > how can I resolve envionment variables in a string. > e.g. > > strVar = /myVar > resolve in nothing. This raises a SyntaxError. Python is *not* a shell script language. > str1 = /mytest02/$MYVAR/mytest02 --> /mytest02//myVar/mytest02 > (unix) > str2 =$MYVAR/mytest03 --> /myVar/mytest03 (unix) > str3 =%MYVAR%/mytest03 --> /myVar/mytest03 (windows) > I would not set the variables in this time. > > I think I need a little regular expression code snippet, Nope. my_var = "/myVar" str1 = "/mytest02/%s/mytest02" % my_var str2 = "%(my_var)s/mytest03" % {'my_var': my_var} import os str3=os.path.join(my_var, "mytest03") hth From thinker at branda.to Mon Feb 26 11:00:01 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 00:00:01 +0800 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: <45E30401.6030800@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 zefciu wrote: > I am trying to embed a c function in my python script for a first > time. When I try to call it I get an error > > SystemError: new style getargs format but argument is not a tuple > > Guido said on some mailing list, that it is probably an effect of > the lack of METH_VARARGS in the functions' array, but it's ok in my > source code. Here is the full code: > > #include > > static PyObject * mandelpixel(PyObject *self, PyObject *args) { > double z_real = 0, z_imag = 0, z_real2 = 0, z_imag2 = 0, c_real, > c_imag, bailoutsquare; int iteration_number; register int i; > PyObject coord; if (!PyArg_ParseTuple(args, "Oid", &coord, > &iteration_number, &bailoutsquare)) return NULL; if > (!PyArg_ParseTuple(&coord, "dd", &c_real, &c_imag)) return NULL; Is coord always tuple? - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4wQB1LDUVnWfY8gRAtWsAKCavY85KUtoppRSj0uQTeVnmLu5UwCgyfk1 0c5fkRgKaejDja1YWdKkaTg= =vMjd -----END PGP SIGNATURE----- From jmbzwa at chatteriealice.com Thu Feb 15 16:00:29 2007 From: jmbzwa at chatteriealice.com (Abraham Kaiser) Date: Thu, 15 Feb 2007 16:00:29 -0500 Subject: 1 we are going to support applications which use WCW and Visual Designer. Message-ID: <000d01c75144$f2726e00$5456995e@bzld> It also can be used with Abstract Windowing Toolkit- or AWT-based GUIs, provided that those GUIs are made accessible to the technology. Here is what a JColorChooser might look like in your own application window. Here is one such automatically created popup. Class File primarily names files, queries file attributes, and manipulates directories or temporary files, all in a system-independent way. You probably expected to see a full-fledged rendering of the five different cards, as in Figure 1, including the clickable tabs to select any one of the cards. MicroEdition-Configuration: CLDC-1. When you submit a question to the speakers, your question will not immediately appear in the chat room. Also, discover what's new in tools and Sun courses. net Several years back, I configured a blind gentleman's Microsoft-Windows-based computer to vocally identify the window under the mouse pointer. recognition extends this basic functionality for recognizers. Also, discover the lastest in tutorials for various development tools. And above all, our projects are based on Ant, so you don't need the IDE to build your projects at all. After all, if a widely deployed application breaks a phone or causes damage to the network or the company's reputation, they stand to lose a fair amount of money. Specific applications can request specific Java platform versions without conflicting with the different needs of other applications. Figures 4 and 5 show the two different layout policies. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: articulate.gif Type: image/gif Size: 10775 bytes Desc: not available URL: From steve at REMOVEME.cybersource.com.au Thu Feb 15 01:11:05 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 17:11:05 +1100 Subject: Method overloading? References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <12t7qehj9jm0a21@corp.supernews.com> <1171516359.202035.35020@q2g2000cwa.googlegroups.com> Message-ID: On Wed, 14 Feb 2007 21:12:39 -0800, placid wrote: > On Feb 15, 4:04 pm, Grant Edwards wrote: >> On 2007-02-15, placid wrote: >> >> >> >> > Is it possible to be able to do the following in Python? >> >> > class Test: >> > def __init__(self): >> > pass >> >> > def puts(self, str): >> > print str >> >> > def puts(self, str,str2): >> > print str,str2 >> >> > if __name__ == "__main__": >> > t = Test() >> > t.puts("hi") >> > t.puts("hi","hello") >> >> You tell us: what happened when you tried it? > > Well, when i run it i get this error "puts() takes exactly 3 arguments > (2 given)" which means that the second a time i try to define the > puts() method "overwrites" the first one Yes, that's right. It is no different from doing this: x = 1 x = 2 >> And then what happens when you do this? >> >> class Test: >> def __init__(self): >> pass >> >> def puts(self, *args): >> print ' '.join(args) >> >> if __name__ == "__main__": >> t = Test() >> t.puts("hi") >> t.puts("hi","hello") > > but this isn't overloading. Neither was your first example. This is an example of overloading: class Cheese(object): def flavour(self): return "tasty and scrumptious" def colour(self): return "yellow" Now we define a sub-class which overloads some methods: class BlueVein(Cheese): def colour(self): return "white with blue veins" Testing it: >>> c = BlueVein() >>> c.flavour() # inherited from the super class 'tasty and scrumptious' >>> c.colour() # over-ridden by the sub-class 'white with blue veins' >>> super(BlueVein, c).colour() # call the super class method 'yellow' I hope this helps. -- Steven D'Aprano From researchbase at gmail.com Fri Feb 9 01:11:38 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 9 Feb 2007 11:41:38 +0530 Subject: strange problem using modules from my own package. In-Reply-To: <20070209054912.937F11E4010@bag.python.org> References: <20070209054912.937F11E4010@bag.python.org> Message-ID: On 09/02/07, Gabriel Genellina wrote: > At Friday 9/2/2007 02:10, you wrote: > > Please keep posting on the list - you'll reach a whole lot of people > there... sorry, I had just hit the reply button and did not notice that python-list was not there. >my crystal ball I can see this statement: import pbcf > or perhaps: from pbcf import something (it's not so clear...) > written inside any module in your package. So, your package must be > installed in any directory listed in sys.path, for python to be able > to actually find it; perhaps in site-packages. can I have package in a folder and then a main.py in the same folder but out side the package? > Also, if you try to execute a module "inside" your package, it does > not even *know* that it lives inside a package. > but all this is working in eclipse with pydev. and I looked in the console but there were no errors. From rshepard-at-appl-ecosys.com Fri Feb 9 19:28:12 2007 From: rshepard-at-appl-ecosys.com (rshepard-at-appl-ecosys.com) Date: 10 Feb 2007 00:28:12 GMT Subject: Matching Strings References: Message-ID: On 2007-02-10, rshepard at nospam.appl-ecosys.com wrote: > if item == selName: Slicing doesn't seem to do anything -- if I've done it correctly. I changed the above to read, if item[2:-2] == selName: but the output's the same. Rich From gagsl-py at yahoo.com.ar Mon Feb 5 18:47:07 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:47:07 -0300 Subject: Definitions of editor and IDE? References: <20070203224824.0CC7C1E400A@bag.python.org> Message-ID: En Sat, 03 Feb 2007 19:48:06 -0300, Dick Moores escribi?: > Are there generally accepted definitions of "editor" and "IDE". Is there > a clear-cut > distinction between them? I've been looking at the lists of each at > python.org, > < http://wiki.python.org/moin/PythonEditors> and < > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments>. > Many programs are on both lists: Komodo, Eclipse, jedit, SPE, Wing IDE, > UliPad, > etc. IDE means "Integrated Development Environment". Usually includes a source file editor, but many more things, like: a debugger, an object inspector, some software design tools, a GUI designer, etc. -- Gabriel Genellina From david.bear at asu.edu Fri Feb 2 14:27:51 2007 From: david.bear at asu.edu (David Bear) Date: Fri, 02 Feb 2007 12:27:51 -0700 Subject: more examples on lamba Message-ID: <2006330.mqpy8evNZf@teancum> I've been going through David Mertz's python book and he is heavy in to lamba's and higher order functions. This is all very new to me. Can anyone point me to more web stuff that describes more deeply lamba's and making high order functions -- functional programming styles. Coming from BASIC and Pascal, these are constructions that never entered into youthfull learning;-) -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From http Sat Feb 3 21:31:03 2007 From: http (Paul Rubin) Date: 03 Feb 2007 18:31:03 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xejp89pa9.fsf@ruckus.brouhaha.com> <7xfy9n2pz4.fsf@ruckus.brouhaha.com> Message-ID: <7xbqkaejrs.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > Paul> Why would I expect your employer to solve my problems anyway, even > Paul> if they relate to some module that you actually use? > > Your reasoning seems to be that Python should contain the functional union > of everything at least in Java and PHP if not Perl, Ruby and Tcl as well. I wouldn't go quite that far. I think there are specific application areas, such as web server apps, where the Python advocates here on clpy pitch Python relentlessly against those other languages. Given that context, Python's stdlib should try to match the libraries of those other languages in those areas. There are other areas where Python doesn't get pitched as hard and the other languages have acknowledged advantages. So it's ok if Python's stdlib gets less attention in those areas. > Free software or not, each person who contributes to the development > of the Python core has to put food on the table. As an example, I > suspect most core Java development is funded directly by Sun who > pays its employees to develop libraries, JIT compilers and the like. > While my employer pays me to program in Python I'm not paid to > develop core Python code. What little I do is done on my own time. Again I don't understand what your employer or your activities have to do with any of this. If you don't want to spend your time developing Python then don't. You didn't write the interpreter or the tkinter library or the itertools library and yet there they are. There's ongoing development that will continue with or without you or me, and for that matter with or without funding from Sun. > If you want to turn the Python distribution into a kitchen sink, > make the argument on python-dev and be prepared to shoulder your > share of the burden should your arguments sway the group as a whole. We've had this conversation before and I continue to think your reasoning above is invalid. I'm not a Python developer, I'm just a user, and my volunteer coding priorities are elsewhere, as I've explained before. Python's developers and advocates have a declared goal of reaching as many users as they can, and as a user I don't mind offering suggestions about how to do that, but my responsibilities don't go any further. From __peter__ at web.de Fri Feb 9 06:11:19 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Feb 2007 12:11:19 +0100 Subject: unique elements from list of lists References: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> Message-ID: Tekkaman wrote: > I have a list of lists and I want to define an iterator (let's call > that uniter) over all unique elements, in any order. For example, > calling: > > sorted(uniter([['a', 'b', 'd'], ['b', 'c'], ['a', 'c', 'd']])) > > must return ['a', 'b', 'c', 'd']. I tried the following > implementations: > > from itertools import chain > def uniter1(listOfLists): > for item in set(chain(*listOfLists)): yield item def uniter(lists): return iter(set(chain(*lists))) This avoids the explicit for-loop. Peter From bearophileHUGS at lycos.com Tue Feb 6 15:56:45 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Feb 2007 12:56:45 -0800 Subject: Two mappings inverse to each other: f, g = biject() In-Reply-To: <45C856E4.6090307@pytex.org> References: <45C856E4.6090307@pytex.org> Message-ID: <1170795405.214593.187170@s48g2000cws.googlegroups.com> Jonathan Fine: > A google search for biject.py and bijection.py > produced no hits, so I suspect that this may not > have been done before. There are few (good too) implementations around, but they are called bidict or bidirectional dicts. Sometimes I use this implementation, with few changes: http://www.radlogic.com.au/releases/two_way_dict.py Bye, bearophile From jstroud at mbi.ucla.edu Wed Feb 14 23:34:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 20:34:20 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: skip at pobox.com wrote: > >> Concatenating tuples and lists seems logical if you think of tuples > >> as sequences. If you think of them more like Pascal records or C > >> structs instead (I believe that's Guido's perspective on tuples) then > >> it makes no sense at all. > > James> Then iterating over them makes no sense? > > I agree that tuples are a bit schizophrenic. They really are sequences from > an implementation standpoint, but from a logical standpoint it's maybe best > not to think of them that way. > > That said, this: > > for x in (1,2,3): > pass > > is a skosh faster (perhaps an immeasurably small skosh) than this: > > for x in [1,2,3]: > pass > > so people will probably continue to use tuples instead of lists in these > sorts of situations. > > For an example of the struct-ness of a tuple consider the output of os.stat: > > >>> import os > >>> s = os.stat("/etc/hosts") > >>> s > (33188, 34020475L, 234881029L, 1, 0, 0, 214L, 1170562950, 1124700602, 1142602578) > >>> s.st_mtime > 1124700602.0 > >>> s[0] > 33188 > >>> type(s) > > > It's effectively a tuple with field names. I don't know when the switch > occurred (it's in 2.2, as far back as my built interpreter versions > currently go), but back in the day os.stat used to return a plain old tuple. > > I have no idea if the schizophrenic personality of tuples will improve with > drugs^H^H^H^H^H Python 3, but I wouldn't be at all surprised if it did. > > Skip The arguments for how tuples behave are all very compelling and indeed I keep them in mind when I code--careful not to confuse their uses. The problem is that, to the uninitiated, they are redundant and are often used interchangably. Also, it is very easy for the uninitiated to create highly functional code in python, and so we get many hybrid uses and confusion. I increasingly come to the decision to avoid tuples altogether because, eventually, you end up turning them into lists anyway and so they begin to represent extra overhead--although its always fun to try to identify cases when they might provide some value. James From karoly.kiripolszky at gmail.com Tue Feb 6 07:44:07 2007 From: karoly.kiripolszky at gmail.com (=?iso-8859-1?q?K=E1roly_Kiripolszky?=) Date: 6 Feb 2007 04:44:07 -0800 Subject: C parsing fun In-Reply-To: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> Message-ID: <1170765847.250016.83410@l53g2000cwa.googlegroups.com> Helo again! When I came up with this idea on how to parse C files with ease, I was at home and I only have access to the sources in subject in the office. So I've tried the previously posted algorithm on the actual source today and I realized my originally example data I've ran the test with was so simple, that with some header files the algorithm still failed. I had to make some further changes and by now I was able to parse 1135 header files in 5 seconds with no errors. This may be considered as spamming, but this package is so small I don't wan't to create a page for it on SF or Google Code. Furthermore I want to provide people who find this topic a working solution, so here's the latest not-so-elegant-brute-force-but-fast parser: http://kiri.csing.hu/stack/python/bloppy-0.3.zip On Feb 5, 1:43 pm, "karoly.kiripolszky" wrote: > Helo ppl! > > At the job I was given the task to make a script to analyze C++ code > based on concepts my boss had. To do this I needed to represent C++ > code structure in Python somehow. I read the docs for Yapps, pyparsing > and other stuff like those, then I came up with a very simple idea. I > realized that bracketed code is almost like a Python list, except I > have to replace curly brackets with squared ones and surround the > remaining stuff with quotes. This process invokes no recursion or node > objects, only pure string manipulations so I believe it's really fast. > Finally I can get the resulting list by calling eval() with the > string. > > For example when I need to parse a class definition, I only need to > look for a list item containing the pattern "*class*", and the next > item will be the contents of the class as another list. > > You can grab the code at: > > http://kiri.csing.hu/stack/python/bloppy-0.1.zip > > (test script [test.py] included) From google at mrabarnett.plus.com Tue Feb 6 16:26:29 2007 From: google at mrabarnett.plus.com (MRAB) Date: 6 Feb 2007 13:26:29 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170775779.707583.131420@k78g2000cwa.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> <1170775779.707583.131420@k78g2000cwa.googlegroups.com> Message-ID: <1170797189.318430.208790@p10g2000cwp.googlegroups.com> On Feb 6, 3:29 pm, garri... at gmail.com wrote: > On Feb 1, 8:25 pm, "Krypto" wrote: > > > The correct answer as told to me by a person is > > (N>>3) + ((N-7*(N>>3))>>3) > > The above term always gives division by 7 > > Does anybody else notice that this breaks the spirit of the problem > (regardless of it's accuracy)? 'N-7' uses the subtraction operator, > and is thus an invalid solution for the original question. > [snip] Instead of subtraction you can use complement-and-add: N + ~7 + 1 (that's a tilde '~' not a minus '-'). From annaraven at gmail.com Sun Feb 18 12:22:50 2007 From: annaraven at gmail.com (Anna Ravenscroft) Date: Sun, 18 Feb 2007 09:22:50 -0800 Subject: Game Programming Clinic and Online Gaming at PyCon In-Reply-To: <45D7CC0F.7020105@taupro.com> References: <45D7CC0F.7020105@taupro.com> Message-ID: On 2/17/07, Jeff Rush wrote: > > At PyCon this year we're going to have a multi-day game programming clinic > and > challenge. This is a first-time event and an experiment to find those in > the > Python community who enjoy playing and creating games. Python has several > powerful modules for the creation of games among which are PyGame and > PyOpenGL. > > On Friday evening, Phil Hassey will give an introduction to his game > Galcon, > an awesome high-paced multi-player galactic action-strategy game. You > send > swarms of ships from planet to planet to take over the galaxy. Phil will > be > handing out free limited-time licenses to those present. He will also be > glad > to talk about the development of Galcon using PyGame. > > After the Friday PSF Members meeting lets out around 8:40pm, Richard Jones > will give his 30-60 minute introduction to the PyGame framework so you too > can > get started writing games. Wonderful. Thanks for the heads-up! I look forward to this. On Saturday evening, Lucio Torre and Alejandro J. Cura, who have come from > Argentina to give the talk "pyweek: making games in 7 days" Friday > afternoon, > will help people develop their games in the clinic room with mini-talks on > various game technologies. Ah - that's a really fun presentation - I saw it at CafeConf. Glad to hear they'll be helping folks on Satyrday night. Thanks for all the links Jeff. Very helpful. -- cordially, Anna -- It is fate, but call it Italy if it pleases you, Vicar! -------------- next part -------------- An HTML attachment was scrubbed... URL: From giles_brown at hotmail.com Tue Feb 13 19:17:59 2007 From: giles_brown at hotmail.com (Giles Brown) Date: 13 Feb 2007 16:17:59 -0800 Subject: _ssl.pyd is buggy? In-Reply-To: References: <45D1F804.8050609@designaproduct.biz> Message-ID: <1171412279.368565.295060@v45g2000cwv.googlegroups.com> Something I always found useful is to use the win32traceutil to set up the trace debugging tool. You can then see the output in the pythonwin trace collector tool. This is very useful for Python services and COM servers. Best of luck, Giles From bear at sonic.net Mon Feb 26 14:12:42 2007 From: bear at sonic.net (Ray Dillinger) Date: Mon, 26 Feb 2007 11:12:42 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: <45e33052$0$27235$742ec2ed@news.sonic.net> Tech HR wrote: > But we're a very young company (barely six months old at this point) so > we're willing to listen to most anything at this point. (We're using > Darcs for revision control. Haskell, anyone?) Tell us, where you would expect an applicant for one or more of these jobs to live if they accepted a job with your firm? It's not at all apparent from your website or job descriptions where the worksite is physically located. Bear From angelic_assistant at yahoo.com Wed Feb 28 03:55:58 2007 From: angelic_assistant at yahoo.com (Jennifer Crosby) Date: Wed, 28 Feb 2007 08:55:58 GMT Subject: Cover up attempt Message-ID: http://toiletseatcoverup.blogspot.com/ - Yahoo ads not performing well? Publisher profits in the toilet? Join the best affiliate program known to man. Jennifer Crosby very hot but is she single? Ya its no two man race to a one man shit show this time dear. From gagsl-py at yahoo.com.ar Tue Feb 6 12:18:28 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 6 Feb 2007 14:18:28 -0300 Subject: huge amounts of pure Python code broken by Python 2.5? References: <1170780602.945994.34390@k78g2000cwa.googlegroups.com> Message-ID: "John Roth" escribi? en el mensaje news:1170780602.945994.34390 at k78g2000cwa.googlegroups.com... > On Feb 6, 8:40 am, Steven Bethard wrote: >> Jean-Paul Calderone wrote: >> >> > Huge amounts of my pure Python code was broken by Python 2.5. >> >> Interesting. Could you give a few illustrations of this? (I didn't run >> into the same problem at all, so I'm curious.) >> > > At a guess, the most likely thing to break code in job lots in 2.5 was > the change in default coding from latin-1 (or whatever the > installation has the default set to) to ascii. And that has given a warning since 2.3... -- Gabriel Genellina From karoly.kiripolszky at gmail.com Mon Feb 5 09:56:33 2007 From: karoly.kiripolszky at gmail.com (=?iso-8859-1?q?K=E1roly_Kiripolszky?=) Date: 5 Feb 2007 06:56:33 -0800 Subject: C parsing fun In-Reply-To: References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> <1170683733.434435.171350@j27g2000cwj.googlegroups.com> Message-ID: <1170687393.909619.85660@a34g2000cwb.googlegroups.com> http://kiri.csing.hu/stack/python/bloppy-0.2.zip Test data now also contains brackets in literal strings. Claudio Grondi ?rta: > K?roly Kiripolszky wrote: > > You're right, thank you for the comment! I will look after how to > > avoid this. > And after you have resolved this 'small' ;-) detail you will probably > notice, that some full functional and in wide use being parser have > still trouble with this ... > > Claudio > > > > Marc 'BlackJack' Rintsch ?rta: > >> In <1170679559.272656.145660 at v33g2000cwv.googlegroups.com>, > >> karoly.kiripolszky wrote: > >> > >>> and the great thing is that the algorithm can be used with any > >>> language that structures the code with brackets, like PHP and many > >>> others. > >> But it fails if brackets appear in comments or literal strings. > >> > >> Ciao, > >> Marc 'BlackJack' Rintsch > > From fuzzyman at gmail.com Fri Feb 16 10:17:26 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Feb 2007 07:17:26 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> <1171636975.653884.122850@p10g2000cwp.googlegroups.com> Message-ID: <1171639046.713992.238540@j27g2000cwj.googlegroups.com> On Feb 16, 2:54 pm, Steven D'Aprano wrote: > On Fri, 16 Feb 2007 06:42:55 -0800, Fuzzyman wrote: > > I mentioned the 2to3 translator- the goal of which is *precisely* to > > allow you to write code that will run on Python 2.X and when > > translated run under Python 3.0. > > Unfortunately, that is not a realistic goal for the 2to3 translator. The > goal is to accurately translate 80% of Python code that needs changing, > and issue warnings for the other 20%. > Right, but it *was* a stated aim of the translator when discussed on Python-dev recently. > > You then repeated the problem with the 'print' statement. > > > It may be true that you won't be able to write code that runs > > untranslated on 2 and 3. That doesn't stop you writing code for Python > > 2.X, then translating a version for Python 3. (Uhm... indeed that's > > the point of 2to3.) > > > So you only have one codebase to maintain and you can still use > > print... > > No, you have TWO sets of code. You have the code you write, and the code > you have run through 2to3. Even if 2to3 gives you 100% coverage, which it > won't, you still have two codebases. > Only one of which you maintain - if the translator works 100% (which I accept may be unrealistic). Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -- > Steven. From list-ener at strank.info Fri Feb 16 09:36:24 2007 From: list-ener at strank.info (Stefan Rank) Date: Fri, 16 Feb 2007 15:36:24 +0100 Subject: Pep 3105: the end of print? In-Reply-To: References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: <45D5C168.5070605@strank.info> on 16.02.2007 13:02 Edward K Ream said the following: >> There are a tool called "2to3" that translates things like "print foo" to >> print(foo). > > The point of my original post was that if I want to maintain a common code > base the tool must translate 'print foo' to 'print2(foo)'. I think you are misunderstanding the purpose of the 2to3 tool. It is supposed to create a new version of the code that runs on py3, while you can still run your *"old"* code on py2.x There won't be a common code base for all python versions. You will have to decide at what point you want to switch from developing the 2.x code (and using the 2to3 tool to support py3) to developing the py3 code. (You might then develop a 3to2 tool, but I think this discussion is getting way ahead of its time. ;-) From mfmdevine at gmail.com Wed Feb 14 10:35:49 2007 From: mfmdevine at gmail.com (amadain) Date: 14 Feb 2007 07:35:49 -0800 Subject: multi processes In-Reply-To: <1171467145.957828.188780@j27g2000cwj.googlegroups.com> References: <1171464784.419065.149140@v45g2000cwv.googlegroups.com> <1171467145.957828.188780@j27g2000cwj.googlegroups.com> Message-ID: <1171467349.918427.25530@l53g2000cwa.googlegroups.com> On Feb 14, 3:32 pm, garri... at gmail.com wrote: > On Feb 14, 7:53 am, "amadain" wrote: > > > Hi > > Heres a poser. I want to start a program 4 times at exactly the same > > time (emulating 4 separate users starting up the same program). I am > > using pexpect to run the program from 4 separate locations accross the > > network. How do I start the programs running at exactly the same time? > > I want to time how long it takes each program to complete and to show > > if any of the program initiations failed. I also want to check for > > race conditions. The program that I am running is immaterial for this > > question - it could be mysql running queries on the same database for > > example. Using threading, you call start() to start each thread but if > > I call start on each instance in turn I am not starting > > simultaneously. > > A > > Standard answers about starting anything at *exactly* the same time > aside, I would expect that the easiest answer would be to have a fifth > controlling program in communication with all four, which can then > send a start message over sockets to each of the agents at the same > time. > > There are several programs out there which can already do this. One > example, Grinder, is designed for this very use (creating concurrent > users for a test). It's free, uses Jython as it's scripting language, > and even is capable of keeping track of your times for you. IMO, it's > worth checking out. > > http://grinder.sourceforge.net Thank you. I'll check that out. From steve at REMOVEME.cybersource.com.au Thu Feb 15 01:48:10 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 17:48:10 +1100 Subject: f---ing typechecking References: Message-ID: On Wed, 14 Feb 2007 22:21:43 -0800, James Stroud wrote: >> The user's expected behaviour for [1] + (1,) might be to return a list, or >> it might be to return a tuple. Since there is no obviously correct >> behaviour, the right thing to do is to refuse to guess. > > I guess we differ on what is obvious. This seems obvious to me: > > [1] + (1,) => [1, 1] > (1,) + [1] => (1, 1) > > simply becuase the operand on the left should take precendence because > its "__add__" is called and its "__add__" returns a list. But that's data dependent. When you call [1] + MyTuple(1) your MyTuple.__radd__ will be called first, not the list's __add__. > In essence, as > we know the obviously correct behavior for __add__ and __radd__, then it > would be the obviously correct behavior that the above would follow. But we don't know the obviously correct behaviour. Why should list.__add__ return a list if the other operand is a tuple? You're assuming what I'm asking you to justify. int.__add__ doesn't necessarily return an int. Why should lists be different? > I would venture to guess that most people would intuitively consider the > above behavior correct, I dare say you are right for *some* people. After all, Perl and other weakly-typed languages try to coerce virtually all types. I doubt it is a majority. > simply because the information content > difference between a list versus a tuple is non-existent (outside of the > information that one is a list and the other a tuple). Why would their > types dictate coercion? But that's what you're doing -- implicit coercion. [1] + (1,) == [1] + [1] (1,) + [1] == (1,) + (1,) I don't believe there is any justification for doing such coercion for lists and tuples. > With ints and floats, as you point out, the > reasons that type dictates coercion are obvious and mathematical. Thus, > for tuples and lists, it wouldn't make sense to consider one type taking > precendence over the other, so we fall back to position, which seems to > be the common sense approach. I would say the commonsense approach is to refuse the temptation to guess in the face of ambiguity. Since neither coercing lists to tuples nor tuples to lists is more obviously correct, raising an exception is the sensible behaviour. Let the caller choose the correct coercion to use. -- Steven D'Aprano From larry.bates at websafe.com Mon Feb 5 16:12:45 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 05 Feb 2007 15:12:45 -0600 Subject: alias for data member of class instance? In-Reply-To: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> References: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> Message-ID: <45C79DCD.70801@websafe.com> Sean McIlroy wrote: Sean McIlroy wrote: > hi all > > is there a way to do this ... > > class clown: > def __init__(self): > self.x = 0 > self.y = ALIAS(self.x) ## FEASIBLE ? > > ... so that you get results like this ... > > krusty = clown() > krusty.x >>> 0 > krusty.y >>> 0 > krusty.x = 1 > krusty.x >>> 1 > krusty.y >>> 1 > > ... ? thanks. > > peace > stm > > hi all > > is there a way to do this ... > > class clown: > def __init__(self): > self.x = 0 > self.y = ALIAS(self.x) ## FEASIBLE ? > > ... so that you get results like this ... > > krusty = clown() > krusty.x >>> 0 > krusty.y >>> 0 > krusty.x = 1 > krusty.x >>> 1 > krusty.y >>> 1 > > ... ? thanks. > > peace > stm > Not sure why you want it, but here is one solution: class clown: def __init__(self): self.x=0 def __getattr__(self, key): if key == 'y': return self.x return self.__dict__[key] -Larry From mark.asbach at post.rwth-aachen.de Fri Feb 2 03:30:07 2007 From: mark.asbach at post.rwth-aachen.de (Mark Asbach) Date: Fri, 2 Feb 2007 09:30:07 +0100 Subject: Python, readline and OS X References: Message-ID: <1hswi70.1cpcm2q11u6pg0N%mark.asbach@post.rwth-aachen.de> Hi James, hi Ron, > Where have you installed libreadline? Is LD_LIBRARY_PATH pointing to the > directory libreadline.dylib? Did you install libreadline with fink? If > so, try > > setenv LD_LIBRARY_PATH /sw/lib That would probably make no difference since on Mac OS X that variable is called DYLD_LIBRARY_PATH (contrary to SysV Unices). > Bash (OSX default) and similar shells use this silly 2 part syntax: > > LD_LIBRARY_PATH=/sw/lib > export LD_LIBRARY_PATH It's just your way of using it that makes it a 2 part syntax: export DYLD_LIBRARY_PATH=/sw/lib does the trick. And by the way: the bash construct is far less error prone regarding quoting when used in shell scripts. Mark From hq4ever at gmail.com Tue Feb 6 02:52:00 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Tue, 6 Feb 2007 09:52:00 +0200 Subject: lambda functions ? In-Reply-To: <7xy7nc6y9e.fsf@ruckus.brouhaha.com> References: <7xy7nc6y9e.fsf@ruckus.brouhaha.com> Message-ID: Wow, Thank you everyone for the help. I am amazed by the motivation people have on this list to help new comers. I hope that I will be able to contribute equally some day. On 05 Feb 2007 14:22:05 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Maxim Veksler" writes: > > >>> def make_incrementor(n): > > ... return lambda x: x + n > > Is the same as: > > def make_incrementor(n): > def inner(x): > return x + n > return inner > > When you enter make_incrementor, it allocates a memory slot (normally > we'd think of this as a stack slot since it's a function argument, but > it's really in the heap) and copies its argument there. Then you > create the function "inner" which refers to that memory slot because > of the reference to "n". Then make_incrementor returns, but since the > returned object still contains the reference to that memory slot, the > memory slot is not freed (this is the part where it becomes important > that the slot is really not on the stack). So when you call the > returned function, it still can get at that slot. > Following the debugger on your code, I can identify the following stages: def make_incrementor(n): def inner(x): return x + n return inner f = make_incrementor(10) f(10) f(0) 1. "def make_incrementor(n)" Create function object in memory and set "make_incrementor" to point to it. 2. "f = make_incrementor(10)" Set "f" to point to "inner(x) function". Set n value to 10. 3. "f(10)" Call to inner(x), which will return "father" n + "local" x. This means that "f" is not a pointer to make_incrementor but rather to the internal (copied?) function. > This style is very common in Scheme programming so you might read a > Scheme book if you want to understand it. The classic: > > http://mitpress.mit.edu/sicp/ > I might just well do that. > > Could some please try (if even possible) to implement the above code > > without using "lambda" I believe it would help me grasp this a bit > > faster then. > > Does the above help? all Your explanation was excellent. Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From cito at online.de Sun Feb 11 13:56:16 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 11 Feb 2007 19:56:16 +0100 Subject: Problem with reimporting modules In-Reply-To: <1171209111.551190.146590@a34g2000cwb.googlegroups.com> References: <1171209111.551190.146590@a34g2000cwb.googlegroups.com> Message-ID: Yes I know about reload(), but TurboGears (TurboKid) does not use it and the docs say that removing modules from sys.module is possible to force reloading of modules. I don't want to rewrite everything since it's a pretty complex thing with modules which are compiled from templates which can depend from other templates etc... From exarkun at divmod.com Mon Feb 19 12:09:04 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 19 Feb 2007 12:09:04 -0500 Subject: Declare a variable global In-Reply-To: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> Message-ID: <20070219170904.25807.1276657147.divmod.quotient.27350@ohm> On 19 Feb 2007 09:04:19 -0800, "yinglcs at gmail.com" wrote: >Hi, > >I have the following code: > >colorIndex = 0; > >def test(): > print colorIndex; > >This won't work. Are you sure? exarkun at charm:~$ cat foo.py colorIndex = 0 def test(): print colorIndex test() exarkun at charm:~$ python foo.py 0 exarkun at charm:~$ The global keyword lets you rebind a variable from the module scope. It doesn't have much to do with accessing the current value of a variable. Jean-Paul From bignose+hates-spam at benfinney.id.au Fri Feb 2 07:06:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 23:06:01 +1100 Subject: Writing "pythonish" code References: Message-ID: <87y7ngu5li.fsf@benfinney.id.au> Mizipzor writes: > The problem isnt in pythons syntax, its in the architecture/design, > the concept of writing "pythonish code" if you like. The nomenclature around here for that concept is "Pythonic". > One thing is that in c++ im used to have private members in classes > and no member is altered except through the public functions of the > class. In python everything is, as far as I know, public. Python has no strict prohibition on accessing any attribute of a class. The convention is to name attributes with a leading underscore if you don't think they should be accessed from outside the class. This allows users of your class (i.e. people writing code that uses that class) to know what the public interface is -- i.e. all the attributes that aren't named with a leading underscore -- without preventing access to the other attributes if that makes for better code. Since you can't ever know all the possible uses of a class when you write it, this flexibility is a good thing. > Im confused by this, should I still have members in the python class > that I simply dont edit directly and let the class do its internal > stuff? Who is "I" in the above question? You should write your classes on the assumption that you don't know who will be making use of them, and consider your code to be a means of communication with the later users (programmers) of your code. > Or should I see the python classes like c++ structs with functions? I don't see what benefit this would have; Python classes are classes. > Now, the thing that bothers me the most. When I write python modules > I write one class per file, and the file and the class has a common > name. To move toward more Pythonic code, you should treat a module as a logically-coherent collection of functionality. It can contain any number of classes or other objects. Divide your code into modules by functionality, not dogmatically by one-class-per-module. > foo.py > ========= > > class foo: > def bar(self): > print "bar" > > ========= > > main.py > ========= > > import foo > > localFoo = foo.foo() > localFoo.bar() > > ========= > > To me, the main.py code above looks very ugly. Can you articulate what looks ugly? Python makes strong use of namespaces, so the above looks fine to me: it's clear where everything is coming from. The only confusion comes from the fact that the module "foo" and the class "foo" have the same name, which as discussed doesn't need to be the case unless it actually makes sense. > So, assuming Im never gonna have more than one instance of the foo > class This is a separate assumption, and doesn't necessarily follow from what you've said above. > can I write something like this: > > foo.py > ========= > > def bar(self): > print "bar" > > ========= > > main.py > ========= > > import foo > > foo.bar() > > ========= > > Thats much more cleaner if you ask me, and kinda a good way to make > sure that you dont have more than one "instance" of the foo class > (which no longer is a class at all). But is it "pythonish"? Very. This is Python's response to the "Singleton" pattern that some other languages require: put attributes directly at a module level, import that module wherever you need those attributes, and you're guaranteed a single shared instance of the module. A good example is a module containing a set of attributes defining the configuration for the application. -- \ "I was sleeping the other night, alone, thanks to the | `\ exterminator." -- Emo Philips | _o__) | Ben Finney From david at boddie.org.uk Wed Feb 14 13:12:36 2007 From: david at boddie.org.uk (David Boddie) Date: Wed, 14 Feb 2007 19:12:36 +0100 Subject: Newbie Question References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> <1171361096.528759.231380@a34g2000cwb.googlegroups.com> Message-ID: On Tuesday 13 February 2007 11:04, bruno.desthuilliers at gmail.com wrote: > To be true, I don't know if any of these toolkits (GTK, wxWindows, QT) > and their GUIDesigners have the features you like in Delphi. What I > know is that: > 1/ these three toolkits have everything *needed* to write serious GUI > apps > 2/ they are all (more or less) portable > 3/ the first two are free software And, for the sake of completeness, it should be mentioned that the third is available under the GPL, which is a Free Software license. David From gagsl-py at yahoo.com.ar Wed Feb 14 01:58:22 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 03:58:22 -0300 Subject: How can this Perl regular expression be expressed in Python? References: <8WvAh.14675$O02.10228@newssvr11.news.prodigy.net> Message-ID: En Wed, 14 Feb 2007 04:11:37 -0300, John Nagle escribi?: > Gabriel Genellina wrote: >> En Wed, 14 Feb 2007 01:07:33 -0300, John Nagle >> escribi?: >> >>> Here's a large Perl regular expression, from a Perl address parser in >>> CPAN: >>> >>> use re 'eval'; >>> $Addr_Match{street} = qr/ >>> (?: >>> # special case for addresses like 100 South Street >>> (?:($Addr_Match{direct})\W+ (?{ $_{street} = $^N >>> }) >>> ($Addr_Match{type})\b (?{ $_{type} = $^N >>> })) > Incidentally, does anybody know what "$^N" means in Perl? That > abbreviation isn't in the list of special variables. From the context it appears to be the "last matched group", or something like that... but best look for some authoritative answer. -- Gabriel Genellina From jan.m.danielsson at gmail.com Mon Feb 26 18:10:34 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 27 Feb 2007 00:10:34 +0100 Subject: Preallocate? -- potentially brain dead question about performance Message-ID: <45e368ea$1@griseus.its.uu.se> Hello all, I have a list which contains a bunch of tuples: mylist = [ ('1', 'Foobar'), ('32', 'Baz'), ('4', 'Snorklings') ] (The list can potentially be shorter, or much longer). Now I want to take the first element in each tuple and store it in a list (to use in a Set later on). Which would You prefer of the following: newlist = [ ] for e in mylist: newlist.append(int(e[0])) ..or.. newlist = [ None ] * len(mylist) for i in range(len(mylist)): newlist.append(int(e[0])) To me, the second one is more appealing, when I think in terms of risk of memory fragmentation, etc. But since Python is such a high level language, I'm not sure my traditional reasoning applies. -- Kind regards, Jan Danielsson From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 10:33:41 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Feb 2007 02:33:41 +1100 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: On Fri, 16 Feb 2007 09:07:02 -0600, Edward K Ream wrote: >>> That's the proof. Can you find a flaw in it? >> No, but it doesn't matter. There's no particular reason why you have to >> write "print (whatever)" in your code. What you need is *some function* >> that is capable of duplicating the functionality of print, > > Precisely wrong. Are you trying to say that the name "print" is more important to you than the functionality? If not, then I have no idea why you say I'm wrong. > The title of this thread is 'the end of print', and the > whole point of my comments is that spelling matters. That might be the point you are trying to make, but you haven't succeeded. > I would have absolutely no objection to the pep if it specified some other > name for an 'official' print function. Pick any name, preferably longer > than two characters, that does not conflict with either an existing global > function or module. Huh? Now you're just not making sense. If Python 3 dropped the print statement and replaced it with official_print_function(), how would that help you in your goal to have a single code base that will run on both Python 2.3 and Python 3, while still using print? In software development there is a common saying: "Good, Fast, Cheap -- Pick any two". The same holds here: Keep the print name; Keep the print functionality; Keep a single code base. Pick any two. -- Steven. From jeff at taupro.com Sun Feb 18 03:52:41 2007 From: jeff at taupro.com (Jeff Rush) Date: Sun, 18 Feb 2007 02:52:41 -0600 Subject: Extracurricular Activities at PyCon This Year Message-ID: <45D813D9.6020806@taupro.com> At PyCon this year we are having a significant number of activities besides the keynotes and talks. One group of those are the birds-of-a-feather gatherings being held in the evenings. The Python community consists of a number of smaller communities and we're encouraging them to hold meetings, dinners and other activities at PyCon this year. The organizers have tried to leave room in the busy schedule for these to happen and of course for some non-Python social BoFs as well. Here are the BoFs with which you have the opportunity to get involved: * Python in Education * Python in Science * Healthcare and Python * A Content Repository Standard for Python * Jython Development * Django * Pylons Web Framework * Trac Users and Developers * Keysigning Party * Tech that Runs the Python Conference * Users of Bazaar Version Control/Launchpad * Buildbot Users and Developers * Python Advocacy Community Forum * Texas Regional Unconference Dinner Meet * PyGame Programming/Playing Clinic * Board Game Socials * Bowling * Climbers You can check them out at: http://us.pycon.org/TX2007/BoF The room/offsite schedule is listed at the bottom of that page but many of the groups have not yet declared when and where they are meeting. Nudges are welcome. The other set of activities at PyCon are the 4-days of code sprints held at the end of the conference. A sprint is a focused development session, in which developers gather in a room and focus on building a particular subsystem. A sprint is organized with a coach leading the session. The coach sets the agenda, tracks activities, and keeps the development moving. The developers will sometimes work in pairs using the Extreme Programming (XP) pair programming approach. The sprints that have announced so far are: * Work towards Zope 3.4 release * Fun Educational Software for "Playful Learning" * PyCon-Tech: Improve the convention software * Zope 3 Learner's Circle * Python Job Board * Django * Trac * Jython * Docutils: squash bugs & add features * TurboGears * Write a Game * Create a Win32 version of MySQLdb under Python 2.5 * SchoolTool & CanDo Sprint coaches should plan for an introductory session on Sunday afternoon or Monday morning, to help attendees get started. This might involve helping them to get SVN or CVS installed and checking out the development tree, talking about the software's architecture, or planning what the four-day sprint will try to accomplish. You can read more at: http://us.pycon.org/TX2007/Sprinting and even add your name to particular sprint wiki pages, to encourage them to happen. See you later this week. Get plenty of sleep beforehand, you won't get much at PyCon this year! Jeff Rush PyCon Co-Chair From jstroud at mbi.ucla.edu Fri Feb 2 00:49:11 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 01 Feb 2007 21:49:11 -0800 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: Ben Finney wrote: > James Stroud writes: > > >>Peter Otten wrote: >> >>>Chris wrote: >>> >>>>I am trying to overload the __invert__ operator (~) such that it >>>>can take a second argument, >>> >>>>>>x ~ x >>> >>> File "", line 1 >>> x ~ x >>> ^ >>>SyntaxError: invalid syntax >> >>Seems an arbitrary limitation. Consider >> - x >>and >> x - y > > > Both of which are meaningful syntax in Python, hence the Python parser > accepts them and knows what operations to call on the objects. > > >>Which is inconsistent with limiting ~ to a unary operation. > > > Which is the only Python-meaningful way to use that operator, and > translates to an appropriate call on the object. > > The Python runtime parser is designed to parse Python, not some > arbitrary language that someone chooses to implement in Python. > You haven't addressed why the limitation isn't arbitrary. You have only told us what we already know. So your argument, therefore, is not one. James From gibo at gentlemail.com Mon Feb 19 19:50:11 2007 From: gibo at gentlemail.com (GiBo) Date: Tue, 20 Feb 2007 13:50:11 +1300 Subject: Checking for EOF in stream In-Reply-To: <12tkgeh32duee72@corp.supernews.com> References: <12tkgeh32duee72@corp.supernews.com> Message-ID: <45DA45C3.2000707@gentlemail.com> Grant Edwards wrote: > On 2007-02-19, GiBo wrote: >> Hi! >> >> Classic situation - I have to process an input stream of unknown length >> until a I reach its end (EOF, End Of File). How do I check for EOF? The >> input stream can be anything from opened file through sys.stdin to a >> network socket. And it's binary and potentially huge (gigabytes), thus >> "for line in stream.readlines()" isn't really a way to go. >> >> For now I have roughly: >> >> stream = sys.stdin >> while True: >> data = stream.read(1024) > if len(data) == 0: > break #EOF >> process_data(data) Right, not a big difference though. Isn't there a cleaner / more intuitive way? Like using some wrapper objects around the streams or something? GiBo From polivare at lilyphilia.net Mon Feb 12 17:41:32 2007 From: polivare at lilyphilia.net (Patricio Olivares) Date: 12 Feb 2007 14:41:32 -0800 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: Message-ID: <1171320092.674506.192770@v33g2000cwv.googlegroups.com> On Feb 12, 3:06 pm, "krishnakant Mane" wrote: > os.start does not work.. attribute error. > regards. > Krishnakant. It's os.system('thefile') or os.system('start thefile') but that's windows only. It seems like there's no platform-independent way to launch a preferred application to open a file, but... based on I would suggest (by looking at sys.platform) to use "start" on windows, "open" on mac, and on linux to use the xdg-open shell script which is part of XdgUtils... It works standalone. Even seems it would not take too much effort to port it to python if you want. From gabriel.altay at gmail.com Mon Feb 26 15:54:39 2007 From: gabriel.altay at gmail.com (gabriel.altay at gmail.com) Date: 26 Feb 2007 12:54:39 -0800 Subject: getting info on remote files Message-ID: <1172523279.352084.92920@t69g2000cwt.googlegroups.com> hello everyone, Im trying to write some python code that will return information (file size, last modified ...) about files on a remote computer that I have 'no password' ssh access to. Ive been able to write code that logs on to remote computers and I can issue a command using, os.system(ssh blah.blah.blah.org "ls -l myfile") but how do I store the information returned by the ls command into a variable. The primary goal of this is to 1. check file size on remote computer 2. scp file to local computer 3. make sure file size of copy and original are the same any suggestions would be appreciated thanks gabe From skip at pobox.com Fri Feb 2 18:20:03 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 2 Feb 2007 17:20:03 -0600 Subject: Python does not play well with others In-Reply-To: <7xirek9pdt.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> Message-ID: <17859.50979.256973.695048@montanaro.dyndns.org> Paul> Numpy should certainly be included and I think there are efforts Paul> in that direction. There is also a movement to choose a web Paul> framework to include and Django might be a good choice. Right off the bat you run into problems. While Numpy is popular in the scientific computing community it's just dead weight for people without numerical computing application needs. Besides, the Enthought folks seem to be doing a pretty good job building a Python distribution geared toward scientific computing. (Hint: Numpy is just the tip of that particular iceberg.) The Pylons, web.py, Karrigell, Webware and TurboGears people might (rightly) feel slighted if you include Django but not their frameworks. Where would you stop? At the boundaries of your particular application interests? Skip From iansan at gmail.com Thu Feb 8 18:49:56 2007 From: iansan at gmail.com (IamIan) Date: 8 Feb 2007 15:49:56 -0800 Subject: Regexp not performing the same in FTP versus Python Message-ID: <1170978596.337428.261110@h3g2000cwc.googlegroups.com> Hello all, I'm trying to use a regular expression in an FTP script to list certain files. When run in a standard FTP session the command: dir ????????.??[oOdDnNmM]* returns 48 files. When I use the following Python script it prints roughly 12 files (a subset of the 48), ending with 'None': import ftplib, traceback ftp = ftplib.FTP('host') ftp.login(user='user', passwd='pass') try: admFiles = ftp.dir('????????.??[oOdDnNmM]*') print admFiles except: traceback.print_exc ftp.quit() Is my Python syntax off? Thank you. From pwuertz at students.uni-mainz.de Thu Feb 22 23:30:21 2007 From: pwuertz at students.uni-mainz.de (Peter Wuertz) Date: Fri, 23 Feb 2007 05:30:21 +0100 Subject: export an array of floats to python In-Reply-To: <1172169365.508476.279360@a75g2000cwd.googlegroups.com> References: <1172169365.508476.279360@a75g2000cwd.googlegroups.com> Message-ID: Thank you! Thats the complete solution *g* From gagsl-py at yahoo.com.ar Sat Feb 10 05:03:28 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 07:03:28 -0300 Subject: Need a cross-platform way to execute binary References: <1171098220.101483.138910@q2g2000cwa.googlegroups.com> Message-ID: En Sat, 10 Feb 2007 06:03:40 -0300, techtonik escribi?: > Hello, everyb. > > Does anybody know simple cross-platform method of probing if > executable binary is available and launching it. > > > Problem no.1: test if executable file is available > I'll take windows platform as the most relevant in this case. > os.access() doesn't handle env PATHEXT and can't detect if a given > path would be executable or not. Here "executable" means file that > could be be launched by system() (if there are any other ways - I'd be > happy to know them) > > Suppose I have "ufo2exe" executable two directories up. >>>> os.access("../../ufo2map.exe", os.X_OK) > True > > However... >>>> os.access("../../ufo2map", os.X_OK) > False That's right - such file does not exist. On Windows, in general, X_OK is the same as F_OK: for any existing file, whatever name or extension, returns True. Permissions are managed thru ACL and this simple function does NOT consider them. > > But... >>>> os.system("..\..\ufo2map") > ---- ufo2map 1.0 ---- > 0 (Beware of single \ on normal strings!) Use win32api.FindExecutable; should return the full path to ufo2map.exe. "foo.txt" would return notepad.exe (or whatever you have associated to text files). That is exactly what would be launched by os.system("foo.txt") > Problem no.2: launch executable file > The same windows platform again. All python commands are using forward > slashes for paths, but system doesn't handle this situation (it could > at least try to convert immediate forward slashes to backwards) Use os.path.normpath on the filename. (If you got it from FindExecutable above, that would not be needed) > os.access() thinks this file is executable, but os.system() fails ... >>>> os.access("../../ufo2map.exe", os.X_OK) > True >>>> os.system("../../ufo2map.exe") > '..' is not recognized as an internal or external command, > operable program or batch file. > 1 > > the contrary - access() fails to tell this path can be launched, but > file Is executable, ... >>>> os.access("..\..\ufo2map", os.X_OK) > False Same as above - such file does not exist. >>>> os.system("..\..\ufo2map") > ---- ufo2map 1.0 ---- > 0 > Is there any workaround in Python or I have to stick with platforms- > specific quirks? > I'm using Python 2.4.2 I think you will have to treat each platform differently. Just for starting, the concept of "executable" is not the same across platforms. But you could make some generic functions (with different implementations on different platforms). -- Gabriel Genellina From larry.bates at websafe.com Mon Feb 12 10:54:19 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Feb 2007 09:54:19 -0600 Subject: favourite editor In-Reply-To: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> Message-ID: <45D08DAB.6080908@websafe.com> azrael wrote: > Since i'm new on this forum, and first time meeting a python comunity, > i wanted to ask you for your python editors. > > Im looking for some good python editor, with integrated run function, > without having to set it up manualy like komodo. > I found the pyscripter, and it has all i need, but it's unsatble. > bloated. it crashes when i close an yplication window run by python > from pyscripter. please. tell me a good one with buil in run (<-very > important) and nice gui. if possible to suport projects, code > highlighting, code completition, class browser, python comand line > (>>>), traceback. > > I didn't take a look on vista (and i dont want to), but i hope they > improved the notepad. > I use pyscripter as my primary editor and have NEVER had it crash or do anything that could be considered "unstable". It has best GUI of any Windows editor I've seen. I have to admit that I tend to run my programs from a console window because it forces a clean load of the program (no runtime environment "leftovers") and if I'm doing wxPython or other GUI apps, they almost always interfere in some way with the editors (same was true for ActiveState). Maybe you could give that a try. -Larry From hg at nospam.org Mon Feb 5 05:21:43 2007 From: hg at nospam.org (hg) Date: Mon, 05 Feb 2007 11:21:43 +0100 Subject: Will Python Run On Microsoft Vista? References: <1170695324.106530.157720@v45g2000cwv.googlegroups.com> Message-ID: slogging_away wrote: > I know, I know - flame away but its not clear to me if Python will run > on a system running Microsoft Vista. Is anyone successfully running > Python on Vista? If so, is it what version of Python are you > running? I'm ordering a new system and if Python won't work on Vista > then it will definately influence the OS selection. > > Thanks in advance! OK so it does not ;-) ! From Bulkan at gmail.com Mon Feb 19 01:03:41 2007 From: Bulkan at gmail.com (placid) Date: 18 Feb 2007 22:03:41 -0800 Subject: What is more efficient? In-Reply-To: References: Message-ID: <1171865021.561877.24630@p10g2000cwp.googlegroups.com> On Feb 19, 4:38 pm, Gary Herron wrote: > Karlo Lozovina wrote: > > Let's say I have a class with few string properties and few integers, and > > a lot of methods defined for that class. > > > Now if I have hundreds of thousands (or even more) of instances of that > > class - is it more efficient to remove those methods and make them > > separate functions, or it doesn't matter? > > > Thanks... > > It is not noticeably more or less efficient in either memory or > execution speed. well lucky i wont be designing/creating a new language! > > Both method and function code is compiled and stored once in either the > class name space (for the method) or the module name space (for the > function), and the lookup of either one is a single lookup in the > appropriate name space. > > Actually the method lookup requires one extra step: First look for the > method in the instance (which fails) and then look for it in the class > (which succeeds). But that extra look up is highly optimized and > probably not noticeable. The number of methods/functions may slow things > up, but it will affect either name space equally. > > Gary Herron From GatlingGun at gmail.com Thu Feb 1 05:21:38 2007 From: GatlingGun at gmail.com (TOXiC) Date: 1 Feb 2007 02:21:38 -0800 Subject: Help me with this!!! Message-ID: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> Hi all, I've this code: regex = re.compile(r"(?si)(\x8B\xF0\x85\xF6)(?P.*) (\xC6\x44\x24)",re.IGNORECASE) file = open(fileName, "rb") for line in file: if (match): print line file.close() It search a text inside that hex value. It works perfecly on a txt file but if I open a binary file (.exe,.bin ecc...) with the same value it wont work, why? Please help! From B.Ogryczak at gmail.com Thu Feb 1 12:25:19 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 1 Feb 2007 09:25:19 -0800 Subject: Question about a single underscore. In-Reply-To: References: Message-ID: <1170350719.663044.319960@m58g2000cwm.googlegroups.com> On Feb 1, 5:52 pm, "Steven W. Orr" wrote: > I saw this and tried to use it: > > ------------------><8------------------- const.py------------- [...] > sys.modules[__name__]=_const() __name__ == 'const', so you?re actually doing const = _const() From thermostat at gmail.com Thu Feb 1 14:51:10 2007 From: thermostat at gmail.com (Dan) Date: 1 Feb 2007 11:51:10 -0800 Subject: xml.dom.minidom memory usage Message-ID: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> I'm using python's xml.dom.minidom module to generate xml files, and I'm running into memory problems. The xml files I'm trying to create are relatively flat, with one root node which may have millions of direct child nodes. Here's an example script: #!/usr/bin/env python import xml.dom.minidom def gen_xml(n): doc = xml.dom.minidom.Document() root = xml.dom.minidom.Element("foo") root.ownerDocument = doc root.setAttribute("one", "1") doc.appendChild(root) for x in xrange(n): elem = xml.dom.minidom.Element("bar") elem.ownerDocument = doc elem.setAttribute("attr1", "12345678") elem.setAttribute("attr2", "87654321") root.appendChild(elem) return doc if I run gen_xml(1000000), my python process ends up using all my 90% of my memory, and the system ends up thrashing (Linux, P4, 1G ram, python 2.4.3) . So, my questions are (1) am I doing something dumb in the script that stops python from collecting temp garbage? (2) If not, is there another reasonable module to generate xml (as opposed to parsing it), or should I just implement my own xml generation solution? Thanks, -Dan From arkanes at gmail.com Thu Feb 1 14:34:37 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 1 Feb 2007 13:34:37 -0600 Subject: how to make a python windows service know it's own identity In-Reply-To: <1170357853.916290.252460@v33g2000cwv.googlegroups.com> References: <1170264160.124454.6270@j27g2000cwj.googlegroups.com> <45C23B18.5050000@websafe.com> <1170357853.916290.252460@v33g2000cwv.googlegroups.com> Message-ID: <4866bea60702011134hc624951jdaad0cee0761c0cd@mail.gmail.com> On 1 Feb 2007 11:24:13 -0800, Chris Curvey wrote: > On Feb 1, 2:10 pm, Larry Bates wrote: > > Chris Curvey wrote: > > > Hi all, > > > > > I have used the win32com libraries to set up a service called > > > MyService under Windows. So far, so good. Now I need to run multiple > > > copies of the service on the same machine. I also have that working. > > > For monitoring and logging, I'd like each instance of the service to > > > know it's own identity (MyService1, MyService2, etc.) > > > > > But I can't quite seem to grasp how to do this. In the code below, > > > the command line parameter "-i" gives the service an identity, but how > > > do I get the service to understand it's identity when it is started? > > > > > Many thanks! > > > > > class MyService(win32serviceutil.ServiceFramework): > > > """NT Service.""" > > > > > _svc_name_ = "MyService" > > > _svc_display_name_ = "My Service" > > > > > _id_ = '' > > > > > def SvcDoRun(self): > > > provider = MyServiceClass(identifier=self._id_) > > > provider.start() > > > > > # now, block until our event is set... > > > win32event.WaitForSingleObject(self.stop_event, > > > win32event.INFINITE) > > > > > # __init__ and SvcStop snipped > > > > > ########################################################################### > > > if __name__ == '__main__': > > > import optparse > > > parser = optparse.OptionParser() > > > parser.add_option("-i", "--identifier", dest="identifier") > > > (opts, args) = parser.parse_args() > > > if opts.number is not None: > > > MyService._svc_name_ += opts.identifier > > > MyService._svc_display_name_ += opts.identifier > > > MyService._provider_id_ = opts.identifier > > > > > win32serviceutil.HandleCommandLine(MyService, > > > customInstallOptions="i:") > > > > What is your use case for this? Why not make a single server > > process multiple providers (store them in a list or other > > container)? > > > > -Larry Bates > > The use case is that I have a queue of jobs that need to run. My > service connects to a central "distributor" server, which hands out > jobs to complete. I'd like to be able to run multiple copies of the > distributed service so that I can make the most use of each machine > where they run. (I'm not certain of the thread safety of some of the > libraries I'm using, so I'm leery of going the multi-threaded route) > Anyway, when my service gets a job to process, I'd like to know which > copy of the service is working on which job. So I want my log > messages to look like this: > > Job 123: Host: alpha Service: MyService A > Job 124: Host: alpha Service: MyService B > Job 124: Host: beta Service: MyService C > > Is that clear, or have I muddied the waters? > Windows services are identified by name, so if you're running multiple services they will need to have unique _svc_name members. From MrJean1 at gmail.com Thu Feb 8 19:58:50 2007 From: MrJean1 at gmail.com (MrJean1) Date: 8 Feb 2007 16:58:50 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1170982730.209872.229600@j27g2000cwj.googlegroups.com> On Feb 8, 6:03 am, "Srikanth" wrote: > Yes, > > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. > > Thanks, > Srikanth Here is a list . My preference is SciTE on Linux and Windows and BBebit on MacOS . None are quite IDEs though. /Jean Brouwers From silovana.vjeverica at com.gmail Fri Feb 9 16:09:38 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Fri, 9 Feb 2007 22:09:38 +0100 Subject: Django, one more newbie question Message-ID: Umm, can somebody tell me which language is this one: {% if latest_poll_list %}
    {% for poll in latest_poll_list %}
  • {{ poll.question }}
  • {% endfor %}
{% else %}

No polls are available.

{% endif %} Whole tutorial is on this page: http://www.djangoproject.com/documentation/tutorial3/ endfor, endif, {{? :) -- http://www.nacional.hr/articles/view/23894/23 From shadabsayani at yahoo.com Sat Feb 17 01:54:30 2007 From: shadabsayani at yahoo.com (Shadab Sayani) Date: Sat, 17 Feb 2007 06:54:30 +0000 (GMT) Subject: WHAT IS THIS? In-Reply-To: Message-ID: <20070217065430.63781.qmail@web38712.mail.mud.yahoo.com> HI, I think it is safe to remove it.As far as I know no windows OS core programs use python Cheers, Shadab. --- Captain wrote: > Just bought a new PC with Windows XP Media Edition. > I have two entries in > the "Add or Remove Programs" section of Control > Panel, but there is no > corresponding item in the Start Menu. One entry > says: Python 2.2.3 and the > other says: Python 2.2 pywin32 extensions > (build203).. The size for each is > 29.28mb. I gather Python is a programming language, > but I am wondering why > it was installed on my PC, and is it safe to remove > it? I have no intention > of learning the program. Thanks in advance > > > -- > http://mail.python.org/mailman/listinfo/python-list > Send instant messages to your online friends http://uk.messenger.yahoo.com From bdesth.quelquechose at free.quelquepart.fr Tue Feb 6 16:39:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 22:39:10 +0100 Subject: Python editor In-Reply-To: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> Message-ID: <45c8ee60$0$1026$426a74cc@news.free.fr> BBands a ?crit : > No, no, no, this is not an invitation to the editor wars. > > I have been using Jos? Cl?udio Faria's superb Tinn-R, http://www.sciviews.org/Tinn-R/, > with the R language, http://www.r-project.org/. This editor allows you > to send code to the R shell for execution. You can easily send a line, > the selection, the balance after the cursor or the whole script. > > I have recently decided to move this project to Python instead of R. > However, I miss the interaction with the shell a la Tinn-R. Do any of > the Python editors support this feature? I would be especially > interested in using IPython as the shell. emacs From muntasir.khan at gmail.com Mon Feb 19 10:16:17 2007 From: muntasir.khan at gmail.com (Muntasir Azam Khan) Date: 19 Feb 2007 07:16:17 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <1171898177.784761.283130@s48g2000cws.googlegroups.com> On Feb 17, 3:22 am, ifti_cr... at yahoo.com wrote: > I am VB6 programmer and wants to start new programming language but i > am unable to deciced. > > i have read about Python, Ruby and Visual C++. but i want to go > through with GUI based programming language like VB.net > > so will you please guide me which GUI based language has worth with > complete OOPS Characteristics > > will wait for the answer > > hope to have a right direction from you Programmer > > Regards > Iftikhar > itzon... at yahoo.com There is no other GUI based programming language like VB. That's because there is no such thing as a GUI based programming language. If you want to learn a real general purpose programming language try learning python. If you are only interested in making GUI's for windows applications, better stick with VB or any of the other .NET languages. From jth02 at arcor.de Thu Feb 8 04:17:07 2007 From: jth02 at arcor.de (Jens Theisen) Date: 08 Feb 2007 09:17:07 +0000 Subject: idea for testing tools References: <87ejp1mzla.fsf@arcor.de> <45ca5f5a$0$26771$426a74cc@news.free.fr> Message-ID: <8764adm2jw.fsf@arcor.de> Bruno Desthuilliers writes: > http://codespeak.net/py/current/doc/test.html#assert-with-the-assert-statement Ok, I didn't come across this before. I didn't work for me though, even the simple case #!/usr/bin/python a = 1 b = 2 def test_some(): assert a == b didn't reveal the values for a and b, though some more complex cases showed something. -- Cheers, Jens From gagsl-py at yahoo.com.ar Sat Feb 24 23:54:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 01:54:11 -0300 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) References: <45e06bab$0$20809$5fc30a8@news.tiscali.it> <45E0D859.1040109@earthlink.net> Message-ID: En Sat, 24 Feb 2007 21:29:13 -0300, Charles D Hixson escribi?: > Sorry, the "script" hasn't been written. But Python apparently *won't* > (automatically) do what I want, which is create a class whose > sub-classes automatically have unique class variables of a determined > form such that I can do a hierarchical search through them. (I could > plausibly handle this for the instance case but "class variables are > static", so it looks like I can't do it for class variables in a > straightforward manner. This looks like it's going to demand a factory > method, or some alternate approach. (Not sure yet which I'll choose.) "Class variables are static" until you assign to them a new value, then become instance (normal) attributes. class A: x = 1 a = A() a.x # prints 1 a.x = 100 a.x # prints 100 A.x # still 1 b = A() b.x # still 1 > What I'm looking for is a reasonable way to implement what Marvin Minsky > calls Panologies. These are "objects" (my term) with sufficient local > intelligence to try alternative models of a situation until they find > one that's appropriate. E.g., is this being operated on as a physical > transaction or a social transaction. (Yes, it is physically happening, > and it's taking place in physical space, but different models yield > different analyses of what's happening. Which is appropriate for the > situation currently being evaluated?) You may be interested on Acquisition, a concept from Zope2. Objects not only have behavior by nature (inheritance) but nurture (acquisition). *Where* an object is contained (or, *how* you reach to it), determines its behavior as well as *what* it is. > P.P.S.: This isn't all loss. I'm expecting that eventually I'll start > running into performance problems, and at that point it would be > necessary to start translating into a native-compiler language. Your design seems to be too dynamic to be feasible on a more static language. -- Gabriel Genellina From roche.alexis at gmail.com Fri Feb 16 04:02:59 2007 From: roche.alexis at gmail.com (roche.alexis at gmail.com) Date: 16 Feb 2007 01:02:59 -0800 Subject: Compression library Message-ID: <1171616579.762722.81270@v45g2000cwv.googlegroups.com> Hi all, I'm looking for a library in python containing severall compression algorithms like RLE, Deflate, LZ77-78-W, Huffman,...... do someone know if such of this type of lib exists?? Thanks From http Tue Feb 13 19:20:58 2007 From: http (Paul Rubin) Date: 13 Feb 2007 16:20:58 -0800 Subject: Comparing lists ... References: <45d253e8$0$449$426a74cc@news.free.fr> Message-ID: <7x64a5wpw5.fsf@ruckus.brouhaha.com> Loic writes: > I want to design a function to compare lists and return True only if > both lists are equal considering memory location of the list. > I suppose it would be the equivalent of comparing 2 pointers in c++ Use the "is" keyword. print (l1 is l2) print (l0 is l2) From skip at pobox.com Thu Feb 1 12:49:49 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Feb 2007 11:49:49 -0600 Subject: SWIG overhead In-Reply-To: <1170351559.493523.45020@a75g2000cwd.googlegroups.com> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> <1170351559.493523.45020@a75g2000cwd.googlegroups.com> Message-ID: <17858.10301.35576.673999@montanaro.dyndns.org> John> Bottom line: the c-types module was a lot smaller, in Python, and John> completely comprehensible. And while I didn't measure the John> performance, I doubt if it was slower. One advantage SWIG (or Boost.Python) has over ctypes is that it will work with C++. Skip From sjmachin at lexicon.net Wed Feb 21 01:45:16 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 22:45:16 -0800 Subject: Regex Speed In-Reply-To: <1172018440.659870.195010@h3g2000cwc.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172013317.943062.303110@t69g2000cwt.googlegroups.com> <1172018440.659870.195010@h3g2000cwc.googlegroups.com> Message-ID: <1172040316.797307.222930@h3g2000cwc.googlegroups.com> On Feb 21, 11:40 am, garri... at gmail.com wrote: > On Feb 20, 4:15 pm, "John Machin" wrote: > > > What is an "exclusionary set"? It would help enormously if you were to > > tell us what the regex actually is. Feel free to obfuscate any > > proprietary constant strings, of course. > > My apologies. I don't have specifics right now, but it's something > along the line of this: > > error_list = re.compile(r"error|miss|issing|inval|nvalid|math") > exclusion_list = re.complie(r"No Errors Found|Premature EOF, stopping > translate") > > for test_text in test_file: > if error_list.match(test_text) and not > exclusion_list.match(test_text): > #Process test_text > > Yes, I know, these are not re expressions, but the requirements for > the script specified that the error list be capable of accepting > regular expressions, since these lists are configurable. You could do a quick check on the list of patterns; if they are simple strings (no ()+*?[] etc), then you could use Danny Yoo's ahocorasick module (from http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/): >>> import ahocorasick as ac >>> gadget = ac.KeywordTree() >>> for text in "error|miss|issing|inval|nvalid|math".split('|'): ... gadget.add(text) ... >>> gadget.make() >>> def showall(machine, line): ... startpos = 0 ... while 1: ... result = machine.search(line, startpos) ... if not result: return ... beg, end = result ... print beg, end, repr(line[beg:end]) ... startpos = beg + 1 ... >>> showall(gadget, 'the hissing misses invalidated erroneous mathematics') 5 11 'issing' 12 16 'miss' 19 24 'inval' 20 26 'nvalid' 41 45 'math' >>> showall(gadget, 'the hissing misses invalidated terror mathematics') 5 11 'issing' 12 16 'miss' 19 24 'inval' 20 26 'nvalid' 32 37 'error' 38 42 'math' >>> showall(gadget, 'these are not the droids that you are looking for') >>> But of course you would just use a simple search() per line -- I'm just showing you that it works :-) > > > What system calls? Do you mean running grep as a subprocess? > > Yes. While this may not seem evil in and of itself, we are trying to > get our company to adopt Python into more widespread use. I'm guessing > the limiting factor isn't python, but us python newbies missing an > obvious way to speed up the process. You (can't/don't have to) write everything in Python or any other single language. One of Pythons's very good points is that you can connect it to anything -- or if you can't, just ask in this newsgroup :-) Look, boss, yesterday we got it running grep; today we're calling a module written in C; not bad for a bunch of newbies, eh? > And python 2.5.2. 2.5.2? Who needs crystal balls when you've got a time machine? Or did you mean 2.5? Or 1.5.2 -- say it ain't so, Joe! Cheers, John From abhra.haldar at gmail.com Mon Feb 26 17:45:03 2007 From: abhra.haldar at gmail.com (ahaldar) Date: 26 Feb 2007 14:45:03 -0800 Subject: pickle problem - frexp() out of range Message-ID: <1172529903.332360.124400@z35g2000cwz.googlegroups.com> Hi: I have some large data structure objects in memory, and when I attempt to pickle them, I get the following error: SystemError: frexp() out of range Are there some objects that are just too large to serialize, and if so, is there an easy workaround without breaking up the object and reconstructing it during deserialization? Here's the code I use to pickle the object: f = open(dir+file, "w+b") pickle.dump(structure, f, protocol=2) # throws error f.close() - abhra From franz.steinhaeusler at gmx.at Fri Feb 2 13:42:42 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhäusler) Date: Fri, 02 Feb 2007 19:42:42 +0100 Subject: Ubunu - Linux - Unicode - encoding References: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> <1m4tymklxmhra.1lcm42759ok57.dlg@40tude.net> <39h4s2h1eck0agttvgl95ntp3oj5smrt0k@4ax.com> Message-ID: On Fri, 2 Feb 2007 00:12:45 +0100, Alan Franzoni wrote: >Il Thu, 01 Feb 2007 20:57:53 +0100, Franz Steinh?usler ha scritto: > >> If I copy files with german umlauts (??? and strong 's' ?), these >> filenames are not copied properly, and that characters are replaces >> by little square symbols. > >Yes... I, myself, am italian, and I found no problem in using accented >letter (?????). Since you say there's a problem as well in Nautilus and >other Ubuntu software, I suppose there's something wrong with your linux >setup, not with Python. > >Or, at least: you should try solving that problem first, then check what >happens with python. > >Try appending this options in your fstab as hda1 mount options: > >iocharset=iso8859-15 > >unmount & remount and check what does happen. Thank you again, I will give it a try! -- Franz Steinhaeusler From stargaming at gmail.com Sun Feb 11 16:18:58 2007 From: stargaming at gmail.com (Stargaming) Date: Sun, 11 Feb 2007 22:18:58 +0100 Subject: randomly generate n of each of two types In-Reply-To: References: Message-ID: Alan Isaac schrieb: > I need access to 2*n random choices for two types > subject to a constraint that in the end I have > drawn n of each. I first tried:: > > def random_types(n,typelist=[True,False]): > types = typelist*n > random.shuffle(types) > for next_type in types: > yield next_type > > This works but has some obvious costs. > To avoid those I considered this instead:: > > def random_types(n,typelist=[True,False]): > type0, type1 = typelist > ct0, ct1 = 0,0 > while ct0+ct1<2*n: > if random.random() < ((n-ct0)/(2*n-ct0-ct1)): > next_type = type0 > ct0 += 1 > else: > next_type = type1 > ct1 += 1 > yield next_type > > Does this seem a good way to go? Comments welcome. I think there's any easier way using random's function `shuffle`. >>> from random import shuffle >>> def randomly(n, types): ... types *= n ... shuffle(types) ... for x in types: yield x ... >>> randomly(1, [True, False]) >>> list(randomly(1, [True, False])) [True, False] >>> list(randomly(2, [True, False])) [True, False, True, False] >>> list(randomly(4, [True, False])) [False, True, False, False, False, True, True, True] You can even do this with an arbitrary number of choices: >>> list(randomly(2, [True, False, None, NotImplemented])) [NotImplemented, None, NotImplemented, False, False, None, True, True] Notice that this method works in-place, ie >>> a = [True, False] >>> list(randomly(2, a)) [False, False, True, True] >>> a # a changed! [False, False, True, True] This can be changed by creating a copy, though. HTH, Stargaming From bearophileHUGS at lycos.com Fri Feb 2 12:59:45 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Feb 2007 09:59:45 -0800 Subject: compound statement from C "?:" In-Reply-To: References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> Message-ID: <1170439185.917760.135640@k78g2000cwa.googlegroups.com> Jussi Salmela: > In this particular case you don't need the ternary operator: > print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) The last newline is probably unnecessary. This seems be a bit more readable: print "I saw", n, "car" + ("", "s")[n != 1] With Python 2.5 this looks better: print "I saw", n, "car" + ("" if n == 1 else "s") Or the vesion I like better: print "I saw", n, ("car" if n == 1 else "cars") Those () aren't necessary, but they help improve readability, and avoid problems with operator precedence too. That if has a quite low precedence. Bye, bearophile From bignose+hates-spam at benfinney.id.au Sun Feb 25 17:18:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 26 Feb 2007 09:18:25 +1100 Subject: Help on object scope? References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> <1172440275.868863.91120@k78g2000cwa.googlegroups.com> Message-ID: <87vehp3mq6.fsf@benfinney.id.au> bmaron2 at hotmail.com writes: > My code will have about 10 of these global objects, all of which > interact with eachother. It seems silly to have to pass 10 > parameters around to each instance I work with. Yes. A better solution would be to put them inside a module, and import that module. Then the objects are available at any level as attributes of the imported module. ===== foo.py ===== def spam(): return max(eggs, ham) eggs = 17 ham = 12 ===== ===== bar.py ===== import foo def main(): spork = do_something_with(foo.eggs) foo.spam(spork) ===== -- \ "Know what I hate most? Rhetorical questions." -- Henry N. Camp | `\ | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Sun Feb 25 21:55:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 23:55:24 -0300 Subject: Weakref problem: no way to get original object from proxy object? References: Message-ID: En Sun, 25 Feb 2007 19:07:38 -0300, John Nagle escribi?: > Is there some way to get a strong ref to the original object back > from a weakref proxy object? I can't find any Python function to do > this. > ".ref()" doesn't work on proxy objects. Add a method to the original class that just returns self. About your backref function: Yes, I usually use something like that, it's annoying having to handle None always. -- Gabriel Genellina From thinker at branda.to Mon Feb 26 12:19:02 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 01:19:02 +0800 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: <45E31686.7080301@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 zefciu wrote: > Thinker wrote: > >> It should be "PyObject *coord;" . Maybe, it is what is wrong with >> your program! >> >> > Should it? The gcc shows me a warning then: > > warning: 'coord' is used uninitialized in this function > > and during the execution I get the same error *plus* a segfault. > > zefciu Yes! Please refer http://docs.python.org/api/arg-parsing.html#l2h-210 And your second PyArg_ParseTuple() call, should not make a reference on coord. It should be PyArg_ParseTuple(coord, ...) since you declare coord as a pointer. You can add some printf() to throw out messages to make sure where the program stop at. If you can compile the module with debug information and use gdb to backtrace dump file, it would be useful. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF4xaG1LDUVnWfY8gRAsW7AKC7D3oZ8p8iWVFcBvkiVwMSrG1oNwCg36ym e1Fa0AO3KzSD5FcYs0LK7P4= =kYLW -----END PGP SIGNATURE----- From bignose+hates-spam at benfinney.id.au Tue Feb 27 02:47:22 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 27 Feb 2007 18:47:22 +1100 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01> Message-ID: <87odngyrcl.fsf@benfinney.id.au> "Alan Isaac" writes: > "Ben Finney" wrote: > > The Pythonic design is: don't expect to have such control over > > users of your code. > > I know this is a popular response, but the fact of the matter > remains that it can be helpful to know when someone tries to set a > value for a nonexisting attribute. That's quite a different request from your original request asking the Pythonic design for *preventing* setting of new attributes. > This is especially true if there have been any interface changes. If the interface has changed, then you don't need to trap *every* setting of an attribute; only the names that you know have changed. ===== foo_v1.py ===== class Foo(object): def bar(self): return 17 spam = 42 ===== ===== foo_v2.py ===== import logging class Foo(object): def baz(self): return 13 eggs = 69 def bar(self): """ Obsolete interface for Foo.baz() """ logging.warn("Deprecated Foo.bar() call, please use Foo.baz()") return self.baz() def _get_spam(self): """ Obsolete interface for Foo.eggs """ logging.warn("Deprecated Foo.spam reference, please use Foo.eggs") return self.eggs def _set_spam(self, value): """ Obsolete interface for Foo.eggs """ logging.warn("Deprecated Foo.spam reference, please use Foo.eggs") self.eggs = value spam = property(_get_spam, _set_spam) ===== After a reasonable grace period, you can drop these compatibility interfaces in a future version. -- \ "For every complex problem, there is a solution that is simple, | `\ neat, and wrong." -- Henry L. Mencken | _o__) | Ben Finney From cvanarsdall at mvista.com Wed Feb 7 12:57:52 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 07 Feb 2007 09:57:52 -0800 Subject: multithreading concept In-Reply-To: <1170866126.933766.66430@h3g2000cwc.googlegroups.com> References: <1170866126.933766.66430@h3g2000cwc.googlegroups.com> Message-ID: <45CA1320.60106@mvista.com> Paul Boddie wrote: > [snip] > > Take a look at the Python Wiki for information on parallel processing > with Python: > > http://wiki.python.org/moin/ParallelProcessing > What a great resource! That one is book marked for sure. I was wondering if anyone here had any opinions on some of the technologies listed in there. I've used a couple, but there are some that I've never seen before. In particular, has anyone used rthread before? It looks like something I may use (now orwhen it matures), are there opinions on it? Under the cluster computing section, has anyone tried any of the other technologies? I've only used Pyro and i love it, but I'd like opinions and experiences with other technologies if anyone has anything to say. -c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From jstroud at mbi.ucla.edu Sun Feb 25 15:35:04 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 25 Feb 2007 20:35:04 GMT Subject: Help on Dict In-Reply-To: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> References: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> Message-ID: Clement wrote: > Can any body tell how Dict is implemented in python... plz tell what > datastructure that uses................ > I think it uses a dict. James From theller at ctypes.org Fri Feb 23 03:22:24 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 23 Feb 2007 09:22:24 +0100 Subject: pyinstaller fails to create exe-File In-Reply-To: <1172177754.619194.30090@k78g2000cwa.googlegroups.com> References: <1172177754.619194.30090@k78g2000cwa.googlegroups.com> Message-ID: DierkErdmann at mail.com schrieb: > Hi ! > > I am trying to create an exe file using pyinstaller. Running the > created exe-File gives the error message > "" > Traceback (most recent call last): > File "", line 8, in > File "E:\Documents\mich\job\abs\backup_skript\buildbackup\out1.pyz/ > email", lin > e 79, in __getattr__ > File "D:\Programme\pyinstaller\iu.py", line 334, in importHook > raise ImportError, "No module named %s" % fqname > ImportError: No module named email.mime.multipart > "" > > My python-Skript uses the following imports: > import ConfigParser > import glob > import os > import smtplib > import time > import win32api > import zipfile > from email.MIMEMultipart import MIMEMultipart > from email.MIMEBase import MIMEBase > from email.MIMEText import MIMEText > from email.Utils import COMMASPACE, formatdate > from email import Encoders > > Can someone help? Running > python script.py > works without any problems. There have been large changes to the email module in Python 2.5, see the NEWS.txt file. email's __init__.py module does some import hacks to ensure compatibility with previous versions, unfortunately the packagers cannot handle them automatically. It /may/ be possible to write a package hook for pyinstaller, I do not know. For py2exe at least, the best solution currently is to include the whole email package; this can be done with '-p email' on the command line, or by passing the corresponding option to the setup function. > I have also tried to use py2exe, but > python setup.py py2exe > gives the following error message: > > copying d:\programme\python25\lib\site-packages\py2exe\run.exe -> E: > \Documents\m > ich\job\abs\backup_skript\dist\backup.exe > Traceback (most recent call last): > File "setup.py", line 4, in > setup(console=["backup.py"]) > File "d:\programme\python25\lib\distutils\core.py", line 151, in > setup > dist.run_commands() > File "d:\programme\python25\lib\distutils\dist.py", line 974, in > run_commands > self.run_command(cmd) > File "d:\programme\python25\lib\distutils\dist.py", line 994, in > run_command > cmd_obj.run() > File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", > line 223, > in run > self._run() > File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", > line 290, > in _run > self.create_binaries(py_files, extensions, dlls) > File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", > line 548, > in create_binaries > arcname, target.script) > File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py", > line 788, > in build_executable > add_resource(unicode(exe_path), script_bytes, u"PYTHONSCRIPT", 1, > True) > RuntimeError: EndUpdateResource: Das System kann das angegebene Ger?t > oder die a > ngegebene Datei nicht ?ffnen. (=System cannot find the specified > device or the file) That's a different problem; it has nothing to do with the email package. You should try to clean the dist and build directories that py2exe creates, sometimes this helps. If it still does not work, you should try to find out what the error means. Is the file readonly? locked because still in use? Thomas From michael at stroeder.com Mon Feb 5 05:50:52 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 05 Feb 2007 11:50:52 +0100 Subject: LDAP/LDIF Parsing In-Reply-To: <45c4be21$0$453$426a74cc@news.free.fr> References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> <45c26772$0$4272$426a74cc@news.free.fr> <45c339f3$0$432$426a74cc@news.free.fr> <45c4be21$0$453$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > > If you know which attributes are supposed to be multivalued in your > specific application, then it's time to write a more serious, > application-specific wrapper. ldap.schema can be used to find that out. Ciao, Michael. From mhellwig at xs4all.nl Wed Feb 14 18:40:36 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 15 Feb 2007 00:40:36 +0100 Subject: rot13 in a more Pythonic style? In-Reply-To: <1171495225.405531.202090@v33g2000cwv.googlegroups.com> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> <45d3403a$0$337$e4fe514c@news.xs4all.nl> <1171495225.405531.202090@v33g2000cwv.googlegroups.com> Message-ID: <45d39db1$0$324$e4fe514c@news.xs4all.nl> bearophileHUGS at lycos.com wrote: > Martin P. Hellwig >> for me (personal) being Pythonic means that I should >> separate the logic and variables, etc... > > Well, for me me Pythonic means using built-in functionalities as much > as possible (like using encode("rot13") or translate), and to write > less code, (avoiding overgeneralizations from the start too). It means > other things too. > > Bye, > bearophile > Yup, but I have a sever case of "NIH" especially if the question asked is something more general then the example given :-) However you are very much right, I reimplemented rot13 and translate in a dull way here :-) -- mph From jan.m.danielsson at gmail.com Mon Feb 26 20:30:18 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 27 Feb 2007 02:30:18 +0100 Subject: Preallocate? -- potentially brain dead question about performance In-Reply-To: <1172533460.309061.255590@h3g2000cwc.googlegroups.com> References: <45e368ea$1@griseus.its.uu.se> <1172533460.309061.255590@h3g2000cwc.googlegroups.com> Message-ID: <45e389aa$1@griseus.its.uu.se> bearophileHUGS at lycos.com wrote: >> newlist = [ None ] * len(mylist) >> for i in range(len(mylist)): >> newlist.append(int(e[0])) > > Note that this appends after the Nones, not over them. And note that > here the name 'e' is undefined. What an idiot I am.. Yes, I know that.. And I actually *had* working code laying around, but rather than opening it and copy-and-pasting, I simply rewrote it. I obviously meant: newlist[i] = int(e[0]) > The most used idiom for that is: > > newlist = [int(e[0]) for e in mylist] > Or better lazily if you want to create a set, avoiding the list > creation: > > newlist = set(int(e[0]) for e in mylist) ...completely avoiding the design issue I raised altogether. Thanks! Exactly what I was hoping for! :-) -- Kind regards, Jan Danielsson From sturlamolden at yahoo.no Fri Feb 9 17:36:22 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 9 Feb 2007 14:36:22 -0800 Subject: multithreading concept In-Reply-To: References: <45CB99DB.1080102@mvista.com> Message-ID: <1171060582.233378.67310@l53g2000cwa.googlegroups.com> On Feb 9, 4:00 pm, "S.Mohideen" wrote: > I am sorry if I sound foolish. > Suppose I split my Net application code using parallel python into several > processes based upon the number of CPU available. That means a single socket > descriptor is distributed across all processes. Is parallelity can be > acheived using the processes send/recv on the single socket multiplexed > across all the processes.. I haven't tried it yet - would like to have any > past experience related to this. Is CPU or network the speed limiting factor in your application? There are two kinds of problems: You have a 'CPU-bound problem' if you need to worry about 'flops'. You have an 'I/O bound' problem if you worry about 'bits per second'. If your application is I/O bound, adding more CPUs to the task will not help. The network connection does not become any faster just because two CPUs share the few computations that need to be performed. Python releases the GIL around all i/o operations in the standard library, such as reading from a socket or writing to socket. If this is what you need to 'parallelize', you can just use threads and ignore the GIL. Python's threads can handle concurrent I/O perfectly well. Remember that Google and YouTube use Python, and the GIL is not a show stopper for them. The GIL locks the process to one CPU. You need to get around this if the power of one CPU or CPU core limits the speed of the application. This can be the case in e.g. digital image processing, certain computer games, and scientific programming. I have yet to see a CPU- bound 'Net application', though. If you are running Windows: take a look at the CPU usage in the task manager. Does it say that one of the CPUs is running at full speed for longer periods of time? If not, there is noting to gained from using multiple CPUs. From robin at reportlab.com Mon Feb 5 06:07:02 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 05 Feb 2007 11:07:02 +0000 Subject: in place-ness of list.append In-Reply-To: References: Message-ID: <45C70FD6.9060807@chamonix.reportlab.co.uk> Bart Van Loon wrote: > Hi all, > ....... > > #-------------------------------------------------- > def addnumber(alist, num): > """ work around the inplace-ness of .append """ > mylist = alist[:] > mylist.append(num) > return mylist > #-------------------------------------------------- > > and I am wondering if this is good practice or not. > > any advice on this matter? ....... would it not be simpler to just use ..... alist+[num]..... where you need it? Seems more natural than def addnumber(alist,num): return alist+[num] and then ......addnumber(alist,num)...... -- Robin Becker From skip at pobox.com Tue Feb 27 19:36:10 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 27 Feb 2007 18:36:10 -0600 Subject: PyCon blogs? Message-ID: <17892.52858.798903.806121@montanaro.dyndns.org> Was anybody blogging about PyCon (talks and/or sprints)? Got any pointers? Thanks, Skip From skip at pobox.com Sat Feb 3 16:20:38 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 3 Feb 2007 15:20:38 -0600 Subject: Python does not play well with others In-Reply-To: <1170513315.797227.90250@v33g2000cwv.googlegroups.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <1170513315.797227.90250@v33g2000cwv.googlegroups.com> Message-ID: <17860.64678.347374.797504@montanaro.dyndns.org> Szabolcs> seriously, python is a programming language and not a flee Szabolcs> market (so don't compare it to java or php) If it grew to be as bloated as Java it might well become a "flee" market. ;-) Skip From sjmachin at lexicon.net Sun Feb 11 01:22:14 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 Feb 2007 22:22:14 -0800 Subject: os.tmpfile() -> permission denied (Win XP) In-Reply-To: <1171171987.567968.278740@s48g2000cws.googlegroups.com> References: <1171169872.507298.196990@j27g2000cwj.googlegroups.com> <1171171987.567968.278740@s48g2000cws.googlegroups.com> Message-ID: <1171174934.062171.10620@j27g2000cwj.googlegroups.com> On Feb 11, 4:33 pm, "John Machin" wrote: > On Feb 11, 4:15 pm, "Gabriel Genellina" wrote: > > > En Sun, 11 Feb 2007 01:57:52 -0300, John Machin > > escribi?: > > > > | >>> os.tmpfile() > > > Traceback (most recent call last): > > > File "", line 1, in > > > OSError: [Errno 13] Permission denied > > > > 1. Before I start checking what permissions who has to do what to > > > which, what directory is it likely to be trying to open the temp file > > > in? C:\WINDOWS\TEMP....? > > > You could analyze the source, > > I have already followed the twisty little passages: os.tmpfile() is > really nt.tempfile(), but there is no Modules/ntmodule.c (Modules/ > posixmodule.c does a Jekyll & Hyde trick). (nt|posix)module calls > tmpfile(), which is (as I mentioned) in the C stdio library. How can I > analyse the source of that? Have Microsoft had a rush of blood to the > head and gone open source overnight?? > > > but usually I find easier to use FILEMON:http://www.sysinternals.com > > Thanks, I'll try that. While Filemon is still alive, it's been superceded by Procmon, which combines filemon + regmon + plus new goodies. I tried procmon. And the result of an administrator user doing os.tmpfile(): 281773 4:50:14.8607126 PM python.exe 2716 CreateFile C:\t2ks SUCCESS Access: Generic Read/Write, Delete, Disposition: Create, Options: Synchronous IO Non-Alert, Non-Directory File, Delete On Close, Attributes: N, ShareMode: Read, Write, Delete, AllocationSize: 3,184,748,654,057,488,384 [big snip] *** AARRGGHH It's creating the file in the *ROOT* directory *** A quick google for "tmpfile root directory" reveals that this is a "popular" problem on Windows. See e.g. http://bugs.mysql.com/bug.php? id=3998 which has several users corroborating the story, plus this handy hint: """ But MSDN says (ms-help://MS.MSDNQTR.2003APR.1033/vclib/html/ _crt_tmpfile.htm): ------- The tmpfile function creates a temporary file and returns a pointer to that stream. The temporary file is created in the root directory. To create a temporary file in a directory other than the root, use tmpnam or tempnam in conjunction with fopen. """ I wonder why my environment has entries for TMP and TEMP (both pointing to the same path, and it sure ain't the root directory) -- must be one of those "haha fooled you" tricks :-( Regards, John From memcached at aol.com Sun Feb 25 00:09:56 2007 From: memcached at aol.com (memcached at aol.com) Date: Sun, 25 Feb 2007 00:09:56 EST Subject: about framework Message-ID: Python has some web framework.I'm not familiar with all of them. Do you think which is best popular of them?Thanks.


**************************************
AOL now offers free email to everyone. Find out more about what's free from AOL at http://www.aol.com. From ayaz at dev.slash.null Sat Feb 3 10:24:37 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Sat, 03 Feb 2007 20:24:37 +0500 Subject: newbie question: ftp.storbinary() References: Message-ID: "Scott Ballard" typed: > Sorry for the lame question, I'm still trying to pick up Python and new to > the list here. > > Question: > I'm trying to write a python script that will access an FTP site and upload > some files. I've gotten everything working except for the actual uploading > of the files. > > I'm assuming that I should use storbinary( command, file[, blocksize]) to > transfer the files. the documentation says "command should be an appropriate > "STOR" command: "STOR filename"." > > I can't seem to figure out an `appropriate "STOR" command' is??? It frustrated the hell out of me too until I found this: http://effbot.org/librarybook/ftplib.htm The following works: from ftplib import FTP ftp = FTP() ftp.set_debuglevel(2) ftp.connect(_host, _port) ftp.login(_user, _pass) ftp.storbinary('STOR ' + _file, open(_file)) ftp.quit() -- Ayaz Ahmed Khan A witty saying proves nothing, but saying something pointless gets people's attention. From donn at u.washington.edu Fri Feb 16 14:21:59 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 16 Feb 2007 11:21:59 -0800 Subject: IOError: [Errno 4] Interrupted system call References: <1171594649.279210.139470@l53g2000cwa.googlegroups.com> Message-ID: In article <1171594649.279210.139470 at l53g2000cwa.googlegroups.com>, chadrik at gmail.com wrote: > i'm getting the same error when trying to read results from popen2 > within a pyQt window. is this a threading issue? is my pyQt window > responsible for interrupting the read? i'm fairly new to python so > i'm struggling to figure this out. can you recommend any possible > methods of preventing this? for instance, could acquiring a thread > lock before calling popen solve the problem? No. Did you look at the text of the post you responded to here? What do you think about that advice? Do you have any signal handlers? Donn Cave, donn at u.washington.edu From __peter__ at web.de Mon Feb 19 05:55:35 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 11:55:35 +0100 Subject: timeout in urllib.open() References: Message-ID: Stefan Palme wrote: (top-posting undone) [Peter] >> I believe this can only be set globally: >> >> import socket >> socket.setdefaulttimeout(seconds) [Stefan] > Uuuh this is no solution for me, because the > website-checking tool is part of a very very big > application running in an application server, so > globally setting the timeout may break a lot of > other things... > > But when there is a "default timeout" (as indicated by > the method name) - isn't there a "per-socket timeout" > too? Yes, but it isn't as easily available... Perhaps you find some ideas here: http://mail.python.org/pipermail/python-dev/2007-February/070897.html Peter From nospamformeSVP at gmail.com Mon Feb 12 14:04:49 2007 From: nospamformeSVP at gmail.com (Don Taylor) Date: Mon, 12 Feb 2007 14:04:49 -0500 Subject: Generating pdf files in epydoc on Windows In-Reply-To: <45cfc90f.0@entanet> References: <45cfc90f.0@entanet> Message-ID: Duncan Smith wrote: > As I remember, LaTeX and ghostscript. Thanks. OK, I have these installed now, but apparently epydoc can't find them and I don't know how to teach it to find them. Error: latex failed: [Errno 2] The system cannot find the file specified epydoc does creates some .tex files when I ask it for .pdf o/p. Don. From Luap777 at gmail.com Thu Feb 8 19:32:43 2007 From: Luap777 at gmail.com (Luap777 at gmail.com) Date: 8 Feb 2007 16:32:43 -0800 Subject: excel find last column In-Reply-To: References: Message-ID: <1170981163.874220.27660@h3g2000cwc.googlegroups.com> > > I get the error that xlPrevious is not defined. > If you are using pythonwin, run the COM Makepy utility on Microsoft Excel Object Library. Then you have access to the defined constants as follows. >>> import win32com.client >>> win32com.client.constants.xlPrevious 2 Hope this helps. Paul From pavlovevidence at gmail.com Thu Feb 1 09:41:56 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 1 Feb 2007 06:41:56 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: References: <1170339280.420231.304370@s48g2000cws.googlegroups.com> Message-ID: <1170340916.646800.195670@h3g2000cwc.googlegroups.com> On Feb 1, 9:20 am, Jean-Paul Calderone wrote: > On 1 Feb 2007 06:14:40 -0800, Carl Banks wrote: > > > > >On Jan 31, 3:37 pm, Jean-Paul Calderone wrote: > >> On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: > > >> >Michele Simionato wrote: > >> >> On Jan 31, 5:23 pm, "Frank Potter" wrote: > >> >> > I want to find a multithreaded downloading lib in python, > >> >> > can someone recommend one for me, please? > >> >> > Thanks~ > > >> >> Why do you want to use threads for that? Twisted is the > >> >> obvious solution for your problem, > > >> >Overkill? Just to download a few web pages? You've got to be > >> >kidding. > > >> Better "overkill" (whatever that is) than wasting time re-implementing > >> the same boring thing over and over for no reason. > > >"I need to download some web pages in parallel." > > >"Here's tremendously large and complex framework. Download, install, > >and learn this large and complex framework. Then you can write your > >very simple throwaway script with ease." > > >Is the twisted solution even shorter? Doing this with threads I'm > >thinking would be on the order of 20 lines of code. > > The /already written/ solution I linked to in my original response was five > lines shorter than that. And I suppose "re-implementing the same boring thing over and over" is ok if it's 15 lines but is too much to bear if it's 20 (irrespective of the additional large framework the former requires). Carl Banks From coolguy17111987 at gmail.com Tue Feb 6 05:57:31 2007 From: coolguy17111987 at gmail.com (coolguy17111987 at gmail.com) Date: 6 Feb 2007 02:57:31 -0800 Subject: Free Pc To Phone Calling Message-ID: <1170759451.236199.99950@m58g2000cwm.googlegroups.com> Now you can call anywhere in world for free ...hurry up...Its Globe 7.. you are paid to watch free videos(of your choice)... Now its no. 1 VOIP service in the world....Click on the link below...download the software, register for free and start calling.... What are you waiting for now.... Call any phone anywhere Free! - Globe 7 http://surl.in/HLGB7268591UXYDPMK-google Weather Report Toolbar Hi all..Now you can get the weather report of your area instantly...Just Install the toolbar and get the weather report on it..Instant report..Go for it...What is you waiting for... Download the toolbar only 400Kb, Install it..and thats it... Download Weather Toolbar - Instant weather reports, forecasts, and radar images anytime for FREE! - http://surl.in/HLWTD268591UXYDPMK- google Search Profiles - FREE! Intimate Dating. Start Chatting within seconds - http://surl.in/HLMAT268591UXYDPMK-google Unlimited iPod Music, Movies, TV Shows Downloads. No Monthly or Per Downloads Fees! - http://surl.in/HLMID268591UXYDPMK-google Webmasters - Earn Money from your Website. Get Paid Daily! - http://surl.in/HLAXR268591UXYDPMK-google From dharding at gmail.com Sat Feb 24 12:27:19 2007 From: dharding at gmail.com (Daniel Harding) Date: 24 Feb 2007 09:27:19 -0800 Subject: Endianness conversion In-Reply-To: <45e05c49$0$20809$5fc30a8@news.tiscali.it> References: <45e05c49$0$20809$5fc30a8@news.tiscali.it> Message-ID: <1172338039.789502.26470@h3g2000cwc.googlegroups.com> On Feb 24, 9:39 am, Toby wrote: > As part of a program I'm writing, I need to save to disk big amounts of > data (hundreds of MB, in 8kB chunks) swapping every couple of bytes. > > I obviously cannot do it in a Python loop. > > Is there a function I could use in the standard library, or do I have to > write my own C extension? Try the using the array module. array objects provide a byteswap method which reverses endianness. -Daniel From mail at microcorp.co.za Tue Feb 13 01:11:11 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 13 Feb 2007 08:11:11 +0200 Subject: Tkinter and Tile References: Message-ID: <021a01c74f4e$88cf9f60$03000080@hendrik> "Eric Brunel" wrote: FYI, changes done in tcl/tk are usually quite rapidly integrated in Tkinter. For example, for the "panedwindow" widget, introduced in tk8.4 (first version out in the end of 2002), a Tkinter wrapper was available in Python 2.3 (first version out mid-2003). So I don't doubt that the Tile extension package will be integrated in Tkinter, as soon as it is available in an official tcl/tk release. Do you imagine that the bizarre behaviour of "ButtonRelease" will be fixed too? - Hendrik From bearophileHUGS at lycos.com Tue Feb 6 18:11:47 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Feb 2007 15:11:47 -0800 Subject: Steiner Tree In-Reply-To: <1170663061.700803.231460@s48g2000cws.googlegroups.com> References: <1170663061.700803.231460@s48g2000cws.googlegroups.com> Message-ID: <1170803507.353774.286190@v33g2000cwv.googlegroups.com> Suresh: > I could find GeoSteiner (http://www.diku.dk/geosteiner/) which is > implemented as a C program. Anybody know python wrapper for this? > Anybody tried this program in a python program? Once compiled, you may just need to use it with files calling it through the console with pipes from Python. If that isn't enough, you can probably write a simple enough wrapper using Pyrex. If you succed, I may be interested in the result. Bye, bearophile From bruno.desthuilliers at gmail.com Fri Feb 9 05:10:22 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 9 Feb 2007 02:10:22 -0800 Subject: Dictionary Question In-Reply-To: References: <2adc542f0702081832k2b917a86pede0f419d5ff7be4@mail.gmail.com> Message-ID: <1171015822.500879.73070@l53g2000cwa.googlegroups.com> On 9 f?v, 04:02, "Gabriel Genellina" wrote: > En Thu, 08 Feb 2007 23:32:50 -0300, Sick Monkey > escribi?: > > > db = {'b... at gmail.com':'none', '... at yahoo.com':'none', > > '... at aol.com':'none', > > '... at gmail.com':'none',} > > > And I want to pull out all of the "gmail.com" addresses.. How would I do > > this? > > > NOTE: I already have a regular expression to search for this, but I feel > > that looping over a dictionary is not very efficient. (answer to the OP) Looping over a dict keys should be quite fast. If you're worried about perfs, it would be better to first get rid of useless regexps: filtered_db = dict((k, v) for k, v in db.iteritems() \ if not k.endswith('@gmail.com')) From ptmcg at austin.rr.com Fri Feb 9 19:57:24 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 9 Feb 2007 16:57:24 -0800 Subject: Matching Strings In-Reply-To: References: Message-ID: <1171069044.437826.186460@j27g2000cwj.googlegroups.com> On Feb 9, 6:03 pm, rshep... at nospam.appl-ecosys.com wrote: > I'm not sure how to change a string so that it matches another one. > > My application (using wxPython and SQLite3 via pysqlite2) needs to compare > a string selected from the database into a list of tuples with another > string selected in a display widget. > > An extract of the relevant code is: > > selName = self.polTree.GetItemText(selID) > ... > for item in self.appData.polNat: > print 'Item: ', item, '\n', 'selName: ', selName, '\n' > if item == selName: > print '***** ', self.appData.polNat[1] > > The last comparison and print statement never work because the strings are > presented this way: > > Item: (u'ground water',) > selName: ground water > > What do I need to do to 'Item' to strip the parentheses, unicode symbol, > single quotes, and comma? Do I want 'raw' output? If so, how do I specify > that in the line 'if item == selName:'? > > TIA, > > Rich I suspect that the variable item is *not* a string, but a tuple whose zero'th element is a unicode string with the value u'ground water'. Try comparing item[0] with selname. >From my command prompt: >>> u'a' == 'a' True -- Paul From gagsl-py at yahoo.com.ar Sat Feb 10 18:50:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 20:50:35 -0300 Subject: Something like the getattr() trick. References: <76fd5acf0702101438q19484482qa37c37bbc81f9aed@mail.gmail.com> Message-ID: On 2/10/07, Ayaz Ahmed Khan wrote: >> class Vuln: >> >> class VulnInfo(Vuln): >> >> class VulnDiscuss(Vuln): >> >> def main(url): >> vuln_class = ['Info', 'Discuss'] >> vuln = Vuln(url) >> vuln._parse() >> for link in vuln.get_link(): >> i = VulnInfo(link) >> i._parse() >> d = VulnDiscuss(link) >> d._parse() >> >> >> Is there a way to get references to VulnInfo and VulnDiscuss objects In addition to what other people has suggested: - Use some kind of registry: register("Vuln", Vuln, VulnInfo, VulnDiscuss) (a dictionary would do) and then look up by name - If all three classes are contained inside the same module, look up them by name into globals: InfoClass = globals()["%sInfo" % self.__class__.__name__] (assuming self is an instance of Vuln, this would give you the VulnInfo class) - Replace your line: vuln_class = ['Info', 'Discuss'] with vuln_class = [VulnInfo, VulnDiscuss] As you see, there are many ways to do that - choose what better fits your needs. -- Gabriel Genellina From ke5crp1 at verizon.net Sat Feb 3 03:55:34 2007 From: ke5crp1 at verizon.net (John Barrett) Date: Sat, 03 Feb 2007 08:55:34 GMT Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170482833.643671.254640@s48g2000cws.googlegroups.com> <1170488368.634755.138920@m58g2000cwm.googlegroups.com> Message-ID: wrote in message news:1170488368.634755.138920 at m58g2000cwm.googlegroups.com... > On Feb 2, 10:32 pm, "John Barrett" wrote: >> wrote in message > >> >> > [snip] >> >> > Run your "experiment" again but add some pure oxygen such as was >> >> > escaping from the on-board breathing oxygen tanks on the >> >> > airplanes that were crashed into the WTC. >> >> > No need to do it. We have the pictures of live humans waving from the >> > gaping holes in the towers where the planes crashed. We have the >> > testimonies of the fire fighters that the fires were not that hot and >> > minor. The fuel of the plane which is mainly in the wings were severed >> > outside the netting and much of them burnt outside in the fireball >> > that is visible in all the videos. Futhermore, the black soot that was >> > visible to the naked eye is indicative of bloody cold flame. Also, the >> > probability of the oxygen tanks oriented in such a way to inject >> > oxygen onto the steel as in a oxygen cutting torch is extremely low. >> > These cylinders have a 1000-3000psi of pressure which makes them into >> > a rocket or an explosive under uncontrolled gas release. And they >> > would not contaminate the molten metal with any sulfur. Either the >> > atmosphere inside was oxidising or reducing. If it was oxidising, how >> > did the sulfur in huge quantities contaminate the molten metal pools? >> > The official lies to explain sulfur is from the plaster wall. But that >> > requires a reducing atmosphere with finely divided and intimately >> > mixed reactants in a calciner where they are continuously rotated and >> > run for several hours. Yet the fires ran not even for an hour before >> > the building collapsed. >> >> OK - given all that -- you are left with only one conclusion (or at least >> I >> am) -- progressive structural failure, the loss of support where the >> plane >> hit was sufficient to put excessive stress on the remaining structural >> members, resulting in a catastrophic sequential failure > > I dont think you have seen any actual structural failures, esp > progressive. > That happens often in earthquake and they have stacked floors. There > is > famous picture of an earthquake on these websites and in the videos. > Futhermore > due to erratic stops and goes in the progressive failure, the > structure falls on the side esp a big bldg like WTC1&2 should have > fallen from the tipping torque to one side. That did not happen. only > controlled demolition bldgs fall down straight. > >> -- it doesnt take >> exotic chemical mixes to put excessive mechanical stress on a system... >> just >> chop out enough supports.. it may take time for the remaining supports to >> deform enough to reach the failure point.. but they will get there, as >> demonstrated -- occams razor dude -- the least hypothesis is usually the >> right one -- and I get enough conspiracy theory crap out of my dad -- >> makes >> a good movie -- but doesnt pan out in real life -- too many >> whistle-blowers >> around !! > > Occams razor is applicable to nature's works. human works are not > amenable to it. Besides, the official fairy tale is the conspiracy > theory. > >> The city I live in is installing those red-light cameras to catch >> light-runners -- my dad likes to claim that they manipulate the yellow >> time >> to catch people in the intersection and increase revenue from traffic >> tickets -- I told him to shut up until he got out there with a stop watch >> and proved it -- and I say the same to you -- PROVE it -- then make some >> noise -- conjecture and conspiracy theories without proof are a waste of >> everyones time. -- how do you know the sulphur was in large quantities ?? >> did you do a chemical analysis ?? or can you produce one done by a >> reputable >> metalurgy company ?? > > These pillars are not machinable steel. the sulfur here was excessive. > we are talking about intergranular corrosion, not that teeny amount > used for imparting machinability and that is not nowadays needed. It > only for cheap and rough chinese type crap and i am not sure even > there if someone would ruin their steel mills by adding this kind of > corrosive sulfur shit. come on dude ... dont mix categories. > >> Ohhh and by the way -- high sulphur steels are regularly used for >> machined >> components -- was the amount of sulphur detected incosistent with what >> may >> have been present due to the use of high sulphur steels ?? (where is that >> metalurgy report again ??) > > yeah a damn fool would put sulfur in the bolts and load bearing > elements such as the bolts of aircrafts and space shuttle. > > Besides how do you explain the completely pulverized building ?????? > if not for explosives. > > have your read THIS ?? From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 09:50:40 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Feb 2007 01:50:40 +1100 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: On Fri, 16 Feb 2007 08:01:11 -0600, Edward K Ream wrote: >> Why won't it be possible to make 'print' in Python 3 that supports all >> the functionality of the current print statement, and then translate to >> that ? >> I saw an assertion to the effect that it wasn't possible - but no proof. > > As discussed in the original post, the problem is the reverse: the Python > 2.x print statement does not support the keyword args required by the pep, > so that print(foo) **in Python 2.x** can not simulate the effect of the > print statement with a trailing comma. Here is the theorum carefully stated > and proved. > > Theorem: is not possible to define a function called print in Python 3.x > such that > > A) print (whatever) is syntaxtically valid in Python 2.x and > > B) print(whatever) outputs what 'print whatever' outputs in Python 2.x for > all values of 'whatever'. [snip] > That's the proof. Can you find a flaw in it? No, but it doesn't matter. There's no particular reason why you have to write "print (whatever)" in your code. What you need is *some function* that is capable of duplicating the functionality of print, which can be used under Python 2.x and 3. It isn't hard to write a function that will duplicate print's functionality, so long as you give up the requirement that it is called just like print. The problem you describe with the print syntax only is a problem if you insist on supporting Python 2.x and 3 from the same codebase. I don't expect many people will try to do that. For those who do, don't use the print syntax. As for the rest of us, we'll just continue to use print using whichever syntax is appropriate. -- Steven. From nagle at animats.com Tue Feb 6 12:56:39 2007 From: nagle at animats.com (John Nagle) Date: Tue, 06 Feb 2007 17:56:39 GMT Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: Message-ID: Steven Bethard wrote: > Jean-Paul Calderone wrote: > > Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve I'd like to know, too. I have the same code running in 2.4 and 2.5, and I've had the following problems: 1. Bug [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 (a patch to sgmllib._convert_ref appears to have broken something) (This might be the switch from Latin-1 to ascii as default, now that I think about it.) 2. MySQLdb isn't fully supported for Python 2.5 yet, and there's no tested Windows executable available, although there's an untested version from a World of Warcraft guild available. 3. M2Crypto has versioning issues between Python, SWIG, gcc, and OpenSSL, and getting everything to play together can be difficult. This is a packaging issue; major Linux distros aren't shipping a compatible set of components. But my own pure Python code is working fine in both version of Python, and on both Windows and Linux. John Nagle From vinay_sajip at yahoo.co.uk Sun Feb 18 06:27:21 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 18 Feb 2007 03:27:21 -0800 Subject: basic jython question In-Reply-To: <1171547234.910049.144010@a34g2000cwb.googlegroups.com> References: <1171543539.339651.319480@m58g2000cwm.googlegroups.com> <1171547234.910049.144010@a34g2000cwb.googlegroups.com> Message-ID: <1171798041.761287.226500@j27g2000cwj.googlegroups.com> > On Feb 15, 1:53 pm, "Richard Brodie" wrote: > > Since the CPython module is heavily influenced by the native Javalogging > > framework (and/or log4j), I would have thought that it would be easier > > to create a Jython wrapper for those. Agreed, but if you copy the logging folder from the CPython Lib folder to the jython lib folder, it should work (except for use of other modules which wouldn't perhaps be available under Java, such as syslog, win32 etc.) - so files, console streams etc. should be OK. Clearly, a facade over an existing system such as log4j or java.util.logging would have the potential to perform better. Regards, Vinay Sajip From pecora at anvil.nrl.navy.mil Sun Feb 18 17:40:21 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sun, 18 Feb 2007 17:40:21 -0500 Subject: numpy, numarray, or numeric? References: <1171591039.085342.21280@l53g2000cwa.googlegroups.com> Message-ID: In article <1171591039.085342.21280 at l53g2000cwa.googlegroups.com>, "RickMuller" wrote: > Use numpy; it is the "officially blessed one" that you refer to. It > has all of the advantages of the other two. > > Numeric was the first library, but it had some drawbacks that led some > people to develop Numarray, which had some additional features. > Finally, the numpy project was started to unify the two groups by > providing some of the new features in a code base consistent with the > old library as well. I agree completely, having converted all my code from Numeric to NumPy. Just my 2 cents. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From http Wed Feb 28 15:18:16 2007 From: http (Paul Rubin) Date: 28 Feb 2007 12:18:16 -0800 Subject: Yet another unique() function... References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <1172647505.784091.193710@q2g2000cwa.googlegroups.com> Message-ID: <7x7iu2niif.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > It's more terse, but my version is built to be faster in the more > common cases of all hashable or/and all sortable items (while working > in other cases too). > Try your unique on an unicode string, that's probably a bug (keepstr > is being ignored). > Version by Paul Rubin is very short, but rather unreadable too. > > Bye, > bearophile Unicode fix (untested): def unique(seq, keepstr=True): t = type(seq) if t in (unicode, str): t = (list, t('').join)[bool(keepstr)] seen = [] return t(c for c in seq if not (c in seen or seen.append(c))) Case by case optimization (untested): def unique(seq, keepstr=True): t = type(seq) if t in (unicode, str): t = (list, t('').join)[bool(keepstr)] try: remaining = set(seq) seen = set() return t(c for c in seq if (c in remaining and not remaining.remove(c))) except TypeError: # hashing didn't work, see if seq is sortable try: from itertools import groupby s = sorted(enumerate(seq),key=lambda (i,v):(v,i)) return t(g.next() for k,g in groupby(s, lambda (i,v): v)) except: # not sortable, use brute force seen = [] return t(c for c in seq if not (c in seen or seen.append(c))) I don't have Python 2.4 available right now to try either of the above. Note that all the schemes fail if seq is some arbitrary iterable, rather one of the built-in sequence types. I think these iterator approaches get more readable as one becomes used to them. From silovana.vjeverica at com.gmail Fri Feb 23 06:44:17 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Fri, 23 Feb 2007 12:44:17 +0100 Subject: Module trouble [newbie] Message-ID: Can somebody explaint this to me: I have module a.py A = 100 import b print "A printing" print "B is %s" % b.B and module b.py B = 2000 import a print "B printing" print "A is %s" % a.A I thought that output would be: B printing A is 100 A printing B is 2000 Because import b would execute b.py, and in b.py line "import a" would be ignored, but my output is: >>> import a 100 A printing B is 100 ?? :) -- http://www.nacional.hr/articles/view/23894/23 From sjmachin at lexicon.net Mon Feb 5 20:59:32 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Feb 2007 17:59:32 -0800 Subject: Decimating Excel files In-Reply-To: <1170725241.634632.100830@v45g2000cwv.googlegroups.com> References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> <1170725241.634632.100830@v45g2000cwv.googlegroups.com> Message-ID: <1170727172.316685.49980@h3g2000cwc.googlegroups.com> On Feb 6, 12:27 pm, "mensana... at aol.com" wrote: > On Feb 5, 5:46 pm, "Gabriel Genellina" wrote: > > > > > En Sat, 03 Feb 2007 18:52:10 -0300, mensana... at aol.com > > escribi?: > > > > On Feb 3, 1:43?pm, gonzlobo wrote: > > >> We have a data acquisition program that saves its output to Excel's > > >> .xls format. Unfortunately, the programmer was too stupid to write > > >> files the average user can read. > > > >> I'd like some advice on how to go about: > > >> 1. Reading a large Excel file and chop it into many Excel files (with > > >> only 65535 lines per file) > > > > An Excel sheet only has 65535 lines. Or do yo mean it has > > > multiple sheets? > > > As I understand the problem, the OP has a program that generates the .xls > > files, but it's so dumb that writes files too large for Excel to read. > > My first thought was how would that be possible? > > But then, nothing's stopping someone from making > a million line .csv file (which Excel thinks it "owns") > that would be too big for Excel to open. > > If that's the case, then chasing COM is barking up > the wrong tree. > To clear up the doubts, I'd suggest that the OP do something like this at the Python interactive prompt: print repr(open('nasty_file.xls', 'rb').read(512)) If that produces recognisable stuff, then it's a CSV file (or a tab separated file) masquerading as an XLS file. OTOH, if it produces a bunch of hex starting with "\xd0\xcf \x11\xe0\xa1\xb1\x1a\xe1" then it's at least an OLE2 compound document -- could be Word or Powerpoint, though :-) What would be even better is, if the OP has downloaded xlrd: Presuming Windows, and Python installed in default location, and xlrd installed using its setup.py, do this at the command prompt c:\python25\python c:\python25\scripts\runxlrd.py ov nasty_file.xls This should give an overview ("ov") of the file, showing for each worksheet how many columns and rows are used, plus other potentially helpful information -- or it will raise an exception; still useful information. Cheers, John From sjmachin at lexicon.net Mon Feb 5 17:23:53 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Feb 2007 14:23:53 -0800 Subject: Unicode formatting for Strings In-Reply-To: <1170709537.453424.103460@p10g2000cwp.googlegroups.com> References: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> <1170709537.453424.103460@p10g2000cwp.googlegroups.com> Message-ID: <1170714233.828654.48610@v33g2000cwv.googlegroups.com> On Feb 6, 8:05 am, robson.cozendey... at gmail.com wrote: > On Feb 5, 7:00 pm, "Chris Mellon" wrote: > > > > > On 2/5/07, Kent Johnson wrote: > > > > robson.cozendey... at gmail.com wrote: > > > > Hi, > > > > > I?m trying desperately to tell the interpreter to put an '?' in my > > > > string, so here is the code snippet: > > > > > # -*- coding: utf-8 -*- > > > > filename = u"Ataris Aqu?ticos #2.txt" > > > > f = open(filename, 'w') > > > > > Then I save it with Windows Notepad, in the UTF-8 format. So: > > > > > 1) I put the "magic comment" at the start of the file > > > > 2) I write u"" to specify my unicode string > > > > 3) I save it in the UTF-8 format > > > > > And even so, I get an error! > > > > > File "Ataris Aqu?ticos #2.py", line 1 > > > > SyntaxError: Non-ASCII character '\xff' in file Ataris Aqu?ticos #2.py > > > > on line 1 > > > > It looks like you are saving the file in Unicode format (not utf-8) and > > > Python is choking on the Byte Order Mark that Notepad puts at the > > > beginning of the document. > > > Notepad does support saving to UTF-8, and I was able to do this > > without the problem the OP was having. I also saved both with and > > without a BOM (in UTF-8) using SciTe, and Python worked correctly in > > both cases. > > > > Try using an editor that will save utf-8 without a BOM, e.g. jedit or > > > TextPad. > > > > Kent > > > -- > > >http://mail.python.org/mailman/listinfo/python-list-Hide quoted text - > > > - Show quoted text -- Hide quoted text - > > > - Show quoted text - > > I saved it in UTF-8 with Notepad. Please consider that you might possibly be mistaken. Here are dumps of 4 varieties of file: | >>> for i in range(4): ... print '\nFile %d:\n%r' % (i, open('robson' + str(i) + '.py', 'rb').read()) ... File 0: '\xef\xbb\xbf# -*- coding: utf-8 -*-\r\nfilename = u"Ataris Aqu \xc3\xa1ticos #2. txt"\r\nf = open(filename, \'w\')' File 1: '# -*- coding: utf-8 -*-\r\nfilename = u"Ataris Aqu\xc3\xa1ticos #2.txt"\r\nf = open(filename, \'w\')' File 2: '# -*- coding: cp1252 -*-\r\nfilename = u"Ataris Aqu\xe1ticos #2.txt"\r \nf = ope n(filename, \'w\')' File 3: '\xff\xfe#\x00 \x00-\x00*\x00-\x00 \x00c\x00o\x00d\x00i\x00n\x00g \x00:\x00 \x00u \x00t\x00f\x00-\x008\x00 \x00-\x00*\x00-\x00\r\x00\n\x00f\x00i\x00l \x00e\x00n\x0 0a\x00m\x00e\x00 \x00=\x00 \x00u\x00"\x00A\x00t\x00a\x00r\x00i\x00s \x00 ] [snip] File 0 was saved in UTF-8 with Notepad. Notepad puts a "UTF-8 BOM" at the front of the file. It works (that is, it creates a file with the a- acute character in its name). There is no \xff character in line 1 for Python to complain about. File 1 was saved in UTF-8 with another editor. No BOM, no problem. Works. File 2 (which specifies cp1252 encoding (my default, and probably yours too)) was saved normally (i.e. without the stuffing about necessary to get UTF-8). Works. File 3 was saved in "Unicode" (really utf_16_le) using Notepad. As you can see, it has a UTF-16-LE BOM (which contains \xff) at the start. Python is not amused, giving exactly the same error message as you reported. So: (1) If you still believe that you are getting a problem with a file saved as UTF-8, please present reproducible credible evidence: for example, a copy/paste of what happens when you (a) dump of the file, immediately followed by (b) running the file with Python. (2) Consider using your "native" encoding (e.g. cp1252) with your normal/usual editor/IDE. > I was thinking here... It can be a > limitation of file.open() method? No, it can't. > Have anyone tested that? Unlikely. HTH, John From sunheaver at gmail.com Fri Feb 23 14:08:55 2007 From: sunheaver at gmail.com (sunheaver at gmail.com) Date: 23 Feb 2007 11:08:55 -0800 Subject: What is the best queue implemetation in Python? In-Reply-To: References: <1172190018.915043.200560@v45g2000cwv.googlegroups.com> Message-ID: <1172257735.337865.138150@p10g2000cwp.googlegroups.com> On Feb 22, 12:40 pm, hg wrote: > John Machin wrote: > > On Feb 23, 11:12 am, "John" wrote: > >> I want to write a code for Breadth First Traveral for Graph, which needs > >> a queue to implement. > > >> I wonder that for such a powerful language as Python, whether there is a > >> better and simpler implementation for a traditional FIFO queue? > > > Better and simpler than *WHAT*? > > Sorry, but you do that all the time ... "ask the question as you know the > answer, otherwise shut the f u ..." > > Can't you assume for a second that other people do not have your wonderful > brain and still have to make it through 60+ years of life of learning ? > > hg Um... first off, you have to admit that a lot of what is posted on the internet in general and even on groups like this is rambling, poorly thought out, missing necessary context, and just generally a mess and hard to understand. So maybe a little peer pressure on folks to clean up their posts and try to express themselves clearly isn't such a bad thing. And finally, let's face it: if the internet ever does cease to be a place where you can see crotechety know-it-all programmers roasting clueless noobs, then, honestly, what is the point of owning a computer? From edreamleo at charter.net Fri Feb 16 07:07:42 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 06:07:42 -0600 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: > I'm pretty sure you're mistaken. Python 3 will be the release that breaks > code. Hopefully very little, but there almost certainly will be some. Pep 3105 breaks a *lot* of code, despite the bland assertion that most production programs don't use print. Presumably, Guido wanted to improve print in such a way that *more* people would use it. But the effect of the pep is that *less* people will be able to use print, *regardless* of how backward compatible Python 3.x is 'allowed' to be. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 16:50:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 22:50:08 +0100 Subject: alias for data member of class instance? In-Reply-To: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> References: <1170706024.687373.235140@a34g2000cwb.googlegroups.com> Message-ID: <45c79f7a$0$1029$426a34cc@news.free.fr> Sean McIlroy a ?crit : > hi all > > is there a way to do this ... > > class clown: > def __init__(self): > self.x = 0 > self.y = ALIAS(self.x) ## FEASIBLE ? class Alias(object): def __init__(self, attrname): self._attrname = attrname def __get__(self, instance, cls): if instance is None: return self return getattr(instance, self._attrname) def __set__(self, instance, value): setattr(instance, self._attrname, value) class Clown2(object): def __init__(self): self.x = 0 y = Alias('x') From medicalsounds at hotmail.com Thu Feb 1 11:19:18 2007 From: medicalsounds at hotmail.com (Jona) Date: 1 Feb 2007 08:19:18 -0800 Subject: Creating a simple arithmetic expressions tree Message-ID: <1170346758.637731.56450@p10g2000cwp.googlegroups.com> So I'm not sure how to write a code that could create a tree placing data at every node... and then retrieve that information as I go by a node... here is what I have ==========CODE=========== from itertools import izip class Node: def __init__(self, left, right): self.left = left self.right = right def __str__(self): return "Node(%s, %s)"%(self.left, self.right) ========================= From duncan.booth at invalid.invalid Wed Feb 28 04:14:47 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Feb 2007 09:14:47 GMT Subject: Lists: Converting Double to Single References: <%6QEh.6362$_73.1862@newsread2.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber wrote: > For floating point, smallest magnitude to largest IS the most > precise. > > Pretend you only have 2 significant digits of precision... > > 10 + 0.4 + 0.4 + 0.4 => 10 > > 0.4 + 0.4 + 0.4 + 10 => 11 and if you try the way I suggested then initial input order doesn't matter: (10 + 0.4) = 10, (0.4 + 0.4) = 0.8, (10 + 0.8) = 11 (0.4 + 0.4) = 0.8, (10 + 0.4) = 10, (0.8 + 10) = 11 Pretend you ran the example code I posted. Specifically the bit where the output is: all the same builtin sum 1000000.0000016732 pairwise sum 1000000.00001 It isn't so much the order of the initial values that matters (especially if the values are all similar). What *really* matters is keeping the magnitude of the intermediate results as small as possible. Summing in pairs ensures that you keep the precision as long as possible. The order of the initial values is less important than this (although it does still have a minor effect). For a solution which works with a sequence of unknown length and doesn't require lookahead I don't think you can do much better than that. BTW, in case someone thinks my example numbers are a bit too weird you can show the same problem averaging a list of 10 digit floating point numbers with exact representations: v = [9999999999.] * 10000000 print "builtin sum ", (sum(v)/len(v)) print "pairwise sum", (sumpairs(v)/len(v)) gives: builtin sum 9999999999.91 pairwise sum 9999999999.0 In both cases the total is large enough to go beyond the range of integers that can be expressed exactly in floating point and as soon as that happens the builtin sum loses precision on every subsequent addition. pairwise summation only loses precision on a very few of the additions. P.S. Apologies for the sloppy coding in the sumpairs function. It should of course do the final addition manually otherwise it is going to give odd results summing lists or strings or anything else where the order matters. Revised version: def sumpairs(seq): tmp = [] for i,v in enumerate(seq): if i&1: tmp[-1] += v i = i + 1 n = i & -i while n > 2: t = tmp.pop(-1) tmp[-1] = tmp[-1] + t n >>= 1 else: tmp.append(v) while len(tmp) > 1: t = tmp.pop(-1) tmp[-1] = tmp[-1] + t return tmp[0] From bdelmee at advalvas._REMOVEME_.be Sat Feb 17 14:33:02 2007 From: bdelmee at advalvas._REMOVEME_.be (=?ISO-8859-15?Q?Bernard_Delm=E9e?=) Date: Sat, 17 Feb 2007 20:33:02 +0100 Subject: handling secure attachments in email messages Message-ID: <45d75849$0$3126$ba620e4c@news.skynet.be> Hello, We have a processing chain automatically handling email attachments in python, which works well. We'd like to add support for encrypted files. We're using python 2.3 on HP-UX. I've checked the online 2.5 documentation, and my understanding is that the standard library still only has support for messages digests, not full encryption of content. The stock answer seems to be to use the "Python Cryptography Toolkit" by AM Kuchlin. It compiled alright on HPUX; I have a .sl extension library which I cannot import for some reason. Ideally I'd want PGP support/compatibility so senders could submit files with PGP integrated to their mail system. Can anyone suggest a module that can help achieve this goal? Any pointer or evidence of a working solution with or without usage of the aforementioned libraries would be appreciated. Thanks, Bernard. From bblais at bryant.edu Sat Feb 10 08:59:06 2007 From: bblais at bryant.edu (Brian Blais) Date: Sat, 10 Feb 2007 08:59:06 -0500 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: <1171060243.501374.249430@a75g2000cwd.googlegroups.com> References: <1170988167.356729.187920@v33g2000cwv.googlegroups.com> <1170988670.576168.205640@v33g2000cwv.googlegroups.com> <1171060243.501374.249430@a75g2000cwd.googlegroups.com> Message-ID: <45CDCFAA.2070207@bryant.edu> Klaas wrote: > I have converted our 100 kloc from 2.4 to 2.5. It was relatively > painless, and 2.5 has features we couldn't live without. > Just out of curiosity, what features in 2.5 can you not live without? I just migrated to 2.5, but haven't had much time to check out the cool new features. thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From exarkun at divmod.com Mon Feb 5 09:07:25 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 Feb 2007 09:07:25 -0500 Subject: subprocess stdin encoding In-Reply-To: <1170659429.228953.52200@q2g2000cwa.googlegroups.com> Message-ID: <20070205140725.25807.1543669276.divmod.quotient.10775@ohm> On 4 Feb 2007 23:10:29 -0800, yc wrote: >I have a encoding problem during using of subprocess. The input is a >string with UTF-8 encoding. > >the code is: > >tokenize = >subprocess.Popen(tok_command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,close_fds=True,shell=True) > >(tokenized_text,errs) = tokenize.communicate(t) > >the error is: > File "/usr/local/python/lib/python2.5/subprocess.py", line 651, in >communicate > return self._communicate(input) > File "/usr/local/python/lib/python2.5/subprocess.py", line 1115, in >_communicate > bytes_written = os.write(self.stdin.fileno(), input[:512]) >UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in >position 204: ordinal not in range(128) > > >How I change the default encoding from "ascii" to "utf-8"? You don't need to change the default encoding. You just need to encode the unicode string you are sending to the child process. Try: tokenized_text, errs = tokenize.communicate(t.encode('utf-8')) Jean-Paul From chris-list-python at shenton.org Thu Feb 1 00:32:39 2007 From: chris-list-python at shenton.org (Chris Shenton) Date: Thu, 01 Feb 2007 00:32:39 -0500 Subject: TimedRotatingFileHandler() isn't rotating at midnight? Message-ID: <86y7nimoi0.fsf@Bacalao.shenton.org> I set this up 3 days ago and have not seen any of the logs I've created this way being rotated. I expected them to rotate every midnight. I'm calling the code that uses this logger many times, each a separate run, if that matters. Am I doing something stupid? I can't find anything on google and don't see anything in the code that would prevent rotating. Thanks. import logging, logging.handlers logging.getLogger().setLevel(logging.DEBUG) # override default of WARNING logfile = logging.handlers.TimedRotatingFileHandler(filename, 'midnight', 1, backupCount=14) logfile.setLevel(logging.DEBUG) logfile.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(module)s: %(message)s')) logging.getLogger().addHandler(logfile) From aisaac at american.edu Sun Feb 11 12:18:34 2007 From: aisaac at american.edu (Alan Isaac) Date: Sun, 11 Feb 2007 17:18:34 GMT Subject: randomly generate n of each of two types Message-ID: I need access to 2*n random choices for two types subject to a constraint that in the end I have drawn n of each. I first tried:: def random_types(n,typelist=[True,False]): types = typelist*n random.shuffle(types) for next_type in types: yield next_type This works but has some obvious costs. To avoid those I considered this instead:: def random_types(n,typelist=[True,False]): type0, type1 = typelist ct0, ct1 = 0,0 while ct0+ct1<2*n: if random.random() < ((n-ct0)/(2*n-ct0-ct1)): next_type = type0 ct0 += 1 else: next_type = type1 ct1 += 1 yield next_type Does this seem a good way to go? Comments welcome. Thank you, Alan Isaac From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 15:13:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 21:13:55 +0100 Subject: get objects referencing another one In-Reply-To: References: Message-ID: <45c788ed$0$1611$426a34cc@news.free.fr> Olivier Feys a ?crit : > I'm working on a tree and I have refcounting problems. > Is it possible from an object, to get the list of objects referencing it ? Another solution may be to use weak references: http://docs.python.org/lib/module-weakref.html HTH From msoulier at gmail.com Thu Feb 1 22:14:45 2007 From: msoulier at gmail.com (msoulier) Date: 1 Feb 2007 19:14:45 -0800 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <1170386085.848910.298290@a34g2000cwb.googlegroups.com> On Jan 23, 8:50 pm, John Nagle wrote: > The major complaint I have about Python is that the packages > which connect it to other software components all seem to have > serious problems. As long as you don't need to talk to anything > outside the Python world, you're fine. As one who has attempted to develop a wxPython application with an sqlite backend, developing on both Linux and Windows, I would conclude that the problem is version skew between third-party components and the core. Python 1.5.2 touted a simple core language that made Python easy to learn. I would argue that the core is no longer simple, and it is very easy to write modules that are not backwards-compatible. This results in third-party components that you may need but are either not updated against the new version of Python that you're using, or are not compatible with the older version of Python that you shipped with. I found it quite a frustrating experience. Love the language but I'd rather it not keep reinventing itself quite so quickly, permitting maintainers to keep up, especially when said maintenance is a volunteer effort. Mike From rshepard at nospam.appl-ecosys.com Mon Feb 26 19:55:23 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 27 Feb 2007 00:55:23 GMT Subject: Lists: Converting Double to Single Message-ID: I start with a list of tuples retrieved from a database table. These tuples are extracted and put into individual lists. So I have lists that look like this: [1, 2, 3, 4, 5]. When I concatenate lists, I end up with a list of lists that looks like this: [[1, 2, 3. 4, 5]. [6, 7. 8, 9. 10]]. Then, I average the column values so I end up with a single list, but with two brackets on each end, for example, [[3.5, 4.5, 5.5, 6.5, 7.5]]. Unfortunately, when I try to use that last list in a NumPy function, I'm told that it cannot be broadcast to the correct shape. So, what I want to do is strip the extra brackes from each end to leave just [3.5, 4.5, 5.5, 6.5, 7.5]. How do I do this, please? Rich From sjmachin at lexicon.net Sun Feb 25 06:20:44 2007 From: sjmachin at lexicon.net (John Machin) Date: 25 Feb 2007 03:20:44 -0800 Subject: finding out the precision of floats In-Reply-To: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> Message-ID: <1172402444.935723.192200@m58g2000cwm.googlegroups.com> On Feb 25, 9:57 pm, "Arnaud Delobelle" wrote: > Hi all, > > I want to know the precision (number of significant digits) of a float > in a platform-independent manner. I have scoured through the docs but > I can't find anything about it! > > At the moment I use this terrible substitute: > > FLOAT_PREC = repr(1.0/3).count('3') I'm a little puzzled: You don't seem to want a function that will tell you the actual number of significant decimal digits in a particular number e.g. nsig(12300.0) -> 3 nsig(0.00123400) -> 4 etc You appear to be trying to determine what is the maximum number of significant decimal digits afforded by the platform's implementation of Python's float type. Is Python implemented on a platform that *doesn't* use IEEE 754 64-bit FP as the in-memory format for floats? Cheers, John From tm012006 at arcor.de Sun Feb 4 02:42:50 2007 From: tm012006 at arcor.de (Torsten) Date: Sun, 04 Feb 2007 08:42:50 +0100 Subject: nokia pys60 contacts + calendar In-Reply-To: References: Message-ID: <45c58e79$0$18839$9b4e6d93@newsspool4.arcor-online.net> Hi, "Programming with Python for Series 60 Platform" http://eugen.leitl.org/Programming_with_Python.pdf "Python for Series 60 Platform - API Reference" PythonForS60_doc_1_3_17.pdf should answer your questions Torsten From bearophileHUGS at lycos.com Mon Feb 26 14:36:51 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Feb 2007 11:36:51 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: <1172518611.232671.58860@k78g2000cwa.googlegroups.com> Tech HR: > In fact, there is a significant faction in > the technical staff (including the CTO) who would like nothing better > than to be able to use Lisp instead of Python. I think CLisp and Python have different enough application areas, so often where one is fit the other can't be much fit. Doing number crunching or heavy processing, or lot of symbolic/pattern processing with Python isn't positive (using Pyrex, Psyco, and numpy may help solve a small part of such problems). If you want to do some kind of html, text processing, and various other things Python may be a better choice. Bye, bearophile From joshua at eeinternet.com Fri Feb 16 19:25:55 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Fri, 16 Feb 2007 15:25:55 -0900 Subject: Output to a text window References: <1171671545.951006.160420@k78g2000cwa.googlegroups.com> Message-ID: <45d63efd$0$16342$88260bb3@free.teranews.com> google at orcon.net.nz wrote: > Hi, > > I'm going around in circles so I'm asking for help. I want to read a > simple text file and output the contents to a GUI window when I click > on a button. I have written a small python program to read the > contents of a file when a button is clicked but can only output this > to a console window. I'm using the pygtk binding with glade for the > gui. > > I know it must be quiet simple but a mental block has rapidly > descended. > > Any help would be appreciated. What does your code look like? What are you using to print? Are you writing to the GUI or using the 'print statement?' j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From python at hope.cz Fri Feb 16 08:34:55 2007 From: python at hope.cz (Johny) Date: 16 Feb 2007 05:34:55 -0800 Subject: Regex - where do I make a mistake? In-Reply-To: References: <1171629872.499083.150140@p10g2000cwp.googlegroups.com> Message-ID: <1171632895.567625.129290@l53g2000cwa.googlegroups.com> On Feb 16, 2:14 pm, Peter Otten <__pete... at web.de> wrote: > Johny wrote: > > I have > > string="""55. > > 128 > > 170 > > """ > > > where I need to replace > > 55. > > 170 > > > by space. > > So I tried > > > ############# > > import re > > string="""55. > class="test123">128170 > > """ > > Newstring=re.sub(r'.*'," ",string) > > ########### > > > But it does NOT work. > > Can anyone explain why? > > "(?!123)" is a negative "lookahead assertion", i. e. it ensures that "test" > is not followed by "123", but /doesn't/ consume any characters. For your > regex to match "test" must be /immediately/ followed by a '"'. > > Regular expressions are too lowlevel to use on HTML directly. Go with > BeautifulSoup instead of trying to fix the above. > > Peter- Hide quoted text - > > - Show quoted text - Yes, I know "(?!123)" is a negative "lookahead assertion", but do not know excatly why it does not work.I thought that (?!...) Matches if ... doesn't match next. For example, Isaac (?!Asimov) will match 'Isaac ' only if it's not followed by 'Asimov'. From boris.smirnov at gmail.com Wed Feb 28 04:00:46 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 28 Feb 2007 01:00:46 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <1172650071.878083.106290@h3g2000cwc.googlegroups.com> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172609807.109748.93170@8g2000cwh.googlegroups.com> <1172617785.871756.77380@j27g2000cwj.googlegroups.com> <1172650071.878083.106290@h3g2000cwc.googlegroups.com> Message-ID: <1172653246.535391.105780@a75g2000cwd.googlegroups.com> On Feb 28, 9:07 am, boris.smir... at gmail.com wrote: > On Feb 28, 8:56 am, Phil Thompson > wrote: > > > On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > > > > When your programs stops with the error, it should also be printing a > > > stack trace. This is a list of all the functions that have been called > > > when Python had the problem. > > > > You shouldn't have to do anything extra to get the stack trace. > > > The error is raised in Qt and aborts immediately. It never gets back to Python > > to generate a trace. > > > He needs to produce a short and complete test which demonstrates the problem, > > then we can point out where the QPaintDevice is being created. > > > Phil > > OK, but before I do a complete test, could anybody tell/explain me why > the same file is working on Windows? > Did anybody already meet with something similar Win vs. Linux? > > b. Here is my simple script: import sys from qt import * class Optimizer(QWidget): def __init__(self, parent = 0): QWidget.__init__(self) QGridLayout(self) if __name__ == '__main__': a = QApplication (sys.argv) mywidget = Optimizer() a.exec_loop() This produces this: > python qt_script_bs_070228.py QPaintDevice: Must construct a QApplication before a QPaintDevice Any suggestions here? Thanks BTW: One question: when I use "import qt" instead of "from qt import *" I get this error: Traceback (most recent call last): File "mscarideidtool_bs_070228.py", line 4, in ? class Optimizer(QWidget): NameError: name 'QWidget' is not defined What is the difference between "import qt" and "from qt import *" ? I thought that these are the same. From apardon at forel.vub.ac.be Fri Feb 9 06:39:42 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Feb 2007 11:39:42 GMT Subject: os.popen and broken pipes References: Message-ID: On 2007-02-09, Philipp Pagel wrote: > > Hi Pythoneers, > > I need to process a large number of files which have been packed by the > UNIX compress tool (*.Z files). As I am not aware of a compress > equivalent of the gzip, zipfile or bzip2 modules, I thought I'd use the > uncompress or zcat commands directly to deal with the files: > > for filename in file_list: > file = os.popen('uncompress -c '+filename, 'r') > do_something(file) > file.close() > > > This works fine for some files but results in > > 'write error onstdout: Broken pipe' > > emitted by uncompress for others. Using zcat instead of uncompress > changes the wording of the error message but not the result. > > I tried to give popen a large bufsize argument but that didn't really > help. > > Probably I'm overlooking something obvious here but right now I can't > see it. Any hints? As far as I can tell, your do_something doesn't consume the entire file. So you close the file prematurly, which results in the uncompress/zcat program trying to write to a pipe that is closed on the otherside, giving you the above message. -- Antoon Pardon From mensanator at aol.com Sun Feb 11 12:11:50 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 11 Feb 2007 09:11:50 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> Message-ID: <1171213910.829042.161820@p10g2000cwp.googlegroups.com> On Feb 11, 5:33?am, Steven D'Aprano wrote: > On Sun, 11 Feb 2007 01:08:21 -0800, mensana... at aol.com wrote: > >> An update is in the works for those > >> using more recent releases, > > > That's good news, although the responsible thing > > to do was not relaease version 2.5 until such issues > > are resolved. > > I realize you're a Windows user, and a Windows user with an AOL email > address at that, Now I know what it felt like to be a Shiite living in Iraq. > so it may come as a shock to learn that the computer > industry doesn't start and finish on Windows. I don't see why the needs of > Windows users like yourself should come ahead of the needs of users on Mac > OS, Linux, Solaris, etc. > > >> but that won't help users who don't have > >> access to Visual Studio. > > > That can be solved by throwing money at the problem. > > But money doesn't help when the solution is on the > > far side of the moon. > > You're mixing metaphors and I don't understand what you mean. > > > > > > >> >> Yes, it's > >> >> occasionally very frustrating to the rest of us, but that's life. > > >> > As the Kurds are well aware. > > >> I really don't think you help your argument by trying to draw parallels > >> between the problems of compiler non-availability and those of a > >> population subject to random genocide. > > > You missed the point of the analogy. > > > The US government suggested to the oppressed tribes > > in Iraq that they should rise up and overthrow > > Saddam Hussein at the end of the first Gulf War. > > And what did the US government do when they rose up? > > Nothing. They were left to twist in the wind. > > Both the southern Iraqis (mostly so-called "marsh Arabs" and Shiites) and > the northern Kurds rose up against Saddam Hussein. After the Kurdish > rebellion failed, the US and UK belatedly provided them with aid, lots of > aid, and kept the northern no-fly zone going until it was no longer > relevant (2003, the second invasion of Iraq). > > It was the southern Iraqis who were left to be slaughtered. Although > technically there was a no-fly zone in the south, it wasn't enforced > when it really counted -- while the rebellion was in full force, the > Iraqi government asked the US for permission to fly into the south. > Permission was given, and the Iraq air force used combat aircraft against > the rebels. Unlike the Kurds, they got no aid, neither money nor military > support. > > The end result was that the southern Iraqs were hung out to dry, while the > Kurds ended up a virtually independent state-within-a-state, with their > own "government", their own army, and US and British aircraft protecting > them. > > >> Try to keep things in perspective, please. > > > See if you can see the similarity. > > > I buy into Python. I spend a lot of effort > > developing a math library based on GMPY to use > > in my research. I discover a bug in GMPY and > > actually go to a lot of effort and solve it. > > Good on you, and I'm not being sarcastic. But do try to keep a bit of > perspective. Whatever your problem, you're not being bombed or shot. > Frankly, the fact that you not only came up with the analogy, but continue > to defend it, suggests an over-active sense of your own entitlement. > > > But _I_ can't even use it because I've been > > left to twist in the wind by the fact that > > Python 2.5 for Windows was built with an > > obsolete compiler that's not even available. > > Luckily, unlike the Kurds, my situation had > > a happy ending, someone else compiled the fixed > > GMPY source and made a 2.5 Windows version > > available. But can anyone say what will happen > > the next time? > > Get yourself a compiler, then you won't be relying on the kindness of > strangers. > > If that's not practical, for whatever reason, then remember: you're > relying on the kindness of strangers. They don't owe you a thing. If > anything, you owe them. > > [snip] > > >> Your efforts would probably be far better spent trying to build a > >> back-end for mingw or some similar system into Python's development > >> system, to allow Python for Windows to be built on a regular rather than > >> a one-off basis using a completely open source tool chain. > > > No, as I said elsewhere, I'm not a software developer, > > I'm an amateur math researcher. My efforts are best spent > > as an actual end user > > If you won't scratch your own itch, don't be surprised if nobody else > cares enough to scratch it for you. > > > to find and report bugs that the > > developers never see. Remember, a programmer, because he > > wrote it, only _thinks_ he knows how the program works. > > Whereas I, the user, _know_ how it works. > > Oh wow. That's the most audacious, self-involved and sheer arrogant claim > I've ever heard, and I've heard a lot of nonsense sprouted by arrogant > know-nothings with delusions of grandeur. For the sake of your > credibility, I hope you can support that claim. > > [snip] > > >> It's much harder than sniping on a newsgroup, > > > That figures. You try and contribute and you get > > accused of being a troll. > > "I have a problem. I demand that somebody fix it for me!" is hardly > contributing. > > If you don't have the technical skills to fix it yourself, have you > considered putting hand in pocket and paying a software developer to do > it? It might even come out cheaper than buying a commercial compiler, and > it would help others. That should appeal to somebody as altruistic as you. > > > > but you earn rather more kudos. > > > Guess what kudos I got for solving the GMPY divm() > > problem? None. How much effort would it have been > > to mention my contribution in the source code > > comments (as was the case for other contributers)? > > Not that I'm bitter, after all, I'm altruistic. > > Naturally. > > > By the way, on the sci.math newsgroup I promote > > Python every chance I get. > > That's mighty big of you. > > > One fellow thanked me > > profusely for recommending Python & GMPY and asked > > for some help with a program he was having problems > > with. We worked it out fine but his problem made me > > suspect there may be more bugs in GMPY. What's my > > motivation for tracking them down? > > Because you want the bugs fixed so you can get on with whatever coding you > want to do. > > Because you're altruistic. > > Because you want people to know how clever you are. > > Are those enough reasons? > > -- > Steven From bj_666 at gmx.net Wed Feb 7 10:46:24 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 07 Feb 2007 16:46:24 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> <1170796103.766866.18320@a34g2000cwb.googlegroups.com> <1170861935.779969.52980@v33g2000cwv.googlegroups.com> Message-ID: In <1170861935.779969.52980 at v33g2000cwv.googlegroups.com>, Gosi wrote: > I like to use J for many things and I think that combining Python and > J is a hell of a good mixture. I was able to follow this sentence up to and including the word "hell"? :-) Ciao, Marc 'BlackJack' Rintsch From yves.delalande at gmail.com Wed Feb 7 07:32:13 2007 From: yves.delalande at gmail.com (yvesd) Date: 7 Feb 2007 04:32:13 -0800 Subject: outlook bar Message-ID: <1170851533.659485.248830@v33g2000cwv.googlegroups.com> Hello, I'm trying to make an outlook bar like in python but i'm not at all familiar with ms-outlook and i'm a bit too weak and in early stage of python learning. Has somebody already made or seen the code IN TKINTER(/)PMW for a bar like that ? Thanks very much for all help. Yves From sofengboe at gmail.com Fri Feb 23 20:45:24 2007 From: sofengboe at gmail.com (sofeng) Date: 23 Feb 2007 17:45:24 -0800 Subject: Parsing HTML In-Reply-To: <1170963788.882845.124810@k78g2000cwa.googlegroups.com> References: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> <1170963788.882845.124810@k78g2000cwa.googlegroups.com> Message-ID: <1172281524.771144.302360@8g2000cwh.googlegroups.com> On Feb 8, 11:43 am, "metaperl" wrote: > On Feb 8, 2:38 pm, "mtuller" wrote: > > > I am trying to parse a webpage and extract information. > > BeautifulSoup is a great Python module for this purpose: > > http://www.crummy.com/software/BeautifulSoup/ > > Here's an article on screen scraping using it: > > http://iwiwdsmi.blogspot.com/2007/01/how-to-use-python-and-beautiful-... This article has moved to http://iwiwdsmp.blogspot.com/2007/02/how-to-use-python-and-beautiful-soup-to.html From steven.bethard at gmail.com Sun Feb 4 13:11:39 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 04 Feb 2007 11:11:39 -0700 Subject: when will python 2.5 take in mainstream? In-Reply-To: References: Message-ID: Eric CHAO wrote: > A lot of application based on python claim that python 2.3 or 2.4 is > needed not 2.5, ie. mysqldb. I've been using python for months. I > don't care about 2.4 or 2.5. But I like the default icons of python in > 2.5. So I just use that, but some scripts can't work on that. > > When will all these applications support 2.5? Many applications that require 2.3 or 2.4 work fine in 2.5. Did you try mysqldb and have it fail? Steve From gagsl-py at yahoo.com.ar Thu Feb 8 03:44:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Feb 2007 05:44:36 -0300 Subject: Referencing vars, methods and classes by name References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> <7xbqk52gt8.fsf@ruckus.brouhaha.com> Message-ID: En Thu, 08 Feb 2007 05:29:23 -0300, Paul Rubin <"http://phr.cx"@NOSPAM.invalid> escribi?: > "Sagari" writes: >> $a = ''b'; >> $obj->$a(); // call method b() of the instance $obj >> >> What is the Python way of performing the same indirections? > > For your last example we could say > > obj.getattr(a)() > > but even that is a bit ugly, depending. Surely you meant to say getattr(obj, a)() -- Gabriel Genellina From sigexfoundry at gmail.com Fri Feb 23 04:11:29 2007 From: sigexfoundry at gmail.com (sigexfoundry at gmail.com) Date: 23 Feb 2007 01:11:29 -0800 Subject: The truth about the SigEx Foundry and the SigEx Ventures Message-ID: <1172221889.176790.49220@v33g2000cwv.googlegroups.com> First of all, I'd like to appologise for the noise and for cross-posting. This is my first and last e-mail on this list. As you may have noticed from the subject of the e-mail, I'm about to speak about the SigEx Ventures company, an organisation that appoints itself as the liaison between strategic investors and young tallented people in IT&C. It originates in the US but currently operates in Europe. Specifically in Pau, France. On their website (www.sigex.com, now www.thefoundryschool.tv) they speak fluent Corporatese. I must admit, I'm not a native English speaker, but even so my ear is trained well enough for me to be able to tell spam from ham. They present some glossy products, that nobody ever actually saw working. They're all vaporware. On the same website they speak about fantastic opportunities offered to young talented fellows in the IT&C field, in the shape of internship at their fantastic research centre in Pau. Unfortunately, it's all in the demo because the real deal is nothing like it. There's no such thing as opportunity to work with cutting-edge technologies or leading researchers in the branch. It's all smoke and mirrors. As a former intern there, I feel that the truth should be made available, as neither of their statements really hold true. My best bet is that they attract investors and suck up their cash without ever producing anything. I'm gathering all sorts of information, starting with my own experience, on http://sigexfoundry.blogspot.com. Feel free to read more there. Why am I doing this? There is a term for my action, called whistleblowing. I'd like to underline the fact that I'm by no means affected by SigEx's past or current actions, I went there as an intern for merely satisfying my own curiosity about them. But I know that many of the subscribers of this list are scholars, professors, people with strong positions in the branch, most of which can easily pass as models for younger enthusiasts. They're the ones I'd like this mail to reach. It'd be a real pity if more people suffered from SigEx's dubious practices. Once again, here is the link to the blog: http://sigexfoundry.blogspot.com And, once again, sorry for the noise. From edreamleo at charter.net Fri Feb 16 10:44:08 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 09:44:08 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: > Keep the print name; > Keep the print functionality; > Keep a single code base. Retain the print statement and its functionality, and define an official_print_function to be used in the common code base. I would be satisfied with this (it's what I do now), and it would cause no needless problems for anyone. Having an official print function is a *good* idea, provided it isn't called print :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jgodoy at gmail.com Sun Feb 18 14:17:33 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 18 Feb 2007 17:17:33 -0200 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? References: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> Message-ID: <87wt2ftgvm.fsf@gmail.com> openopt at ukr.net writes: > Thank you in advance for your response. And those do ... ? -- Jorge Godoy From aboudouvas at panafonet.gr Mon Feb 26 11:56:27 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 26 Feb 2007 08:56:27 -0800 Subject: NetUseAdd mystery Message-ID: <1172508987.854983.162370@j27g2000cwj.googlegroups.com> Is anyone see any error in the following code: mapDrive = "\\\\MyServer\\C$" data = {'remote' : mapDrive, 'local' : 'M:', 'password' : 'mypassword', 'user' : 'Administrator', 'asg_type' : 0} win32net.NetUseAdd(None, 1, data) It gives me "pywintypes.error: (1326, 'NetUseAdd', 'Logon failure: unknown user name or bad password.')" and i cannot figured out why...I searched the forum about the syntax of NetUseAdd command and i think that the syntax is correct and also are the data that i pass to it. (the same data can give me a connection if i use "net use ..." from a command line" So, what am i doing the wrong way (and keeps me on this the last 2 hours??...) Thanks for a any enlightenment... From B.Ogryczak at gmail.com Tue Feb 6 06:15:35 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 6 Feb 2007 03:15:35 -0800 Subject: Python cheatsheets In-Reply-To: References: Message-ID: <1170760531.317648.93120@a34g2000cwb.googlegroups.com> On Jan 7, 10:11 pm, Jussi Salmela wrote: > gonzlobo kirjoitti: > > > Curious if anyone has a python cheatsheet* published? I'm looking for > > something that summarizes all commands/functions/attributes. Having > > these printed on a 8" x 11" double-sided laminated paper is pretty > > cool. > > > * cheatsheet probably isn't the right word, but you get the idea. :) > > http://rgruet.free.fr/ "cheatsheet"? That?s twice O?Reilly's "Python: Pocket Reference". ;-) From silverfrequent at gmail.com Fri Feb 2 12:10:44 2007 From: silverfrequent at gmail.com (Silver Rock) Date: Fri, 2 Feb 2007 15:10:44 -0200 Subject: OSS and ALSA In-Reply-To: References: Message-ID: Hi all, > > I've seen that python comes by default with a module for communication > with OSS. > > I've looked for a ALSA module too (pyalsa) but it seems to handle only > limited operations. > > Is it recommended that one programm using oss becouse of Alsa's OSS > compatibility? > > thanks, > claire > -------------- next part -------------- An HTML attachment was scrubbed... URL: From JStoneGT at aol.com Fri Feb 16 01:38:43 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Fri, 16 Feb 2007 01:38:43 EST Subject: I'm faint why this can't work Message-ID: Hello, I got this similar sample script from books: $ cat sampdict.py #!/usr/bin/python class SampDict(dict): def __init__(self, filename=None): self["name"] = filename But when I run it I got the errors: >>> from sampdict import SampDict >>> SampDict("/etc/passwd") Traceback (most recent call last): File "", line 1, in ? File "sampdict.py", line 4, in __init__ self["name"] = filename AttributeError: SampDict instance has no attribute '__setitem__' I'm using Python 2.3.4. Please help.Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Fri Feb 2 20:12:00 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 2 Feb 2007 17:12:00 -0800 Subject: How much introspection is implementation dependent? In-Reply-To: References: Message-ID: <1170465120.175164.103350@s48g2000cws.googlegroups.com> On Feb 2, 6:56 pm, James Stroud wrote: > Hello, > > I wanted to automagically generate an instance of a class from a > dictionary--which might be generated from yaml or json. I came up with this: > > (snip) > > == > > #! /usr/bin/env python > > # automagical constructor > def construct(cls, adict): > dflts = cls.__init__.im_func.func_defaults > vnames = cls.__init__.im_func.func_code.co_varnames > > argnames = vnames[1:-len(dflts)] > argvals = [adict.pop(n) for n in argnames] > > return cls(*argvals, **adict) > > def test(): > > class C(object): > def __init__(self, arg1, arg2, kwa3=3): > self.argsum = arg1 + arg2 > self.kwsum = kwa3 > def __str__(self): > return "%s & %s" % (self.argsum, self.kwsum) > > # now a dict for autmagical generation > adict = {'arg1':1, 'arg2':2, 'kwa3':42} > > print '======== test 1 ========' > print adict > print construct(C, adict) > > adict = {'arg1':1, 'arg2':2} > print > print '======== test 2 ========' > print adict > print construct(C, adict) > > if __name__ == "__main__": > test() What's the point of this ? You can call C simply by C(**adict). Am I missing something ? George From gerald.kaszuba at gmail.com Wed Feb 14 18:02:54 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 14 Feb 2007 15:02:54 -0800 Subject: ANN: Python Call Graph 0.3.0 Message-ID: <1171494173.943088.161660@v33g2000cwv.googlegroups.com> Hi, I just released pycallgraph 0.3.0. There are many examples on the web site and linked from the web site including a 16188 x 4187 sized call graph! http://pycallgraph.slowchop.com/ The changes are: * Renamed make_graph to make_dot_graph to allow different output types in the future * Callback filter patch by Alec Thomas -- allows more flexibility when filtering calls, including wildcards * Added filter example * Added docstrings The documentation is slowly coming along with epydoc generated documentation from the docstrings. More will come soon. Also on the horizon are different types of formats like ASCII and HTML output. Have fun. Gerald From mail at microcorp.co.za Mon Feb 26 01:11:18 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 26 Feb 2007 08:11:18 +0200 Subject: Nested Parameter Definitions References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> <1172435827.794518.36170@t69g2000cwt.googlegroups.com> Message-ID: <014c01c7596d$15298b60$03000080@hendrik> "Arnaud Delobelle" wrote: > On Feb 25, 6:00 pm, "Paddy" wrote: > > I blogged on finding a new-to-me feature of Python, in that you are > > allowed to nnest parameter definitions: > > > > >>> def x ((p0, p1), p2): > > > > ... return p0,p1,p2 > > ...>>> x(('Does', 'this'), 'work') > > > > ('Does', 'this', 'work') > > Reminds me of LeLisp! It had a similar feature. IIRC you could write > for example (I think 'df' was LeLisp for 'defun'): > (df mycar (a . b) a) > or > (df mylist L L) > or > (df mycaadr (a (b . c) . e) b) > > I didn't know that this was possible in python and it does surprise > me. It feels at odd with the python philosophy. > Not at all - it much nicer than you think, and there is no "nesting" involved - Penguins carry their eggs on their feet. The original function definition describes a function that has a two element tuple as a first parameter, and something else as a second one. The first two names provide a means of accessing the elements of the tuple, instead of using slicing. look at this: >>> def f((a,b),c): return a,b,c >>> tup = ('hi','there') >>> f(tup,'foo') ('hi', 'there', 'foo') >>> lis = ['hi','there'] >>> f(lis,'foo') ('hi', 'there', 'foo') >>> d,e,f = f(lis,42) >>> print d,e,f hi there 42 >>> e 'there' >>> s = 'go' >>> f(s,'back') ('g', 'o', 'back') >>> Long live duck typing... - Hendrik From steve at REMOVE.THIS.cybersource.com.au Tue Feb 20 11:33:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 03:33:46 +1100 Subject: file io (lagged values) newbie question References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> <1171984082.488529.76040@p10g2000cwp.googlegroups.com> Message-ID: On Tue, 20 Feb 2007 07:08:02 -0800, John Machin wrote: >> def write_series(data, f): >> """Write a time series data to file f. >> >> data should be a list of integers. >> f should be an already opened file-like object. >> """ >> # Convert data into a string for writing. >> s = str(data) >> s = s[1:-1] # strip the leading and trailing [] delimiters >> s = s.replace(',', '') # delete the commas >> # Now write it to the file object >> f.write(s) >> f.write('\n') > > And that's not cruft? No. Why do you think it is crufty? Would it be less crufty if I wrote it as a cryptic one liner without comments? f.write(str(data)[1:-1].replace(',', '') + '\n') Okay, it depends on the string conversion of a list. But that's not going to change any time soon. > Try this: f.write(' '.join(str(x) for x in data) + '\n') That will only work in Python 2.5 or better. -- Steven. From steve at REMOVE.THIS.cybersource.com.au Sat Feb 17 19:14:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 18 Feb 2007 11:14:30 +1100 Subject: How do I save the contents of a text buffer References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> Message-ID: On Sat, 17 Feb 2007 15:47:20 -0800, google wrote: > As a test, I tried to write the buffer back to a file with this code > but did not work, Oooh, guessing games! I love guessing games! Let me see... did it reboot your PC? Did Python crash? Did you get an exception? Maybe something about not being able to open the file for reading? Or perhaps disk full? Did you get something unexpected in the file? Maybe an empty file? I'm guessing... it erased your hard disk. Do I win? -- Steven. From arnodel at googlemail.com Sun Feb 25 09:11:02 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 25 Feb 2007 06:11:02 -0800 Subject: finding out the precision of floats In-Reply-To: <1172410271.154309.49700@j27g2000cwj.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> Message-ID: <1172412661.998318.109180@s48g2000cws.googlegroups.com> On Feb 25, 1:31 pm, "John Machin" wrote: > On Feb 25, 11:06 pm, "Arnaud Delobelle" > wrote: [...] > Evidently not; here's some documentation we both need(ed) to read: > > http://docs.python.org/tut/node16.html Thanks for this link > I'm very curious to know what the exceptions were in November 2000 and > if they still exist. There is also the question of how much it matters > to you. Presuming the representation is 64 bits, even taking 3 bits > off the mantissa and donating them to the exponent leaves you with > 15.05 decimal digits -- perhaps you could assume that you've got at > least 15 decimal digits. It matters to me because I prefer to avoid making assumptions in my code! Moreover the reason I got interested in this is because I am creating a Dec class (decimal numbers) and I would like that: * given a float x, float(Dec(x)) == x for as many values of x as possible * given a decimal d, Dec(float(d)) == d for as many values of d as possible. (and I don't want the standard Decimal class :) > While we're waiting for the gurus to answer, here's a routine that's > slightly less dodgy than yours: > > | >>> for n in range(200): > | ... if (1.0 + 1.0/2**n) == 1.0: > | ... print n, "bits" > | ... break > | ... > | 53 bits Yes I have a similar routine: |def fptest(): | "Gradually fill the mantissa of a float with 1s until running out of bits" | ix = 0 | fx = 0.0 | for i in range(200): | fx = 2*fx+1 | ix = 2*ix+1 | if ix != fx: | return i ... >>> fptest() 53 I guess it would be OK to use this. It's just that this 'poking into floats' seems a bit strange to me ;) Thanks for your help -- Arnaud From bdesth.quelquechose at free.quelquepart.fr Tue Feb 6 13:46:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 19:46:34 +0100 Subject: Calling J from Python In-Reply-To: <1170749117.582426.151770@p10g2000cwp.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> Message-ID: <45c8c5ed$0$26712$426a74cc@news.free.fr> Gosi a ?crit : > On Feb 6, 3:04 am, "Eric_Dex... at msn.com" wrote: > >>On Feb 5, 8:48 am, "Gosi" wrote: >> >> >>>It is quite easy to call J from Python >> >>>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... >> >>There are a couple of issue that should be adressed. Am I going to >>jail if I write a program and then redistribute all the files required >>to run the program I write?? > > > J is free for anyone to download and use. But not to inspect or modify. This is "free" as in "free beer", not as in "free speech". > >>The second is how do I use the j stuff >>without learning all that much about j. > > > Just like Python then how much time you spend is uo to you. > > If you want to be good at it you may have to spend some time. > > You may also be just a casual user and dip into it now and again. This is easy with Python, which emphasis readability. I doubt one can say the same about j. From http Wed Feb 14 22:01:22 2007 From: http (Paul Rubin) Date: 14 Feb 2007 19:01:22 -0800 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> <7xr6ssqis8.fsf@ruckus.brouhaha.com> Message-ID: <7x4ppo6s59.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Yes it does. Eventually f goes out of scope and is closed automatically. Oh right, however you can't really predict when the closure occurs, unless you're relying on current CPython artifacts. Re your other post: yes, PEP 363 explains how the "with" statement calls the __exit__ method. From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 14:48:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 20:48:40 +0100 Subject: how to add class attributes in __new__ In-Reply-To: <1170348611.562439.122780@a34g2000cwb.googlegroups.com> References: <1170348611.562439.122780@a34g2000cwb.googlegroups.com> Message-ID: <45c23d20$0$421$426a34cc@news.free.fr> jeremito a ?crit : > I am subclassing the array class and have __new__ to initialize and > create my class. In that class I create not only do I create an array > object, but I also create some other data in __new__ I want to have > access to outside of __new__. I tried > > self.mydata = mydata > > but that didn't work. > > Can someone point me in the right direction? http://www.python.org/download/releases/2.2.3/descrintro/#__new__ From luismgz at gmail.com Wed Feb 28 16:53:37 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Feb 2007 13:53:37 -0800 Subject: class declaration shortcut In-Reply-To: <7o-dndyPgY_db3jYnZ2dnUVZ_t2tnZ2d@comcast.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <7o-dndyPgY_db3jYnZ2dnUVZ_t2tnZ2d@comcast.com> Message-ID: <1172699617.628947.118110@m58g2000cwm.googlegroups.com> On Feb 28, 6:21 pm, Steven Bethard wrote: > Luis M. Gonz?lez wrote: > > I've come across a code snippet inwww.rubyclr.comwhere they show how > > easy it is to declare a class compared to equivalent code in c#. > > I wonder if there is any way to emulate this in Python. > > > The code is as follows: > > > Person = struct.new( :name, :birthday, :children) > > How about something like:: > > class Person(Record): > __slots__ = 'name', 'birthday', 'children' > > You can then use the class like:: > > person = Person('Steve', 'April 25', []) > assert person.name == 'Steve' > assert person.birthday == 'April 25' > assert not person.children > > Is that what you were looking for? If so, the recipe for the Record > class is here: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 > > STeVe Hmmm... not really. The code above is supposed to be a shorter way of writing this: class Person: def __init__(self, name, birthday, children): self.name = name self.birthday = birthday self.children = children So the purpose of this question is finding a way to emulate this with a single line and minimal typing. There are a few problems here: 1) How to get the variable name (in this case "Person") become the name of the class without explicity indicating it. 2) How to enter attribute names not enclosed between quotes. The only way I can do it is by entering them as string literals. It's not that I desperately need it, but I'm just curious about it... Luis From svatoboj at gmail.com Tue Feb 27 09:24:41 2007 From: svatoboj at gmail.com (svata) Date: 27 Feb 2007 06:24:41 -0800 Subject: os.system and quoted strings Message-ID: <1172586281.606903.79990@s48g2000cws.googlegroups.com> Hello, as I'm new to python I've stumbled accros os.system and its not very well documented usage. I use Win XP Pro and Python 2.5. Here is the code snippet: -------------------------------------------------------------------------------------------------- import time import os dir = "C:\\Documents and Settings\\somepath\\" fileName = time.strftime("%d%m%Y") os.system('gvim dir+fileName+".txt"') --------------------------------------------------------------------------------------------------- The problem is that concatenated variable dir+fileName doesn't get expanded as expected. Is there anything I omitted? svata From donn at u.washington.edu Fri Feb 16 19:31:17 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 16 Feb 2007 16:31:17 -0800 Subject: IOError: [Errno 4] Interrupted system call References: <1171594649.279210.139470@l53g2000cwa.googlegroups.com> <1171660060.302688.101070@k78g2000cwa.googlegroups.com> Message-ID: In article <1171660060.302688.101070 at k78g2000cwa.googlegroups.com>, chadrik at gmail.com wrote: > i don't have any signal handlers in my code, but i have no idea what > is going on in the internals of the pyQt framework that i'm using for > the GUI. > > as far as simply ignoring the exception, that does not seem to work. > for instance, here's some code i've tried: > > > p = subprocess.Popen('mycommand', shell=True, stdin=subprocess.PIPE, > stdout=subprocess.PIPE, close_fds=True) > output = '' > tries = 0 > while tries < 12: > try: > tries = tries+1 > print "retrieving results" > output = p.stdout.readlines() > > except IOError: > print "IOError! try %s" % tries > print "output:", output > #time.sleep(1) > else: > print "Great Success" > print "output:", output > break ... > if the first try raises an error output does not get set and then the > second try succeeds but returns an empty list when it should return > results. moving the Popen inside the loop isn't an option either, > because, in addition to returning results, the command performs an > action which should only run once. > > sorry if i'm missing something obvious here, i'm a python newb. No, actually this is somewhat non-obvious, if I'm right. You can't use readlines() like that, it's a Python thing that evidently loses some or all of its buffered data, and you start over from scratch. Instead, probably the simplest thing would be to implement your own readlines around that restart loop, actually reading one line at a time and appending to the line list. I'm not sure that's totally bulletproof - probably will work, but if you need a sure thing, I would go to UNIX I/O (posix.read), in a loop, and then split the concatenated results by newline. Or, of course if you could shut down the signals... Donn Cave, donn at u.washington.edu From paul at boddie.org.uk Mon Feb 26 12:07:53 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 26 Feb 2007 09:07:53 -0800 Subject: ez_setup.py In-Reply-To: References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> <45E305D0.4010806@timgolden.me.uk> <45E3075E.2090308@knmi.nl> <45E3083F.2020303@timgolden.me.uk> <45E30AE9.40900@knmi.nl> Message-ID: <1172509673.917257.172100@v33g2000cwv.googlegroups.com> On 26 Feb, 17:36, Tim Golden wrote: > > OK. Keep copying to the list, please. As I said, I'm not > a *nix person (and I'm running here on Windows) so you'll > get a more informed and wider audience from c.l.py. Just to clarify one thing, $HOME isn't automatically inserted into sys.path on UNIX, at least in all versions of Python I've used. However, the directory where an executed Python program resides may be used in the process of locating modules: it seems to be inserted automatically into sys.path as the first element, in fact. So if calendar.py is in the same directory as ez_setup.py, I would imagine that any attempt to import the calendar module will result in the this non-standard calendar.py being found and imported, rather than the standard library's calendar module. The most appropriate solution is to put ez_setup.py in other location and then to run it. For example: mv ez_setup.py /tmp python /tmp/ez_setup.py Putting the non-standard calendar.py in a directory separate from other programs might be an idea, too. Paul From exarkun at divmod.com Thu Feb 8 12:25:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 8 Feb 2007 12:25:20 -0500 Subject: postgres backup script and popen2 In-Reply-To: <1170955106.724239.47920@k78g2000cwa.googlegroups.com> Message-ID: <20070208172520.25807.130012284.divmod.quotient.14698@ohm> On 8 Feb 2007 09:18:26 -0800, Gabriel Genellina wrote: >On 8 feb, 13:29, Jean-Paul Calderone wrote: >> On 8 Feb 2007 08:23:49 -0800, Gabriel Genellina wrote: >> >On 8 feb, 10:27, Ma?l Benjamin Mettler wrote: >> >> flupke schrieb: >> >> > i made a backup script to backup my postgres database. >> >> > Problem is that it prompts for a password. It thought i >> >> > could solve this by using popen2. >> >> >> Use pexpect:http://pexpect.sourceforge.net/ >> >> >pexpect could work. But a better way would be to supply the password >> >on the command line. >> >> So that it shows up in `ps' output to anyone on the system? :) > >Any solution has pros and cons... Some solutions have more or less of these than other solutions though. >having the password in the source code is not so good anyway... Sure, but just because one has a password in the source doesn't mean one should completely give up. If you want to completely give up, you can just disable password authentication in pgsql. That's a lot simpler than any other solution mentioned so far. :) Jean-Paul From __peter__ at web.de Tue Feb 13 09:20:18 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Feb 2007 15:20:18 +0100 Subject: float print formatting References: Message-ID: hg wrote: > Considering the float 0.0, I would like to print 00.00. > > I tried '%02.02f' % 0.0 ... but I get 0.00 > > Any clue ? The first integer specifies the total width: >>> "%05.2f" % 0 '00.00' Peter From chrisc at dbass.demon.co.uk Wed Feb 7 11:35:41 2007 From: chrisc at dbass.demon.co.uk (magnate) Date: 7 Feb 2007 08:35:41 -0800 Subject: (n)curses or tcl/tk? Message-ID: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> Hi All, Just learning Python - my first new language for about 18 years (I'm not a programmer ...). I'm writing a small utility to manipulate some text files (for the game VGA Planets, if you're interested: http:// www.phost.de). It's currently working, but it looks a bit ugly with raw_input and just basic text output. I have plans to expand the functions of the utility, and I want a simple GUI frontend. I assumed I'd end up with something that looks a bit like the Debian installer: a curses-driven thing with simple ascii boxes and buttons. But reading a bit more about Python makes me think that support for tcl/tk is much more developed than support for curses. So my question is, should I go to the trouble of learning how to make boxes and stuff using tcl/tk, or just go with ncurses as I imagined? Which is more portable? The basic idea is that this just runs on the largest possible variety of systems (er, assuming they have Python installed, of course). I use Debian mostly, but of course it needs to run on bog-standard Windows boxes. Does that tilt the balance in favour of curses or tcl/tk? Or should I just stick with ugly text? Thanks for all your help, CC (noob) From alan.franzoni_invalid at geemail.invalid Fri Feb 16 05:40:02 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Fri, 16 Feb 2007 11:40:02 +0100 Subject: The Python interactive interpreter has no command history References: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> Message-ID: Il Thu, 15 Feb 2007 15:14:00 -0200, Eduardo "EdCrypt" O. Padoan ha scritto: > Are you using Ubuntu? The last comes with 2.4.x and 2.5. This only > occurs on 2.5. This happens when you compile Python with libreadline > installed, AFAIK. I'm on Edgy and command history works well both with 2.4 and 2.5 with my config. If it's really an Edgy glitch, it must be configuration-related! -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From adamgarstang at googlemail.com Wed Feb 28 17:23:13 2007 From: adamgarstang at googlemail.com (Adam) Date: 28 Feb 2007 14:23:13 -0800 Subject: New to Tkinter GUI building In-Reply-To: References: <1172695675.279652.98920@a75g2000cwd.googlegroups.com> Message-ID: <1172701393.612661.193690@m58g2000cwm.googlegroups.com> On Feb 28, 9:13 pm, Adonis Vargas wrote: > Adam wrote: > > > > > I think my main questions are: > > 1. How can I get the Window to be sized the way I want it? > > 2. How can I get the Scrollbars to fill the side of the text box > > instead of being small? (like .pack(fill= tk.Y) > > > > > I have only posted the code relevant to the GUI. > > > TIA > > Adam > > To size the window use Tk's geometry method > > self.top.geometry("%dx%d%+d%+d" % (800, 600, 0, 0)) # (width, > height, x, y) > > For the scrollbar to fill vertically, use the sticky grid option. > > self.scrlr1.grid(row=0, column=1, sticky=tk.N + tk.S) > > Hope this helps. > > Adonis Can't test now as its late in th UK and I'm going to bed. Looks good though. So remove the size from the frames etc and use the geometry method instead? Then use grid to "pack" them for want of a better word? From steve at REMOVEME.cybersource.com.au Thu Feb 1 21:30:44 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 02 Feb 2007 13:30:44 +1100 Subject: Sorting a list References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c24563$0$31965$c3e8da3@news.astraweb.com> Message-ID: On Thu, 01 Feb 2007 14:52:03 -0500, John Salerno wrote: > Bruno Desthuilliers wrote: > >> You don't tell how these lines are formatted, but it's possible that you >> don't even need a regexp here. But wrt/ sorting, the list of tuples with >> the sort key as first element is one of the best solutions. > > Ah, so simply using sort() will default to the first element of each tuple? No. It isn't that sort() knows about tuples. sort() knows how to sort a list by asking the list items to compare themselves, whatever the items are. Tuples compare themselves by looking at the first element (if any), and in the event of a tie going on to the second element, then the third, etc. -- Steven D'Aprano From donmorrison at gmail.com Wed Feb 7 16:11:58 2007 From: donmorrison at gmail.com (Don Morrison) Date: Wed, 7 Feb 2007 13:11:58 -0800 Subject: string.find for case insensitive search In-Reply-To: References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: lower() is also deprecated :) oh well On 7 Feb 2007 21:06:08 GMT, Duncan Booth wrote: > "Johny" wrote: > > > Is there a good way how to use string.find function to find a > > substring if I need to you case insensitive substring? > > s.lower().find(substring.lower()) > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnny_garcia51 at sbcglobal.net Sun Feb 11 15:43:29 2007 From: johnny_garcia51 at sbcglobal.net (Johnny Garcia) Date: Sun, 11 Feb 2007 20:43:29 GMT Subject: New Pythin user looking foe some good examples to study Message-ID: I have just discovered Python and am familiarizing myself with the syntax but I have always found that code examples where the best way for me to learn. Can anyone point me to a site with some good open source functioning python applications? I would appreciate any help. Also, does anyone know of any good Linux or python user groups in the orange county, California area? From rdiaz02 at gmail.com Wed Feb 28 07:30:54 2007 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Wed, 28 Feb 2007 13:30:54 +0100 Subject: book for a starter In-Reply-To: <1115a2b00702271431x59272addq3beab195b0f696c5@mail.gmail.com> References: <54j9qfF20cqgnU1@mid.individual.net> <1172603326.853903.315620@z35g2000cwz.googlegroups.com> <1172606926.215944.227660@v33g2000cwv.googlegroups.com> <1115a2b00702271431x59272addq3beab195b0f696c5@mail.gmail.com> Message-ID: <624934630702280430t1c91c851n8eb39fa1eae94dff@mail.gmail.com> On 2/27/07, Wensui Liu wrote: > Thank you all for your wonderful suggestion and advice. > > Have a great evening! > > wensui > > On 27 Feb 2007 12:08:46 -0800, RickMuller wrote: > > On Feb 27, 12:08 pm, "Sriram" wrote: > > > Hi, > > > > > > If you have experience programming, just read the online tutorial athttp://docs.python.org/tut/tut.html > > > > > > > Seconded. It really is a wonderful introduction to Python. Once you've > > digested that, the Python Library Reference in the docs is your best > > friend. The nice thing about getting familiar with the official python > > documentation is that it's always available to you. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > WenSui, from the R list I think you are not a novice programmer. I'd recommend Python in a Nutshell. Note there is a recent edition that covers Python 2.5. (I actually use almost exclusively Nuthsell --- and the pocket reference which is small and inexpensive and i carry on my backpack all the time). Best, R. > > -- > WenSui Liu > A lousy statistician who happens to know a little programming > (http://spaces.msn.com/statcompute/blog) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From nathan.shair at gmail.com Thu Feb 15 10:53:41 2007 From: nathan.shair at gmail.com (nathan.shair at gmail.com) Date: 15 Feb 2007 07:53:41 -0800 Subject: output to console and to multiple files In-Reply-To: <1171498259.757320.127100@q2g2000cwa.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171498259.757320.127100@q2g2000cwa.googlegroups.com> Message-ID: <1171554821.510472.313950@s48g2000cws.googlegroups.com> On Feb 14, 5:10 pm, "goodwolf" wrote: > like this? > > class Writers (object): > > def __init__(self, *writers): > self.writers = writers > > def write(self, string): > for w in self.writers: > w.write(string) > > def flush(self): > for w in self.writers: > w.flush(): > > import sys > > logfile = open('log.txt', 'w') > sys.stdout = Writers(aya.stdout, file('log.out', 'w'), logfile) > sys.stderr = Writers(aya.stdout, file('log.err', 'w'), logfile) i've tried simliar methods to this and to what Matimus wrote. I know it works great when using print statements. However, I'm looking to find something that will work with the output from a subprocess, such as from spawn, os.system, os.popen, etc. From sickcodemonkey at gmail.com Thu Feb 8 21:32:50 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 8 Feb 2007 21:32:50 -0500 Subject: Dictionary Question Message-ID: <2adc542f0702081832k2b917a86pede0f419d5ff7be4@mail.gmail.com> Hello All. I have a question concerning searching data within dictionaries. Lets say I have a dictionary called db. db = {'blah at gmail.com':'none', 'blah at yahoo.com':'none', 'blah at aol.com':'none', 'blah at gmail.com':'none',} And I want to pull out all of the "gmail.com" addresses.. How would I do this? NOTE: I already have a regular expression to search for this, but I feel that looping over a dictionary is not very efficient. So I have: domsrch = re.compile(r"@(\S+)") listToLookFor = ['gmail.com'] db = {'blah at gmail.com':'none', 'blah at yahoo.com':'none', 'blah at aol.com':'none', 'blah at gmail.com':'none',} I wonder if there is a way to do something like for item in listToLookFor: if domsrch.findall(db.has_key( item )): print "horray" NOTE: I know the findall is for lists, but I dont know of an efficient way to search for this in a dictionary. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 13 06:46:25 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Feb 2007 12:46:25 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171360113.585827.17440@v45g2000cwv.googlegroups.com> Message-ID: devicerandom at gmail.com wrote: > On 13 Feb, 09:14, Peter Otten <__pete... at web.de> wrote: >> deviceran... at gmail.com wrote: >> > Thanks both for suggestions. I still think that using inheritance is >> > somehow cleanest in this case (I always hear the mantra "avoid >> > multiple inheritance!", but this is one of the cases it seems to make >> > a lot of sense to me), but it's nice food for thought/code anyway. >> >> "Avoid inheritance" would be almost as justified :-) > > Why? Well, what problems ocurring with class A: pass class B: pass class C(A, B): pass could be avoided by writing class A: pass class B(A): pass class C(B): pass instead? Classes have to be designed for subclassing, so essentially you get two interfaces, one for subclasses and one for client code instead of just the latter. A more relevant mantra governing inheritance is "Flat is better than nested". >> Problems that may arise with this case of multiple inheritance: >> >> - If you need initializers, ensure that they are all invoked > > Yes, I figured it out. This should be easy in this case. > >> - What would you do about name clashes? To avoid them your plugins need >> to know about each other. > > Yes, I know, but I can't see any simple solution to this (if you can, > please share it with me!). The cmd module works by interpreting any > method starting with "do_" as a command, so "do_blah" becomes the > "blah" command. If two people write a "do_blah" command, and both > plugins are used, I see no easy way to solve the issue (apart > rewriting a cmd module). > Perhaps there can be some previous sanity check in each modules dict > to see if there are obvious namespace clashings, and in this case > issue a warning. I don't know. > >> - State (instance attributes) is shared among all your plugins. Since you >> call all base classes Commands, Python's double-underscore hack won't >> work. > > What double-underscore hack are you referring to? (sigh, my python > limits are all arising...) I can call all base classes > PluginNameCommand, however, this wouldn't break the thing (I'm still > at the very early planning stage) and would maybe work. If you use attributes starting with two underscores inside a method, Python transparently prepends them with the class name. This allows to you to use the same variable name in two base classes and reduces coupling: >>> class A: ... def set_a(self, v): self.__value = v ... >>> class B: ... def set_b(self, v): self.__value = v ... >>> class C(A, B): pass ... >>> c = C() >>> c.set_a("alpha"); c.set_b("beta") >>> vars(c) {'_A__value': 'alpha', '_B__value': 'beta'} But if two classes with the same name use the "private" variable, the mechanism fails: >>> OldA = A >>> class A: ... def set_b(self, v): self.__value = v ... >>> class C(A, OldA): pass ... >>> c = C() >>> c.set_a("alpha"); c.set_b("beta") >>> vars(c) {'_A__value': 'beta'} Peter From wuwei23 at gmail.com Wed Feb 7 19:52:40 2007 From: wuwei23 at gmail.com (alex23) Date: 7 Feb 2007 16:52:40 -0800 Subject: Group Membership in Active Directory Query In-Reply-To: <1170872824.710879.272830@v45g2000cwv.googlegroups.com> References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> <1170859017.416570.247920@v33g2000cwv.googlegroups.com> <1170872824.710879.272830@v45g2000cwv.googlegroups.com> Message-ID: <1170895960.022698.299500@h3g2000cwc.googlegroups.com> On Feb 8, 4:27 am, kooc... at gmail.com wrote: > First and foremost thanks for the feedback. Although I don't > appreciate the slight dig at me. > dummy = ldap_obj.simple_bind...... I _really_ don't think Uwe was intending any slight, 'dummy' generally means 'dummy variable' ie it's just there to catch the value but it's never used after that :) If you're doing a lot of AD work, I highly recommend Tim Golden's active_directory module: http://timgolden.me.uk/python/ active_directory.html His WMI module has also been a godsend on a number of occasions. - alex23 From ruan at jcmills.com Wed Feb 7 13:17:59 2007 From: ruan at jcmills.com (Ruan) Date: Wed, 7 Feb 2007 13:17:59 -0500 Subject: Why doesn't my heapify work? References: <52uiomF1olkevU1@mid.uni-berlin.de> Message-ID: I found out what is wrong. You must give it a negative step, like range(10,1,-1) But my code is not good enought for heapify. I will try again. "Ruan" wrote in message news:eqd4nn$473e$1 at netnews.upenn.edu... > Can't range go from larger to smaller? > > > "Diez B. Roggisch" wrote in message > news:52uiomF1olkevU1 at mid.uni-berlin.de... >> Dongsheng Ruan wrote: >> >>> I want to turn an Array into a heap, but my code just doesn't work: no >>> change after execution. >>> >>> A=[3,5,4,9,6,7] >>> m=len(A)-1 >>> >>> >>> >>> for i in range(m,1): >>> t=(i-1)/2 >>> if A[i]>A[t]: >>> A[i],A[t]=A[t],A[i] >> >> First of all, there is the module heapq that will just do it. >> >> And then you seem to misunderstand how the range-function works. range(m, >> 1) >> will always be the empty list. See >> >> pydoc range >> >> for how it operates. >> >> Overall, your code is very unpythonic, to say the least. I suggest you >> start >> reading the python tutorial first: >> >> http://docs.python.org/tut/ >> >> Especially the looping techniques section: >> >> http://docs.python.org/tut/node7.html#SECTION007600000000000000000 >> >> Diez > > From otsaloma at cc.hut.fi Mon Feb 26 10:33:20 2007 From: otsaloma at cc.hut.fi (Osmo Salomaa) Date: Mon, 26 Feb 2007 17:33:20 +0200 Subject: How to delete PyGTK ComboBox entries? In-Reply-To: References: Message-ID: <1172504000.3601.13.camel@localhost> ma, 2007-02-26 kello 16:08 +0100, Ma?l Benjamin Mettler kirjoitti: > I need to repopulate PyGTK ComboBox on a regular basis. In order to do > so I have to remove all the entries and then add the new ones. > And then repopulate by iterating through the list of desired entries and > calling ComboBox.append_text(text). It works, but is painfully > sloooooooow! model = combo_box.get_model() combo_box.set_model(None) model.clear() for entry in desired_entries: model.append([entry]) combo_box.set_model(model) model.append is essentially the same as combo_box.append_text. Setting the model to None before making changes to it speeds things at least in the case of tree views. I'm not sure if it does much with combo boxes. If you experince speed issues with combo boxes you're either doing something very wrong or you have so many entries that you ought to be using a tree view instead. -- Osmo Salomaa From iamyourenemy at gmail.com Tue Feb 6 06:25:08 2007 From: iamyourenemy at gmail.com (Alejandro Barroso) Date: 6 Feb 2007 03:25:08 -0800 Subject: Inheriting str object In-Reply-To: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> References: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> Message-ID: <1170761108.689314.270210@s48g2000cws.googlegroups.com> On 5 feb, 11:48, "kungfoo... at gmail.com" wrote: > I want to have a str with custom methods, but I have this problem: > > class myStr(str): > def hello(self): > return 'hello '+self > > s=myStr('world') > print s.hello() # prints 'hello world' > s=s.upper() > print s.hello() # expected to print 'hello WORLD', but s is no longer > myStr, it's a regular str! > > What can I do? I'm new to this list(this is my first message) and to Python also (I'm learning these days), so i'm afraid that this is not what you are asking for but anyway you can create an myStr object on the fly, something like: s=myStr(s.upper()) Alex From kristnjov at nospam.com Mon Feb 12 07:32:24 2007 From: kristnjov at nospam.com (Deniz Dogan) Date: Mon, 12 Feb 2007 13:32:24 +0100 Subject: Formatting milliseconds to certain String Message-ID: Hello. I need help with a small problem I'm having. I want to make a function which takes an integer representing some time in milliseconds and returns the same time but formatted as "hours:minutes:seconds,milliseconds" with leading zeros whenever possible. E.g. I input 185804 to the function and it returns 00:03:05,804. The function I'm using now is defined as: def millisToFormat(millis): try: hours = millis / 3600000 mins = (millis - hours * 3600000) / 60000 secs = (millis - hours * 3600000 - mins * 60000) / 1000 millis = millis - hours * 3600000 - mins * 60000 - secs * 1000 hours = str(hours) mins = str(mins) secs = str(secs) millis = str(millis) if len(hours) == 1: hours = "0"+hours if len(mins) == 1: mins = "0"+mins if len(secs) == 1: secs = "0"+secs if len(millis) < 3: millis = (len(millis) - 3) * "0" + millis return str(hours) + ":" + str(mins) + ":" + str(secs) + "," + str(millis) except ValueError: return -1 Note that I am very new to Python and the language I have been using most prior to this is Java. --Deniz Dogan From __peter__ at web.de Sat Feb 3 11:43:15 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Feb 2007 17:43:15 +0100 Subject: Jython References: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> Message-ID: Boris Ozegovic wrote: > Boris Ozegovic wrote: > >> gregturn at mindspring.com wrote: >> >>> Files aren't lists and thus don't have the functions for iteration. >> >> They do have iterator: >> >> C:\Documents and Settings\Silovana Vjeverica\Desktop>python FileReader.py >> 'import site' failed; use -v for traceback >> boris ozegovic >> vedran ozegovic > > But apparently not in Jython... Only Python. Iterable files were introduced in Python 2.2. Jython implements Python2.1, it seems. Peter From elrondrules at gmail.com Thu Feb 1 20:52:09 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 1 Feb 2007 17:52:09 -0800 Subject: script not opening applications Message-ID: <1170381129.210371.279800@m58g2000cwm.googlegroups.com> hi i have a html as follows:
my hello.py is as follows import os os.system ("export DISPLAY=10.0.1.1:0.0") os.system ("./Test &") #Testtool opens a new window What I expected this to do was once I click "Run Test" it should run the hello.py script and open a new window for the Test application. both the hello.py and the test application are in the cgi-bin directory If I run the hello.py in the command line it works fine but not through the html... Any idea as to whats missing.. Thanks From casevh at gmail.com Sat Feb 24 01:19:30 2007 From: casevh at gmail.com (casevh at gmail.com) Date: 23 Feb 2007 22:19:30 -0800 Subject: Rational numbers In-Reply-To: References: <20070223103519.08f25af9@localhost> Message-ID: <1172297970.069334.193020@a75g2000cwd.googlegroups.com> > Looks pretty much the same as mx.Number > > Does this warning come up from gmp? Do I have to compile it with > different flags? > Or do both wrappers use the same code? > > I would like to encourage the python community (i.e. the guys > maintaining the python docs) to point out a recommended rational > library. In one of the rational PEPs, it is stated that there are > multiple robust rational wrappers for python. But it is not stated, > which ones were thoroughly reviewed. > That specific error message is only a warning that occurs the first time a comparison operation is performed. I've successfully used gmpy and just ignored the one-time only error. You can use the "warnings" module to filter out that error. If I remember correctly, it was fixed in version 1.01. I know it is fixed in the SVN version. Which specific version of gmpy are you using? (What is gmpy.version()?) I just compiled Alex's most recent SVN version on Linux without any problems. I'll make Windows binaries next. casevh From aahz at pythoncraft.com Fri Feb 23 19:06:22 2007 From: aahz at pythoncraft.com (Aahz) Date: 23 Feb 2007 16:06:22 -0800 Subject: Pep 3105: the end of print? References: <1171997191.188621.298090@q2g2000cwa.googlegroups.com> <1172221477.057173.22390@q2g2000cwa.googlegroups.com> Message-ID: In article <1172221477.057173.22390 at q2g2000cwa.googlegroups.com>, Jay Tee wrote: > >On the other hand, C++ is firmly established as a "serious" language >in our community while python is not. So the programmers tend to be >more forgiving. There is no perception that compiler developers are >*trying* to be difficult by changing the language to break backwards >compatibility. That's the difference I think. Consider the difference between "Python 3.0 is designed to break backward compatibility" and "Python 3.0 cleans up a lot of accumulated cruft". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From Alessandro.Fachin at gmail.com Sat Feb 3 05:23:22 2007 From: Alessandro.Fachin at gmail.com (Alessandro Fachin) Date: Sat, 03 Feb 2007 11:23:22 +0100 Subject: Create a cookie with cookielib Message-ID: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> Hi, i am trying to forge a new cookie by own with cookielib. But i don't still have success. This a simply code: import cookielib, urllib, urllib2 login = 'Ia am a cookie!' cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) values = {'user':login} data = urllib.urlencode(values) request = urllib2.Request("http://localhost/cookie.php", data) url = urlOpener.open(request) print url.info() page = url.read(500000) print page print cookiejar the output of this is: Date: Sat, 03 Feb 2007 10:20:05 GMT Server: Apache X-Powered-By: PHP/5.1.6 Set-Cookie: user=Alex+Porter; expires=Sat, 03-Feb-2007 11:20:05 GMT Content-Length: 11 Connection: close Content-Type: text/html; charset=UTF-8 Array ( ) ]> And here is the code of cookie.php that i've create for this example: if anyone could help... Thank you From dickey at saltmine.radix.net Wed Feb 28 16:01:43 2007 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Wed, 28 Feb 2007 21:01:43 -0000 Subject: Curses and resizing windows References: Message-ID: <12ubrdnt1msnd36@corp.supernews.com> Nick ! wrote: > http://web.cs.mun.ca/~rod/ncurses/ncurses.html#xterm says "The ncurses > library does not catch [the SIGWINCH aka resizing] signal, because it > cannot in general know how you want the screen re-painted". First, is > this really true? When I make my xterms smaller they clip what is no - given that particular url is a file dating from 1995, it's something that I overlooked in making corrections here: http://invisible-island.net/ncurses/ncurses-intro.html But also note where I link it from: http://invisible-island.net/ncurses/ncurses.faq.html#additional_reading > displayed--is that a function of curses or the xterm? both - xterm sends the signal, and curses receives it. > Second, if true, it explains /what/ is going on--stdscr, only--, but > isn't really satisfactory; it doesn't solve the original poster's bug. > #!/usr/bin/env python > """ > curses_resize.py -> run the program without hooking SIGWINCH > curses_resize.py 1 -> run the program with hooking SIGWINCH > """ > import sys, curses, signal, time > def sigwinch_handler(n, frame): > curses.endwin() > curses.initscr() Actually I'd expect to see curses.refresh() here - but that may be a quirk of the python code. In general, ncurses passes a KEY_RESIZE via the getch() call that the application (such as python) should process. If it's not reading from getch(), ncurses' repainting/resizing won't happen. Also, if you add your own signal handler, ncurses' SIGWINCH catcher won't work. (I'd recommend chaining the signal handlers, but don't know if python supports that ;-). > def main(stdscr): > """just repeatedly redraw a long string to reveal the window boundaries""" > while 1: > stdscr.insstr(0,0,"abcd"*40) > time.sleep(1) > if __name__=='__main__': > if len(sys.argv)==2 and sys.argv[1]=="1": > signal.signal(signal.SIGWINCH, sigwinch_handler) > curses.wrapper(main) -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From rNOSPAMon at flownet.com Fri Feb 2 00:42:31 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 01 Feb 2007 21:42:31 -0800 Subject: Python, readline and OS X References: Message-ID: In article , James Stroud wrote: > Ron Garret wrote: > > In article , > > James Stroud wrote: > > > >>Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib? > > > > > > It wasn't, but changing it so it did didn't fix the problem. (I didn't > > try recompiling Python, just running it. I'll try rebuilding later.) > > You must re-compile python, starting with configure so that configure > can identify the readline libraries. Otherwise it will compile with no > readline, which is your current situation That did the trick. Thanks! rg From pavlovevidence at gmail.com Wed Feb 7 10:37:45 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 7 Feb 2007 07:37:45 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <1170861460.614883.108310@k78g2000cwa.googlegroups.com> References: <45C9A137.8090009@v.loewis.de> <1170861460.614883.108310@k78g2000cwa.googlegroups.com> Message-ID: <1170862664.972024.322260@a75g2000cwd.googlegroups.com> On Feb 7, 10:17 am, "Carl Banks" wrote: > On Feb 7, 8:51 am, Thomas Heller wrote: > > > > > Martin v. L?wis schrieb: > > > > I'm happy to announce partial 1.0; a module to implement > > > partial classes in Python. It is available from > > > >http://cheeseshop.python.org/pypi/partial/1.0 > > > > A partial class is a fragment of a class definition; > > > partial classes allow to spread the definition of > > > a class over several modules. One location serves > > > as the original definition of the class. > > > > To extend a class original_module.FullClass with > > > an additional function, one writes > > > > from partial import * > > > import original_module > > > > class ExtendedClass(partial, original_module.FullClass): > > > def additional_method(self, args): > > > body > > > more_methods > > > > This module is licensed under the Academic Free License v3.0. > > > > Please send comments and feedback to mar... at v.loewis.de > > > Nice idea. > > Indeed. I was going to make a post asking for advice on high-level > delegation (basically you have a generic mostly-OO framework, which > the user extends mostly by subclassing, but how do the generic classes > know about the user-extened classes?). I knew of many solutions, but > all had significant drawbacks. But this seems like it'd work great, > maybe with a few minor inconveniences but nothing like the icky hacks > I've been using. > > Ironic, since I myself posted a very simple example of how to do this > with a class hook here on c.l.python a while back. And looking back at that post, I said that using such a hack would be "truly evil". To every thing there is a season.... Carl Banks From tiedon_jano at hotmail.com Thu Feb 8 13:14:37 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 08 Feb 2007 18:14:37 GMT Subject: Fwd: Python new user question - file writeline error In-Reply-To: References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <1170887579.160693.78160@a34g2000cwb.googlegroups.com> <813A863A-3D95-47B5-8E54-B6DDF5A57DF5@Milochik.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> Message-ID: Shawn Milo kirjoitti: > To the list: > > I have come up with something that's working fine. However, I'm fairly > new to Python, so I'd really appreciate any suggestions on how this > can be made more Pythonic. > > Thanks, > Shawn > > > > > > > Okay, here's what I have come up with: What follows may feel harsh but you asked for it ;) > > > #! /usr/bin/python > > import sys > import re > > month > ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > > infile=file('TVA-0316','r') > outfile=file('tmp.out','w') > > def formatDatePart(x): > "take a number and transform it into a two-character string, > zero padded" If a comment or doc string is misleading one would be better off without it entirely: "take a number": the function can in fact take (at least) any base type "transform it": the function doesn't transform x to anything although the name of the variable x is the same as the argument x "two-character string": to a string of at least 2 chars "zero padded": where left/right??? > x = str(x) > while len(x) < 2: > x = "0" + x You don't need loops for these kind of things. One possibility is to replace the whole body with: return str(x).zfill(2) > return x > > regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") > > for line in infile: > matches = regex.findall(line) > for someDate in matches: > Empty lines are supposed to make code more readable. The above empty line does the contrary by separating the block controlled by the for and the for statement > dayNum = formatDatePart(someDate[1:3]) > monthNum = formatDatePart(month[someDate[4:7]]) > yearNum = formatDatePart(someDate[8:12]) You don't need the formatDatePart function at all: newDate = ",%4s-%02d-%2s," % \ (someDate[8:12],month[someDate[4:7]],someDate[1:3]) > > newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) > line = line.replace(someDate, newDate) > > outfile.writelines(line) > > infile.close > outfile.close You have not read the answers given to the OP, have you. Because if you had, your code would be: infile.close() outfile.close() The reason your version seems to be working, is that you probably execute your code from the command-line and exiting from Python to command-line closes the files, even if you don't. Cheers, Jussi From paul at boddie.org.uk Sat Feb 3 19:28:06 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Feb 2007 16:28:06 -0800 Subject: Python does not play well with others In-Reply-To: <7xodob2q7c.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> Message-ID: <1170548886.842563.121630@v33g2000cwv.googlegroups.com> Paul Rubin wrote: > Ben Finney writes: > > > Since Python is being touted as good for web apps as a competitor to > > > PHP > > > > Python is being touted as a good language for *many* purposes, not > > just web applications. Python is also a "competitor" to Java, to Ruby, > > to Perl, to many other languages. They all have strengths and > > weaknesses. > > Yes but in the cases where Python's weakness compared with one of > those other languages is lack of library functionality, if Python can > remedy the weakness by incorporating similar functionality into its > library it should do so. Python should only incorporate functionality in order to offer a coherent experience (where the omission of functionality would otherwise lead to a flawed experience). For example, having support for SSL in the socket module offers a coherent experience because it means that urllib and related modules can offer to support SSL-related URLs out of the box. That said, there's probably a case for better library design and having things like SSL-related "protocol handlers" be available as plugins, detected and integrated in some kind of framework, although this would bring in configuration issues of its own. [...] > > > I'm paying the hosting company for access to a computer that's > > > connected to electricity and to the internet and which has a > > > straightforward OS, language package, web server, and db installed. > > > > In which case, there should be no problem with *you* installing > > whatever software you need to use the system for what you want. > > No. That would be colo or something similar , where I'm basically > paying for bare metal plus electricity and network, and I'm completely > in charge of the software. Or a virtual private server. > Web hosting means the ISP is in charge of all the software except for my application (i.e. they handle the OS, > language package, web server, and db, as described above). So they > run (typically) Linux, MySQL, Apache, and PHP; and I get to upload my > own PHP apps and use the PHP library. That's a lot less work for me > since I don't have to stay on top of kernel patches or firewall > configuration, and it's cheaper because they host a bazillion sites > (virtual hosts) in a a single server instance. That's known as "shared hosting" these days, I believe. The advantage of shared hosting is arguably convenience for everyone concerned: the provider has a static configuration; the users have the stability of a managed system. However, this only works for people whose needs are met with that configuration, obviously. The big thing for people wanting decent Python support in shared hosting environments (aside from complaints about process isolation) is whether it's easy or obvious enough for providers to make configurations that Python people would actually use. Probably the biggest inhibitor, as far as I can see, has been the server technology chosen. Many hosting providers have historically offered no better than CGI for Python, whilst PHP runs within Apache itself, and it has previously been stated that mod_python has been undesirable with regard to isolating processes from each other. Consequently, a number of Python people seem to have held out for other "high performance" solutions, which various companies now offer. > > > They shouldn't have to deal with dozens of interdependent modules > > > downloaded from different places just to support one language. > > > > Either they are providing far more than the minimal set you describe > > above, or this is entirely outside their domain. Make up your mind. > > No it's you who's got it wrong, I just described above what they're > doing. Do you actually use any services like this? If a hosting provider claims Python and MySQL support, then I'd hope that they have worked out that the MySQLdb package glues the two together. Perhaps better information is necessary for those hosting companies who haven't worked such things out: you'd have a metapackage for stuff like this in certain distributions. > > You can't claim both that the hosting company should have to maintain > > a comprehensive set of functionality, *and* that they should not have to. > > They should get a distro that includes a lot of stuff, type "make", > and all the stuff becomes available to their users. So, for the less forward-thinking providers a metapackage would be the solution, then? Paul From m_tayseer82 at yahoo.com Wed Feb 21 05:33:53 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Wed, 21 Feb 2007 02:33:53 -0800 (PST) Subject: outlook bar like widget In-Reply-To: Message-ID: <829253.83406.qm@web31107.mail.mud.yahoo.com> I implemented this module using Tkinter --------------------------- from Tkinter import * class OutlookBar(Frame): def __init__(self, *args, **options): Frame.__init__(self, *args, **options) self.panes = {} def add_pane(self, name, pane): self.panes[name] = pane pane.pack(side=TOP, fill=X) def get_frame(self, name): return self.panes[name] class OutlookPane(Frame): def __init__(self, *args, **options): if options.get('text'): text = options['text'] del options['text'] Frame.__init__(self, *args, **options) self.btn = Button(self, text=text, command=self.toggle_collapse) self.btn.pack(side=TOP, fill=X) self.child_frame = Frame(self) self.child_frame.pack(side=TOP, fill=X) if options.get('collapsed'): self.collapsed = True del options['collapsed'] else: self.collapsed = False self.child_frame.pack(side=TOP, fill=X) def frame(self): return self.child_frame def toggle_collapse(self): if self.collapsed: self.child_frame.pack(side=TOP) # show else: self.child_frame.pack_forget() self.collapsed = not self.collapsed def add_widget(self, widget): widget.pack(side=TOP) if __name__ == '__main__': #import bwidget as bw root = Tk() root.title('Outlook Bar Demo') bar = OutlookBar(root) bar.pack(expand=1, fill=BOTH) bar.add_pane('pane1', OutlookPane(bar, text='Hello')) pane1 = bar.get_frame('pane1') pane1.add_widget(Button(pane1.frame(), text='Button 1')) pane1.add_widget(Button(pane1.frame(), text='Button 2')) pane1.add_widget(Button(pane1.frame(), text='Button 3')) bar.add_pane('pane2', OutlookPane(bar, text='Zankalon')) pane2 = bar.get_frame('pane2') pane2.add_widget(Button(pane2.frame(), text='Button 1')) pane2.add_widget(Button(pane2.frame(), text='Button 2')) pane2.add_widget(Button(pane2.frame(), text='Button 3')) mainloop() ------------------------- Jaime Casanova wrote: Hi, i'm trying to make an outlook bar like widget basically buttons that when pressed extends to lists... any idea where to start? -- regards, Jaime Casanova --------------------------------- Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Thu Feb 1 00:40:13 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 31 Jan 2007 21:40:13 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170275061.786779.74910@a34g2000cwb.googlegroups.com> References: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> <1170271023.955808.314010@q2g2000cwa.googlegroups.com> <1170275061.786779.74910@a34g2000cwb.googlegroups.com> Message-ID: <1170308413.750283.80070@j27g2000cwj.googlegroups.com> On Jan 31, 9:24 pm, "Carl Banks" wrote: > Well, of all the things you can use threads for, this is probably the > simplest, so I don't see any reason to prefer asynchronous method > unless you're used to it. Well, actually there is a reason why I prefer the asynchronous approach even for the simplest things: I can stop my program at any time with CTRL-C. When developing a threaded program, or I implement a mechanism for stopping the threads (which should be safe enough to survive the bugs introduced while I develop, BTW), or I have to resort to kill -9, and I *hate* that. Especially since kill -9 does not honor try .. finally statements. In short, I prefer to avoid threads, *especially* for the simplest things. I use threads only when I am forced to, typically when I am using a multithreaded framework interacting with a database. Michele Simionato From silovana.vjeverica at com.gmail Sat Feb 3 11:38:34 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Sat, 3 Feb 2007 17:38:34 +0100 Subject: Jython References: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> Message-ID: gregturn at mindspring.com wrote: > Files aren't lists and thus don't have the functions for iteration. > > Try: > > def go(): > for line in open("bobo.txt", "r").readlines(): > print line > > go() For example, you can do even this: import sys for line in sys.stdin: print line, python FileReader.py < bobo.tx 'import site' failed; use -v for traceback boris ozegovic vedran ozegovic -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" From anthra.norell at vtxmail.ch Sat Feb 3 07:37:45 2007 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sat, 03 Feb 2007 13:37:45 +0100 Subject: Find and replace in a file with regular expression In-Reply-To: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> References: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> Message-ID: <45C48219.4020309@vtxmail.ch> TOXiC wrote: > Hi everyone, > First I say that I serched and tryed everything but I cannot figure > out how I can do it. > I want to open a a file (not necessary a txt) and find and replace a > string. > I can do it with: > > import fileinput, string, sys > fileQuery = "Text.txt" > sourceText = '''SOURCE''' > replaceText = '''REPLACE''' > def replace(fileName, sourceText, replaceText): > > file = open(fileName, "r") > text = file.read() #Reads the file and assigns the value to a > variable > file.close() #Closes the file (read session) > file = open(fileName, "w") > file.write(text.replace(sourceText, replaceText)) > file.close() #Closes the file (write session) > print "All went well, the modifications are done" > > replacemachine(fileQuery, sourceText, replaceText) > > Now all went ok but I'm wondering if it's possible to replace text if / > sourceText/ match a regex. > Help me please! > Thx in advance > > Try this: >>> import SE # from http://cheeseshop.python.org/pypi/SE/2.3 >>> replacements = 'SOURCE=REPLACE "another source=another replace" ~[0-9]+~=>>int<< ~[0-9]+\\.[0-9]+~=>>float<< ~' # Define as many replacements as you like. Identify regexes placing them between '~' >>> Stream_Editor = SE.SE (replacements) >>> Stream_Editor (input_file, output_file) That's it. PS 1: Your Stream_Editor accepts strings as well as file names and then returns a string by default. This is a great help for developing substitution sets interactively. >>> print Stream_Editor (''' If it works, this SOURCE should read REPLACE and another source should become another replace and this 123456789 should become >>int<< and this 12345.6789 is a float and so should read >>float<<.''') If it works, this REPLACE should read REPLACE and another replace should become another replace and this >>int<< should become >>int<< and this >>float<< is a float and so should read >>float<<. PS 2: It is convenient to keep large and frequently used substitution sets in text files. The SE constructor accepts a file name instead of the replacements string: >>> Stream_Edtor = SE.SE ('path/replacement_definitions_file') Regards Frederic From Bulkan at gmail.com Sun Feb 18 22:08:45 2007 From: Bulkan at gmail.com (placid) Date: 18 Feb 2007 19:08:45 -0800 Subject: cmd all commands method? In-Reply-To: <1171792793.211346.163520@p10g2000cwp.googlegroups.com> References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> <53per7F1t12jjU1@mid.individual.net> <1171786661.599128.234300@k78g2000cwa.googlegroups.com> <1171792183.564570.307940@m58g2000cwm.googlegroups.com> <1171792793.211346.163520@p10g2000cwp.googlegroups.com> Message-ID: <1171854525.360276.178080@l53g2000cwa.googlegroups.com> On Feb 18, 8:59 pm, "Michele Simionato" wrote: > On Feb 18, 10:49 am, "placid" wrote: > > > On Feb 18, 7:17 pm, "Michele Simionato" > > > > Yes, he is talking about the cmd module:http://docs.python.org/dev/lib/Cmd-objects.html. > > > However that module was never intended as a real interpreter, so > > > defining variables > > > as the OP wants would require some work. > > > > Michele Simionato > > > How much work does it require ? > > Have you ever written an interpreter? It is a nontrivial job. > > Michele Simionato No i have never written an interpreter and i can just imagine how much work/effort is needed to write something like that. If anyone can provide a suggestion to replicate the following Tcl command in Python, i would greatly appreciate it. namespace eval foo { variable bar 12345 } what this does is create a namespace foo with the variable bar set to 12345. http://aspn.activestate.com/ASPN/docs/ActiveTcl/8.4/tcl/TclCmd/variable.htm The code provided by Peter Otten is a good start for me. Cheers for that! Cheers From naima.mans at gmail.com Wed Feb 28 04:51:00 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 28 Feb 2007 01:51:00 -0800 Subject: spawnl and waitpid In-Reply-To: <1172654033.173702.248160@h3g2000cwc.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> <1172654033.173702.248160@h3g2000cwc.googlegroups.com> Message-ID: <1172656260.222943.127950@j27g2000cwj.googlegroups.com> On 28 f?v, 10:13, naima.m... at gmail.com wrote: > On 27 f?v, 19:31, Dennis Lee Bieber wrote: > > > > > > > On 27 Feb 2007 05:39:51 -0800, naima.m... at gmail.com declaimed the > > following in comp.lang.python: > > > > On 27 f?v, 12:27, Thinker wrote: > > > > -----BEGIN PGP SIGNED MESSAGE----- > > > > > > > Your program will be blocked here until child process being terminated. > > > > You should print your messages before this line. > > > > i have tried as you said (cf bellow) and same result... > > > No, you did NOT do as was suggested (unless you misunderstood which > > line "before this" meant. > > > > is there any link which explain how a server Web read script and send > > > the answer ? > > > > ------------------------------------------------------------------------- > > > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > > > \python.exe","python","Main.py") > > > ret = os.waitpid(pid,0) > > > As soon as you execute os.waitpid(), your script WAITS. NOTHING > > after that point will happen until the process you are waiting on exits. > > > > print """please wait ....""" > > > sys.stdout.flush() > > > # retourne le process id > > > if ( ret[1] != 0): > > > print """ wait %i """ %ret[1] > > > sys.stdout.flush() > > > else: > > > print """ end %i """ %ret[1] > > > sys.stdout.flush() > > > pid = os.spawnl(os.P_NOWAIT, > > "c:\\python25\\python.exe", > > "python", > > "Main.py") #apparently a Windows OS > > print "Please wait ..." > > sys.stdout.flush() > > ret = os.waitpid(pid, 0) > > > if ret[1]: > > print "Non-zero exit code: %s %s" % (ret[1], ret[0]) > > else: > > print "Successful exit" > > sys.stdout.flush() > > > {I'm presuming a 0 return code means success... VMS used 1 for success > > and 0 for failure [actually, odd numbers were informational status, even > > numbers were error status]} > > > > --------------------------------------------------------------------------- > > > thanks > > > -- > > Wulfraed Dennis Lee Bieber KD6MOG > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > HTTP://www.bestiaria.com/ > > hello > > thanks a lot.. > > sorry for misunderstanding, my english isn't good (i'm french). > > i have tried like this: > ---------------------------------------------- > #! C:/Python25/python.exe > # -*- coding: cp1252 -*- > > import cgitb; cgitb.enable() > import os,sys > > print "Content-Type: text/html" > print > > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > \python.exe","python","Main.py") > print "please wait.." > sys.stdout.flush() > ret = os.waitpid(pid,0) > # retourne le process id > if ret[1]: > print "Non-zero exit code: %s %s" % (ret[1], ret[0]) > else: > print "Successful exit" > sys.stdout.flush() > -------------------------------------------------------- > > and the result: > > At the end of the script execution it write: > ==>>>> please wait.. Successful exit > > The browser doesn't let the script executing on background to write > the message at once.. it waits the end. > > what happend?- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - re hello perhaps there is a link with the script being called.. as there is a function which use stdout: here it is -------------------------------------------- def erreur_ccm(cmd): try: child_stdin, child_stdout, child_stderr =os.popen3(cmd) stderr=child_stderr.read() stdout=child_stdout.read() if stderr == "": retour = stdout else : retour = 0 except OSError, e: child_stdin.close() child_stdout.close() child_stderr.close() return retour ---------------------------------------------- From jeffrey.aylesworth at gmail.com Tue Feb 27 19:10:21 2007 From: jeffrey.aylesworth at gmail.com (jeff) Date: 27 Feb 2007 16:10:21 -0800 Subject: how to convert an integer to a float? In-Reply-To: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Message-ID: <1172621421.575779.206090@k78g2000cwa.googlegroups.com> On Feb 27, 7:05 pm, "ying... at gmail.com" wrote: > Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, > i1)' always return 0, can you please tell me how can i convert it from > an integer to float? > > def compareValue(n1, n2): > i1 = int(n1) > i2 = int(n2) > > dx = abs(i2 - i1)/min(i2, i1) > print dx > return dx < 0.05 x = x + 0.0 From _karlo_ at _mosor.net_ Mon Feb 19 13:05:59 2007 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Mon, 19 Feb 2007 18:05:59 +0000 (UTC) Subject: What is more efficient? References: Message-ID: "Gabriel Genellina" wrote in news:mailman.4184.1171862407.32031.python-list at python.org: > It doesn't matter whether you have 0 or a million instances, > methods do not occupy more memory. That's what I was looking for! Thanks, to you and all the others. -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From grante at visi.com Thu Feb 8 17:17:57 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Feb 2007 22:17:57 -0000 Subject: Newbie Question References: Message-ID: <12sn8clg5iqlp81@corp.supernews.com> On 2007-02-08, Reid wrote: > I am just starting to play with programing again as a hobby. I have heard > good things about python. I have not really looked into the language much. > My question is, will python make programs with a gui under windows xp. Yes. There are a number of GUI toolkits for python that will work with Windows. Some of the more common ones are listed at http://www.python.org/about/apps/ under the "Desktop GUIs" section. -- Grant Edwards grante Yow! Someone is DROOLING at on my collar!! visi.com From samckain at southslope.net Wed Feb 14 12:12:31 2007 From: samckain at southslope.net (Steve) Date: Wed, 14 Feb 2007 11:12:31 -0600 Subject: list of range of floats Message-ID: I'm trying to create a list range of floats and running into problems. I've been trying something like: a = 0.0 b = 10.0 flts = range(a, b) fltlst.append(flts) When I run it I get the following DeprecationWarning: integer argument expected, got float. How can I store a list of floats? TIA Steve From gagsl-py2 at yahoo.com.ar Wed Feb 28 20:46:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Feb 2007 22:46:29 -0300 Subject: newbie question(file-delete trailing comma) References: <45E54D7A.8060203@isy.liu.se> <787921.87592.qm@web7806.mail.in.yahoo.com> Message-ID: En Wed, 28 Feb 2007 08:34:29 -0300, kavitha thankaian escribi?: > thanks,, > now i have one more problem,,, > the strings should be seperated in an order,,, > some={1:'a', 2:7, 3:'c', 4:'d'} > i need the output to be a,c,d,7 > before my code was: > field_order = [1,3,4,2] > for field in field_order: > f.writelines('\"%s\",' % someprt[field] ) > do you have an idea now how should it look like??? Proceed in small steps. First get the data you need to write, then, format them and build a single line, then write the new line onto the file. some = {1:'a', 2:7, 3:'c', 4:'d'} # i need the output to be a,c,d,7 field_order = [1,3,4,2] row = [] for field in field_order: row.append(some[field]) # row contains ['a', 'c', 'd', 7] # convert to string row = ['%s' % item for item in row] ### alternative: convert to string, with "" around each value ##row = ['"%s"' % item for item in row] # make a single line, using "," as separator line = ','.join(row) # write to file f.write('%s\n' % line) -- Gabriel Genellina From rasmussen.bryan at gmail.com Sun Feb 18 05:04:27 2007 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Sun, 18 Feb 2007 11:04:27 +0100 Subject: string.find returns -1 when string evidently in source file Message-ID: <3bb44c6e0702180204p4d2ddd93s61c46eecc125377f@mail.gmail.com> hi, the following is returning -1: import string import sys x = open("latvian.txt",'r') x1 = x.read() print x1.find("LAYOUT") --- given a file like this KBD Layout01 "Latvian (QWERTY) (Custom)" COPYRIGHT "(c) 2007 IG" COMPANY "IG" LOCALEID "00000426" VERSION 1.0 SHIFTSTATE 0 //Column 4 1 //Column 5 : Shft 2 //Column 6 : Ctrl 6 //Column 7 : Ctrl Alt 7 //Column 8 : Shft Ctrl Alt LAYOUT ;an extra '@' at the end is a dead key //SC VK_ Cap 0 1 2 6 7 //-- ---- ---- ---- ---- ---- ---- ---- 02 1 0 1 0021 -1 00a0 -1 // DIGIT ONE, EXCLAMATION MARK, , NO-BREAK SPACE, 03 2 0 2 0040 -1 00ab -1 // DIGIT TWO, COMMERCIAL AT, , LEFT-POINTING DOUBLE ANGLE QUOTATION MARK *, 04 3 0 3 0023 -1 00bb -1 // DIGIT THREE, NUMBER SIGN, , RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK *, 05 4 0 4 0024 -1 20ac 00a7 // DIGIT FOUR, DOLLAR SIGN, , EURO SIGN, SECTION SIGN 06 5 0 5 0025 -1 -1 00b0 // DIGIT FIVE, PERCENT SIGN, , , DEGREE SIGN 07 6 0 6 005e -1 2019 -1 // DIGIT SIX, CIRCUMFLEX ACCENT, , RIGHT SINGLE QUOTATION MARK, 08 7 0 7 0026 -1 -1 00b1 // DIGIT SEVEN, AMPERSAND, , , PLUS-MINUS SIGN 09 8 0 8 002a -1 -1 00d7 // DIGIT EIGHT, ASTERISK, , , MULTIPLICATION SIGN 0a 9 0 9 0028 -1 -1 -1 // DIGIT NINE, LEFT PARENTHESIS, , , 0b 0 0 0 0029 -1 -1 -1 // DIGIT ZERO, RIGHT PARENTHESIS, , , 0c OEM_MINUS 0 002d 005f -1 2013 2014 // HYPHEN-MINUS, LOW LINE, , EN DASH, EM DASH 0d OEM_PLUS 0 003d 002b -1 -1 -1 // EQUALS SIGN, PLUS SIGN, , , 10 Q 1 q Q -1 -1 -1 // LATIN SMALL LETTER Q, LATIN CAPITAL LETTER Q, , , 11 W 1 w W -1 -1 -1 // LATIN SMALL LETTER W, LATIN CAPITAL LETTER W, , , 12 E 1 e E -1 0113 0112 // LATIN SMALL LETTER E, LATIN CAPITAL LETTER E, , LATIN SMALL LETTER E WITH MACRON, LATIN CAPITAL LETTER E WITH MACRON 13 R 1 r R -1 0157 0156 // LATIN SMALL LETTER R, LATIN CAPITAL LETTER R, , LATIN SMALL LETTER R WITH CEDILLA, LATIN CAPITAL LETTER R WITH CEDILLA 14 T 1 t T -1 -1 -1 // LATIN SMALL LETTER T, LATIN CAPITAL LETTER T, , , 15 Y 1 y Y -1 -1 -1 // LATIN SMALL LETTER Y, LATIN CAPITAL LETTER Y, , , 16 U 1 u U -1 016b 016a // LATIN SMALL LETTER U, LATIN CAPITAL LETTER U, , LATIN SMALL LETTER U WITH MACRON, LATIN CAPITAL LETTER U WITH MACRON 17 I 1 i I -1 012b 012a // LATIN SMALL LETTER I, LATIN CAPITAL LETTER I, , LATIN SMALL LETTER I WITH MACRON, LATIN CAPITAL LETTER I WITH MACRON 18 O 1 o O -1 00f5 00d5 // LATIN SMALL LETTER O, LATIN CAPITAL LETTER O, , LATIN SMALL LETTER O WITH TILDE, LATIN CAPITAL LETTER O WITH TILDE 19 P 1 p P -1 -1 -1 // LATIN SMALL LETTER P, LATIN CAPITAL LETTER P, , , 1a OEM_4 0 005b 007b -1 -1 -1 // LEFT SQUARE BRACKET, LEFT CURLY BRACKET, , , 1b OEM_6 0 005d 007d -1 -1 -1 // RIGHT SQUARE BRACKET, RIGHT CURLY BRACKET, , , 1e A 1 a A -1 0101 0100 // LATIN SMALL LETTER A, LATIN CAPITAL LETTER A, , LATIN SMALL LETTER A WITH MACRON, LATIN CAPITAL LETTER A WITH MACRON 1f S 1 s S -1 0161 0160 // LATIN SMALL LETTER S, LATIN CAPITAL LETTER S, , LATIN SMALL LETTER S WITH CARON, LATIN CAPITAL LETTER S WITH CARON 20 D 1 d D -1 -1 -1 // LATIN SMALL LETTER D, LATIN CAPITAL LETTER D, , , 21 F 1 f F -1 -1 -1 // LATIN SMALL LETTER F, LATIN CAPITAL LETTER F, , , 22 G 1 g G -1 0123 0122 // LATIN SMALL LETTER G, LATIN CAPITAL LETTER G, , LATIN SMALL LETTER G WITH CEDILLA, LATIN CAPITAL LETTER G WITH CEDILLA 23 H 1 h H -1 -1 -1 // LATIN SMALL LETTER H, LATIN CAPITAL LETTER H, , , 24 J 1 j J -1 -1 -1 // LATIN SMALL LETTER J, LATIN CAPITAL LETTER J, , , 25 K 1 k K -1 0137 0136 // LATIN SMALL LETTER K, LATIN CAPITAL LETTER K, , LATIN SMALL LETTER K WITH CEDILLA, LATIN CAPITAL LETTER K WITH CEDILLA 26 L 1 l L -1 013c 013b // LATIN SMALL LETTER L, LATIN CAPITAL LETTER L, , LATIN SMALL LETTER L WITH CEDILLA, LATIN CAPITAL LETTER L WITH CEDILLA 27 OEM_1 0 003b 003a -1 -1 -1 // SEMICOLON, COLON, , , 28 OEM_7 0 0027 0022 -1 00b4@ 00a8@ // APOSTROPHE, QUOTATION MARK, , ACUTE ACCENT, DIAERESIS 29 OEM_3 0 0060 007e@ -1 00ad -1 // GRAVE ACCENT, TILDE, , SOFT HYPHEN, 2b OEM_5 0 00b0@ 007c -1 -1 -1 // DEGREE SIGN, VERTICAL LINE, , , 2c Z 1 z Z -1 017e 017d // LATIN SMALL LETTER Z, LATIN CAPITAL LETTER Z, , LATIN SMALL LETTER Z WITH CARON, LATIN CAPITAL LETTER Z WITH CARON 2d X 1 x X -1 -1 -1 // LATIN SMALL LETTER X, LATIN CAPITAL LETTER X, , , 2e C 1 c C -1 010d 010c // LATIN SMALL LETTER C, LATIN CAPITAL LETTER C, , LATIN SMALL LETTER C WITH CARON, LATIN CAPITAL LETTER C WITH CARON 2f V 1 v V -1 -1 -1 // LATIN SMALL LETTER V, LATIN CAPITAL LETTER V, , , 30 B 1 b B -1 -1 -1 // LATIN SMALL LETTER B, LATIN CAPITAL LETTER B, , , 31 N 1 n N -1 0146 0145 // LATIN SMALL LETTER N, LATIN CAPITAL LETTER N, , LATIN SMALL LETTER N WITH CEDILLA, LATIN CAPITAL LETTER N WITH CEDILLA 32 M 1 m M -1 -1 -1 // LATIN SMALL LETTER M, LATIN CAPITAL LETTER M, , , 33 OEM_COMMA 0 002c 003c -1 -1 -1 // COMMA, LESS-THAN SIGN, , , 34 OEM_PERIOD 0 002e 003e -1 -1 -1 // FULL STOP, GREATER-THAN SIGN, , , 35 OEM_2 0 002f 003f -1 -1 -1 // SOLIDUS, QUESTION MARK, , , 39 SPACE 0 0020 0020 0020 -1 -1 // SPACE, SPACE, SPACE, , 56 OEM_102 0 005c 007c -1 -1 -1 // REVERSE SOLIDUS, VERTICAL LINE, , , 53 DECIMAL 0 002e 002e -1 -1 -1 // FULL STOP, FULL STOP, , , DEADKEY 00b4 006e 0144 // n -> ? 0063 0107 // c -> ? 007a 017a // z -> ? 0073 015b // s -> ? 0065 00e9 // e -> ? 006f 00f3 // o -> ? 004e 0143 // N -> ? 0043 0106 // C -> ? 005a 0179 // Z -> ? 0053 015a // S -> ? 0045 00c9 // E -> ? 004f 00d3 // O -> ? 0020 00b4 // -> ? DEADKEY 00a8 0061 00e4 // a -> ? 0075 00fc // u -> ? 006f 00f6 // o -> ? 0041 00c4 // A -> ? 0055 00dc // U -> ? 004f 00d6 // O -> ? 0020 00a8 // -> ? DEADKEY 007e 006f 00f5 // o -> ? 004f 00d5 // O -> ? 0020 007e // -> ~ DEADKEY 00b0 007a 017c // z -> ? 0061 00e5 // a -> ? 0067 0121 // g -> ? 0065 0117 // e -> ? 005a 017b // Z -> ? 0041 00c5 // A -> ? 0045 0116 // E -> ? 0020 00b0 // -> ? KEYNAME 01 Esc 0e Backspace 0f Tab 1c Enter 1d Ctrl 2a Shift 36 "Right Shift" 37 "Num *" 38 Alt 39 Space 3a "Caps Lock" 3b F1 3c F2 3d F3 3e F4 3f F5 40 F6 41 F7 42 F8 43 F9 44 F10 45 Pause 46 "Scroll Lock" 47 "Num 7" 48 "Num 8" 49 "Num 9" 4a "Num -" 4b "Num 4" 4c "Num 5" 4d "Num 6" 4e "Num +" 4f "Num 1" 50 "Num 2" 51 "Num 3" 52 "Num 0" 53 "Num Del" 54 "Sys Req" 57 F11 58 F12 7c F13 7d F14 7e F15 7f F16 80 F17 81 F18 82 F19 83 F20 84 F21 85 F22 86 F23 87 F24 KEYNAME_EXT 1c "Num Enter" 1d "Right Ctrl" 35 "Num /" 37 "Prnt Scrn" 38 "Right Alt" 45 "Num Lock" 46 Break 47 Home 48 Up 49 "Page Up" 4b Left 4d Right 4f End 50 Down 51 "Page Down" 52 Insert 53 Delete 54 <00> 56 Help 5b "Left Windows" 5c "Right Windows" 5d Application KEYNAME_DEAD 00b4 "ACUTE ACCENT" 00a8 "DIAERESIS" 007e "TILDE" 00b0 "DEGREE SIGN" ENDKBD the encoding of the file is Unicode, I am able to return instances of individual characters but not whole words. Cheers, Bryan Rasmussen From ososa at estudiantes.uci.cu Sun Feb 18 23:13:48 2007 From: ososa at estudiantes.uci.cu (Oliver Sosa Cano) Date: Sun, 18 Feb 2007 23:13:48 -0500 Subject: I need a crack for pyext1.2.5 plugin References: <1171853809.836540.157490@l53g2000cwa.googlegroups.com> Message-ID: Sorry if this is the wrong place to make that question. Pyext is a plugin that acoplate with pydev, it's 'software privativo' like said Stallman, but it's very interesting. I have version 1.2.5. I use Eclipse 'cos it's simply great!! If somebody could tell me some alternative... Thanks (sorry my english) On Feb 18, 8:07 pm, "Oliver Sosa Cano" wrote: > Hi pythoneros. I'm a cuban guy interested in python and I need the crack of an Eclipse plugin: pyext 1.2.5 > > Thanks very much > > cheers > > Oliver Sosa Never heard of pyext - Google turns up this link http://grrrr.org/ext/py/, but this is pyext 0.2.0. If by "crack" you mean "bootlegged user key for commercial software," this is the wrong place for that stuff. On the other hand, if you tell us what kind of Eclipse work you are doing that requires this elusive plug-in, someone may have a suggestion on where to find it, or an equivalent. -- Paul -- http://mail.python.org/mailman/listinfo/python-list From jura.grozni at gmail.com Wed Feb 7 16:32:13 2007 From: jura.grozni at gmail.com (azrael) Date: 7 Feb 2007 13:32:13 -0800 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: References: Message-ID: <1170883933.480967.53500@v33g2000cwv.googlegroups.com> On Feb 7, 3:13 am, "fdu.xia... at gmail.com" wrote: > Hi all, > > I'm interested in Parallel Python and I learned from the website of > Parallel Python > that it can run on SMP and clusters. But can it run on a our muti-CPU > server ? > We are running an origin3800 server with 128 CPUs. > > Thanks. I see you got a problem. me to. how can i get such a little toy for my own and how much do i have to spend on it. i also want sometjing like thi. 128 cpu-s, 64 GB rainbowtables, oh my god. i want this. i am very close to have an orgasm. From rscottco at gmail.com Wed Feb 21 23:40:47 2007 From: rscottco at gmail.com (rscottco at gmail.com) Date: 21 Feb 2007 20:40:47 -0800 Subject: Looking for contract developer(s) - where can I find them? Message-ID: <1172119247.350545.73480@h3g2000cwc.googlegroups.com> Hi, I've just sent a job listing to python.org, but am also trying to proactively find python developers through other means. python.org and guru.com notwithstanding, most job-sites to seem only support people/organizations looking for full/part-time employment or with full-time/part-time positions instead of work-for-hire. I require the latter, and in the very near future (days). I'm not looking for an employee as I cannot guarantee long-term work, though much of what is available is fairly consistent (on the board is a 4-week job, followed by another 6-week one). If anyone has ideas where I might find talented individuals and small companies offering (reasonably-priced i.e. not $125/hr like a local firm charges) python services, I'd be most appreciative. We are developing and extending a couple of projects previously developed for clients and replacing a 5-year-old Zope site, all with django, PostgreSQL etc. The work is immediately available for an experienced, self-motivated python web-application programmer. For those on this list that might be interested, I'm looking for self- motivated developers with excellent python skills and if possible experience with django (along with CVS/Subversion, PostgreSQL, SSH, vi/ emacs and other open-source projects & tools). Zope experience would be handy too as one job is to replace an old site with a spanky-new django one. Good communication and organizational skills are important. Documentation & commenting are also very important along with the ability to work alone and with others. Meeting deadlines, consistent development pace and accurate reporting are also key. Finally, having a sense of humor is valuable... as you might find yourself being called Bruce (especially if your name is Ryan, Shawn or Mike... as the other guys workin' for me already have those names. Then again if your name is really Bruce... 8-) I'd prefer someone from Western Canada (the other half of the country would be okay too, I guess), but if necessary will consider talented individuals from North America. Due to time-zone and possible language/ communication issues, off-shore developers are not attractive _at_this_time_ (sorry). Please submit a resume or other description of qualifications along with availability, desired rate and examples of work (i.e. URLs of projects and what you did on them and/or sample code showing _typical_ style of work). Scott From syedmonty at hotmail.com Mon Feb 19 05:20:06 2007 From: syedmonty at hotmail.com (Rohin) Date: 19 Feb 2007 02:20:06 -0800 Subject: Free URL Submission, Forum, Free Ebooks, Articles Message-ID: <1171880406.586290.177590@j27g2000cwj.googlegroups.com> Free URL Submission, Forum, Free Ebooks, Articles. http://www.aonearticles.com. From djbclark at gmail.com Thu Feb 8 13:54:05 2007 From: djbclark at gmail.com (Daniel Clark) Date: 8 Feb 2007 10:54:05 -0800 Subject: [Windows] Sending CTRL-C event to console application Message-ID: <1170960845.457806.27260@p10g2000cwp.googlegroups.com> I have a Windows command line based application that only shuts down cleanly if it sees "CTRL-C" on the console. I need to automate the running of this application, but still allow the user sitting at the machine to cancel the process cleanly if he/she needs to. In Unix this would be a tiny shell script that used "kill -15", but under Windows there does not seem to be an easy way to do this, at least that I can find. Below is a test program, based on CreateProcess.py from "Python Programming on Win32". The win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) lines don't seem to do anything. What they should do is nothing in the case of notepad, and exit out of the dir builtin process in the case of the cmd.exe process. Any ideas on how to make this work? # CreateProcessDc.py # # Demo of creating two processes using the CreateProcess API, # then waiting for the processes to terminate. import win32process import win32event import win32con import win32api import time # Create a process specified by commandLine, and # The process' window should be at position rect # Returns the handle to the new process. def CreateMyProcess(commandLine, rect): # Create a STARTUPINFO object si = win32process.STARTUPINFO() # Set the position in the startup info. si.dwX, si.dwY, si.dwXSize, si.dwYSize = rect # And indicate which of the items are valid. si.dwFlags = win32process.STARTF_USEPOSITION | \ win32process.STARTF_USESIZE # Set Creation Flags CreationFlags = win32process.CREATE_NEW_CONSOLE | \ win32process.CREATE_NEW_PROCESS_GROUP | \ win32process.NORMAL_PRIORITY_CLASS # Rest of startup info is default, so we leave it alone. # Create the process. info = win32process.CreateProcess( None, # AppName commandLine, # Command line None, # Process Security None, # ThreadSecurity 0, # Inherit Handles? CreationFlags, None, # New environment None, # Current directory win32process.STARTUPINFO()) # startup info. ##si) # startup info. # Return the handle to the process. # Recall info is a tuple of (hProcess, hThread, processId, threadId) return (info[0], info[2]) def RunEm(): pids = [] handles = [] # First get the screen size to calculate layout. screenX = win32api.GetSystemMetrics(win32con.SM_CXSCREEN) screenY = win32api.GetSystemMetrics(win32con.SM_CYSCREEN) # First instance will be on the left hand side of the screen. rect = 0, 0, screenX/2, screenY handle, pid = CreateMyProcess("notepad", rect) handles.append(handle) pids.append(pid) # Second instance of Notepad will be on the right hand side. rect = screenX/2+1, 0, screenX/2, screenY cmd2 = "cmd /k dir /s/p c:\\" handle, pid = CreateMyProcess(cmd2, rect) handles.append(handle) pids.append(pid) # Now we have the processes, wait for them both # to terminate. # Rather than waiting the whole time, we loop 10 times, # waiting for one second each time, printing a message # each time around the loop countdown = range(1,10) countdown.reverse() for i in countdown: print "Waiting %d seconds for apps to close" % i rc = win32event.WaitForMultipleObjects( handles, # Objects to wait for. 1, # Wait for them all 1000) # timeout in milli-seconds. if rc == win32event.WAIT_OBJECT_0: # Our processes closed! print "Our processes closed in time." break # else just continue around the loop. else: # We didn't break out of the for loop! print "Giving up waiting - sending CTRL-C to processes" for pid in pids: try: print "Sending CTRL-C to process with pid: " + str(pid) win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) except win32api.error: pass print "Waiting 10 seconds, then going to terminate processes" time.sleep(10) print "Giving up waiting - killing processes" for handle in handles: try: win32process.TerminateProcess(handle, 0) except win32process.error: # This one may have already stopped. pass if __name__=='__main__': RunEm() From arkanes at gmail.com Mon Feb 26 13:44:44 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 26 Feb 2007 12:44:44 -0600 Subject: 2.4->2.5 current directory change? Message-ID: <4866bea60702261044s5670720ejbc3f39315967cde3@mail.gmail.com> This appears to be a change in behavior from Python 2.4 to Python 2.5, which I can't find documented anywhere. It may be windows only, or related to Windows behavior. In 2.4, the current directory (os.curdir) was on sys.path. In 2.5, it appears to be the base directory of the running script. For example, if you execute the file testme.py in your current working directory, '' is on sys.path. If you execute c:\Python25\Scripts\testme.py, '' is *not* on sys.path, and C:\Python25\Scripts is. That means if you run a Python script located in another directory, modules/etc in your current working directory will not be found. This makes .py scripts in the PYTHONHOME\Scripts file moderately useless, because they won't find anything in the current working directory. I first noticed this because it breaks Trial, but I'm sure there are other scripts affected by it. Is this desirable behavior? Is there anything to work around it except by pushing os.curdir onto sys.path? From michael at stroeder.com Fri Feb 2 08:59:25 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 02 Feb 2007 14:59:25 +0100 Subject: LDAP/LDIF Parsing In-Reply-To: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> Message-ID: Cruelemort wrote: > I was wondering the best way to do this? I have installed and used the > python-ldap libraries and these allow me to access and search the > server, but the searches always return a horrible nesting of lists, > tuples and dictionaries, below is an example of returning just one > record - > > ('dc=example,dc=com', {'objectClass': ['top', 'dcObject', > 'organization'], 'dc': ['example'], 'o': ['Example Organisation']}) It's just modeled after the X.500 data model. A DN and the entry. The entry consists of attributes which consists of attribute type and a set of attribute values. You could write your own wrapper class around ldap.ldapobject.LDAPObject and overrule method search_s(). > (there is an ldif library available but > it is not obvious how this works, i cannot see much documentation, and > it seems to be deprecated...). Module ldif is not deprecated. It's actively maintained by me like the rest of python-ldap. It parses LDIF and returns the same data structure as above. You don't need it for LDAP access anyway. Only for reading LDIF files. Ciao, Michael. From haraldarminmassa at gmail.com Fri Feb 2 04:12:32 2007 From: haraldarminmassa at gmail.com (GHUM) Date: 2 Feb 2007 01:12:32 -0800 Subject: win32com.client In-Reply-To: References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170379374.589869.158610@p10g2000cwp.googlegroups.com> <1170379682.386807.99880@a34g2000cwb.googlegroups.com> Message-ID: <1170407552.911824.75510@p10g2000cwp.googlegroups.com> btw... the statement with "youtube" was a joke. I really applaud rzed you for giving this detailed descriptions, people like him make the spirit of c.l.p.: People get help here WAY over what commercial support usually gets you. Thanks for doing that, rzed! best wishes, HArald From nagle at animats.com Sun Feb 25 01:17:01 2007 From: nagle at animats.com (John Nagle) Date: Sun, 25 Feb 2007 06:17:01 GMT Subject: Are weak refs slower than strong refs? Message-ID: Are weak refs slower than strong refs? I've been considering making the "parent" links in BeautifulSoup into weak refs, so the trees will release immediately when they're no longer needed. In general, all links back towards the root of a tree should be weak refs; this breaks the loops that give reference counting trouble. John Nagle From jstroud at mbi.ucla.edu Tue Feb 13 01:04:19 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 12 Feb 2007 22:04:19 -0800 Subject: how to compare... In-Reply-To: References: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: > jairodsl wrote: > >> Hello everybody ! >> >> >> I have two list, they are, S1=['A','B','C','D','E'], and >> S2=['F','G','H','I','J'], but i have to compare both in this way: >> >> A vs J >> A vs I, B vs J >> A vs H, B vs I, C vs J >> A vs G, B vs H, C vs I, D vs J >> A vs F, B vs G, C vs H, D vs I, E vs J >> B vs F, C vs G, D vs H, E vs I >> C vs F, D vs G, E vs H >> D vs F, E vs G >> E vs F >> >> Perhaps, you should understand better in this way: >> >> A >> J >> >> A B >> I J >> >> A B C >> H I J >> >> A B C D >> G H I J >> >> A B C D E >> F G H I J >> >> B C D E >> F G H I >> >> C D E >> F G H >> >> D E >> F G >> >> E >> F >> >> Could someone give me any idea how to compare(or print) both list in >> this way ??? Thanks a lot !!! >> >> jDSL >> > for i in xrange(1, len(S1)+1): > print S1[0:i] > print S2[-i:] > print > > Am I really the first person to respond to this? > I didn't scroll far enough down. From __peter__ at web.de Wed Feb 14 12:56:33 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Feb 2007 18:56:33 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171360113.585827.17440@v45g2000cwv.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2007-02-13, Peter Otten <__peter__ at web.de> wrote: >> Well, what problems ocurring with >> >> class A: pass >> class B: pass >> class C(A, B): pass >> >> could be avoided by writing >> >> class A: pass >> class B(A): pass >> class C(B): pass >> >> instead? > > With multiple inheritance, the choice of algorithm for Method > Resolution Ordering isn't obvious or trivial. As I understand it, > Python got it wrong for quite some time, allowing "bad" > hierarchies to compile, i.e., classes for which the properties of > local precedence ordering and monotonicity did not hold. > > URL:http://www.python.org/download/releases/2.3/mro/ Is it correct that as long as no classes occur twice in the hierarchy no such ambiguities can arise? Peter From jjl at pobox.com Sun Feb 4 14:17:32 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 04 Feb 2007 19:17:32 GMT Subject: Create a cookie with cookielib References: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> <45c59494$0$36013$4fafbaef@reader4.news.tin.it> Message-ID: <87zm7travc.fsf@pobox.com> Alessandro Fachin writes: > Matthew Franz wrote: > > > I'm not sure what you mean be forge, but if you mean set an arbitrary > > cookie manually (vs. one that was provided by the server). just use > > add_header() in http://docs.python.org/lib/request-objects.html > > Yes is exactly what i want to do... i don't known because i looked at No, you don't ;-) > cookielib to set cookie data, cookie are simply http header :) Inserting > values with add_header() or addheaders() it works. Thank you Fine, but see my other post -- I think you misunderstand how cookies work. John From mhellwig at xs4all.nl Wed Feb 7 08:41:40 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 07 Feb 2007 14:41:40 +0100 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: References: <45C935B1.60606@gmail.com> Message-ID: <45c9d6d4$0$329$e4fe514c@news.xs4all.nl> fdu.xiaojf at gmail.com wrote: > fdu.xiaojf at gmail.com wrote: >> Hi all, >> >> I'm interested in Parallel Python and I learned from the website of >> Parallel Python >> that it can run on SMP and clusters. But can it run on a our muti-CPU >> server ? >> We are running an origin3800 server with 128 CPUs. >> >> Thanks. >> > I have tested that at least it could run sum_primes.py on our server. > > But it seems Parallel Python just launch one python process for > each job, and if I let it use 12 CPUs for 8 jobs, Parallel Python > launches 12 python processes, 4 of which just sleep until all 8 jobs > are done. I've just downloaded it ,having a couple of M-CPU machines, it's quite interesting. At this moment I think that you should not see it as 'magical distribution' of your processing pool but more like the way threads work. So every function will stay on it's CPU while executing and will not use the process power of another CPU if available. So I guess you have to fine grain your program to take the advantage of multiple CPU's, just like you would do if you had 'real' threads. -- mph From gerald.kaszuba at gmail.com Sat Feb 10 14:34:41 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 10 Feb 2007 11:34:41 -0800 Subject: pycallgraph 0.2.0 In-Reply-To: References: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> Message-ID: <1171136081.891918.213120@l53g2000cwa.googlegroups.com> On Feb 11, 12:28 am, s... at pobox.com wrote: > Looks nice. Before you get too far... Is there any chance that you can > support ASCII output mode (obviously not laid out in two dimensions, just > using indentation) so the GraphViz requirement can become optional? > GraphViz has so many dependencies of its own (and many of them are > GTK-related) that the chance of me satisfying them is very small. (I'm on > Solaris and Mac, not Linux, so I don't have the benefit of a Linux distro to > solve those particular headaches for me.) It's easy enough. I'll put it on my todo list. Gerald From mccredie at gmail.com Tue Feb 13 18:44:24 2007 From: mccredie at gmail.com (Matimus) Date: 13 Feb 2007 15:44:24 -0800 Subject: Tkinter: how; newbie In-Reply-To: References: Message-ID: <1171410264.493004.180800@v33g2000cwv.googlegroups.com> > How the callback function get this two number when it has only one > argument (event)? It has one argument, event, which is an instance of a class that has both x and y attributes. > print "clicked at", event.x, event.y It doesn't accept the coordinates as separate parameters because every event binding uses that same signature, even ones for which coordinates might not make any sense. I recommend you look over the python tutorial: http://docs.python.org/tut/ From bearophileHUGS at lycos.com Fri Feb 9 16:40:26 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Feb 2007 13:40:26 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171052486.043598.239470@p10g2000cwp.googlegroups.com> Message-ID: <1171057226.754537.262220@h3g2000cwc.googlegroups.com> Skip: > Python used to work that way. You'd then silently get errors if the API > changed between version A and version B and you neglected to recompile the > extensions you compiled against version A. Can't the compiled module have one or more test functions that can be used during linking to see if the compiled module respects the expected standard? Bye, bearophile From hg at nospam.org Sun Feb 18 11:42:41 2007 From: hg at nospam.org (hg) Date: Sun, 18 Feb 2007 17:42:41 +0100 Subject: PyDev on Mac References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> <1171812580.477975.37060@t69g2000cwt.googlegroups.com> Message-ID: Ahmer wrote: > On Feb 18, 4:50 am, "Diez B. Roggisch" wrote: >> Ahmer schrieb: >> >> > I've been trying to set up PyDev on my new MacBook Pro, but i have not >> > had an success. >> >> > Could you please help! >> >> Just wait until my crystal ball comes back from the cleaners, and I will >> start looking at your problem. >> >> As you can lay back and do nothing while that happens, I suggest you >> take this highly entertaining read: >> >> http://www.catb.org/~esr/faqs/smart-questions.html >> >> Diez > > > The main problem seems to be locating Python. > > Even though I installed the official python for mac, it says the > interpreter is invalid. > So I tried jPython, no succes on that either. It always tells me I am > using an invlaid interpreter. Are you pointing to the python directory in the eclipse/pydev config dialog ? hg From tenax.raccoon at gmail.com Thu Feb 22 11:37:22 2007 From: tenax.raccoon at gmail.com (Jason) Date: 22 Feb 2007 08:37:22 -0800 Subject: list/get methods/attributes of a class? In-Reply-To: <1172158035.977029.188980@q2g2000cwa.googlegroups.com> References: <1172158035.977029.188980@q2g2000cwa.googlegroups.com> Message-ID: <1172162242.724603.224050@v45g2000cwv.googlegroups.com> On Feb 22, 8:27 am, bkamr... at gmail.com wrote: > Hello, > Sorry guys for this newbie questions. But I wonder if there is a > standard or build-in method to know the methods of a class? > > I'm not originally a progrommer and I have worked with python/qt in a > basic level. Now I work a package which has many predefined classes > which I'm going to resue by importing them. I would like to know more > about each imported class, what methods exists and so on. Printing the > object or type(object) doesn't say so much. > > Any hint or helps is really appreciated! > /Ben Also, try out the built-in help function on the original class. It'll list the class layout, methods, and any associated document strings. (It won't list member variables, though.) To see all elements in an instance or class, use the dir() function. >>> class Dummy(object): ... "A sample class that can have any given data." ... def __init__(self, *args): ... self._args = args ... def GetArgCount(self): ... """Show how many arguments were passed at instantiation.""" ... return len(self._args) ... >>> d = Dummy(1, 2, 'three') >>> help(d) # help(Dummy) also works Help on Dummy in module __main__ object: class Dummy(__builtin__.object) | A sample class that can have any given data. | | Methods defined here: | | GetArgCount(self) | Show how many arguments were passed at instantiation. | | __init__(self, *args) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __dict__ = | dictionary for instance variables (if defined) | | __weakref__ = | list of weak references to the object (if defined) >>> --Jason From nagle at animats.com Fri Feb 9 13:33:26 2007 From: nagle at animats.com (John Nagle) Date: Fri, 09 Feb 2007 18:33:26 GMT Subject: pygame and python 2.5 In-Reply-To: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> Message-ID: Ben Sizer wrote: > The problem is something like this: > - Python extensions written in C require recompilation for each new > version of Python, due to Python limitations. > - Recompiling such an extension requires you to have a C compiler set > up on your local machine. > - Windows doesn't come with a C compiler, so you have to download > one. > - The compiler that Python expects you to use (Visual Studio 2003) is > no longer legally available. > - The other compiler that you can use (MinGW) is requires a slightly > convoluted set of steps in order to build an extension. > > Hopefully in the future, some of those convoluted steps will be fixed, > but that requires someone putting in the effort to do so. As is often > the case with Python, and indeed many open source projects, the people > who are knowledgeable enough to do such things usually don't need to > do them, as their setup already works just fine. True. There really should be no need to recompile a C extension unless the linkage format of the C compiler changes, which is a very rare event. Binary compatibility needs to be improved. In the GCC world, any compiler since 3.2 should generate interchangeable output. http://gcc.gnu.org/onlinedocs/gcc/Compatibility.html In the Windows world, I'm not sure about compatibility across the VC6/.NET transition, but I think you only need one version for either side of that one. John Nagle From arkanes at gmail.com Fri Feb 16 11:03:09 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 16 Feb 2007 10:03:09 -0600 Subject: f---ing typechecking In-Reply-To: <1171584254.805386.97300@a75g2000cwd.googlegroups.com> References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> <1171584254.805386.97300@a75g2000cwd.googlegroups.com> Message-ID: <4866bea60702160803v1b88ff4wbccb7a1d0bfded72@mail.gmail.com> On 15 Feb 2007 16:04:14 -0800, Paul McGuire wrote: > On Feb 15, 5:21 pm, Paul Rubin wrote: > > How can there be a structure datatype with an unpredictable > > number of members? > > > > It might have come across as a different question-sorry for any > > confusion. > > This may be where the "tuple is like a struct" analogy isn't so good, > and "tuple is like a list but immutable" is better. > > In both of your examples, the caller of f() sent a fixed list of > arguments: (1,2,3,4,5,6,7) in the first case and (8,9,10) in the > second. Internally I bet the compiler wants to clean up that same > list of those same args when f() is finished. > > Just as a thought experiment, do this for yourself. Implement f as: > > def f(*args): > args = list(args) > print args > > Now what is it you want to do with args that you can't do with it as a > tuple? Do you want some form of communication back to the caller to > occur, for example? Maybe some kind of pass-by-ref instead of pass-by- > value? > I wrote code that did exactly this just yesterday. I needed a list because I wanted to pop arguments off as I consumed them. From horpner at yahoo.com Tue Feb 13 07:49:29 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 13 Feb 2007 13:49:29 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171360113.585827.17440@v45g2000cwv.googlegroups.com> Message-ID: On 2007-02-13, Peter Otten <__peter__ at web.de> wrote: > Well, what problems ocurring with > > class A: pass > class B: pass > class C(A, B): pass > > could be avoided by writing > > class A: pass > class B(A): pass > class C(B): pass > > instead? With multiple inheritance, the choice of algorithm for Method Resolution Ordering isn't obvious or trivial. As I understand it, Python got it wrong for quite some time, allowing "bad" hierarchies to compile, i.e., classes for which the properties of local precedence ordering and monotonicity did not hold. URL:http://www.python.org/download/releases/2.3/mro/ -- Neil Cerutti From steve at REMOVEME.cybersource.com.au Wed Feb 14 21:31:35 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Feb 2007 13:31:35 +1100 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> <7xr6ssqis8.fsf@ruckus.brouhaha.com> Message-ID: Replying to my own question... On Thu, 15 Feb 2007 13:17:00 +1100, Steven D'Aprano wrote: > I don't see where the "with" version closes the file either. How does it > know that I want to call the f's close() method, rather than, say, > f.exit() or f.do_something_else()? Ah, I *think* I see... file objects in Python 2.5 are objects that know how to work with the "with" statement; that is they obey the "context management" protocol and have __enter__ and __exit__ methods that do the right thing to make everything work correctly. http://docs.python.org/whatsnew/pep-343.html Have I got it right? -- Steven D'Aprano From cityhunter007 at gmail.com Wed Feb 7 14:31:32 2007 From: cityhunter007 at gmail.com (James) Date: 7 Feb 2007 11:31:32 -0800 Subject: Python new user question - file writeline error Message-ID: <1170876692.167248.244870@s48g2000cws.googlegroups.com> Hello, I'm a newbie to Python & wondering someone can help me with this... I have this code: -------------------------- #! /usr/bin/python import sys month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG': 8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} infile=file('TVA-0316','r') outfile=file('tmp.out','w') for line in infile: item = line.split(',') dob = item[6].split('/') dob = dob[2]+'-'+str(month[dob[1]])+'-'+dob[0] lbdt = item[8].split('/') lbdt = lbdt[2]+'-'+str(month[lbdt[1]])+'-'+lbdt[0] lbrc = item[10].split('/') lbrc = lbrc[2]+'-'+str(month[lbrc[1]])+'-'+lbrc[0] lbrp = item[14].split('/') lbrp = lbrp[2]+'-'+str(month[lbrp[1]])+'-'+lbrp[0] item[6] = dob item[8] = lbdt item[10]=lbrc item[14]=lbrp list = ','.join(item) outfile.writelines(list) infile.close outfile.close ----------------------------- And the data file(TVA-0316) looks like this: ----------------------------- 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ NOV/2006,V1,,,21/NOV/2006,AST,19,U/L,5,40,, 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ NOV/2006,V1,,,21/NOV/2006,GGT,34,U/L,11,32,h, 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ NOV/2006,V1,,,21/NOV/2006,ALT,31,U/L,5,29,h, 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ NOV/2006,V1,,,21/NOV/2006,ALKP,61,U/L,40,135,, ----------------------------- Basically I'm reading in each line and converting all date fields (05/ MAR/1950) to different format (1950-03-05) in order to load into MySQL table. I have two issues: 1. the outfile doesn't complete with no error message. when I check the last line in the python interpreter, it has read and processed the last line, but the output file stopped before. 2. Is this the best way to do this in Python? 3. (Out of scope) is there a way to load this CSV file directly into MySQL data field without converting the format? Thank you. James From laurent.pointal at wanadoo.fr Mon Feb 5 15:25:40 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Mon, 05 Feb 2007 21:25:40 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <45c78a46$0$29725$426a74cc@news.free.fr> Message-ID: <45c791f1$0$5076$ba4acef3@news.orange.fr> Bruno Desthuilliers wrote: > Gosi a ?crit : >> On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: >> J has very many advanced operations. > > what's an "advanced operation" ? An operation which dont stay in place. From rkmr.em at gmail.com Sun Feb 11 23:39:51 2007 From: rkmr.em at gmail.com (mark) Date: Sun, 11 Feb 2007 20:39:51 -0800 Subject: standardized us address Message-ID: Hi Is there any python module that will convert address to standard US address format: for ex: 314 south chauncey avenue should be: 314 s chauncey ave thanks mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From lbates at websafe.com Fri Feb 23 18:44:14 2007 From: lbates at websafe.com (Larry Bates) Date: Fri, 23 Feb 2007 17:44:14 -0600 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) In-Reply-To: References: Message-ID: Charles D Hixson wrote: > I'm sure I've read before about how to construct prototypes in Python, > but I haven't been able to track it down (or figure it out). > > What I basically want is a kind of class that has both class and > instance level dict variables, such that descendant classes > automatically create their own class and instance level dict variables. > The idea is that if a member of this hierarchy looks up something in > it's local dict, and doesn't find it, it then looks in the class dict, > and if not there it looks in its ancestral dict's. This is rather like > what Python does at compile time, but I want to do it at run time. > > I'm sure I've seen how to do it...but have no idea where, or what it was > called, or when (probably around the time Prothon was being discussed, > as I have the idea of prototype associated with it for no clear reason). What you describe is exactly how Zope works so you might want to spend some time looking at it. http://www.zope.org -Larry From greg at cosc.canterbury.ac.nz Thu Feb 1 02:40:37 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 01 Feb 2007 20:40:37 +1300 Subject: ANN: Pyrex 0.9.5.1a Message-ID: Pyrex 0.9.5.1a is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ This is a glitch-fix nanorelease to correct a problem with the setup.py file. The list of packages to install is now calculate dynamically, so that it will work with or without the testing files. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From robert.kern at gmail.com Sun Feb 25 20:33:55 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 25 Feb 2007 19:33:55 -0600 Subject: finding out the precision of floats In-Reply-To: References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On 25 Feb 2007 05:31:11 -0800, "John Machin" > declaimed the following in comp.lang.python: > >> Evidently not; here's some documentation we both need(ed) to read: >> >> http://docs.python.org/tut/node16.html >> """ >> Almost all machines today (November 2000) use IEEE-754 floating point >> arithmetic, and almost all platforms map Python floats to IEEE-754 >> "double precision". >> """ >> I'm very curious to know what the exceptions were in November 2000 and >> if they still exist. There is also the question of how much it matters > > Maybe a few old Vaxes/Alphas running OpenVMS... Those machines had > something like four or five different floating point representations (F, > D, G, and H, that I recall -- single, double, double with extended > exponent range, and quad) I actually used Python on an Alpha running OpenVMS a few years ago. IIRC, the interpreter was built with IEEE floating point types rather than the other types. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From paddy3118 at netscape.net Fri Feb 2 23:23:48 2007 From: paddy3118 at netscape.net (Paddy) Date: 2 Feb 2007 20:23:48 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170455664.825637.267280@h3g2000cwc.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> <1170429433.258613.320600@a75g2000cwd.googlegroups.com> <1170455664.825637.267280@h3g2000cwc.googlegroups.com> Message-ID: <1170476627.960162.266450@h3g2000cwc.googlegroups.com> On Feb 2, 10:34 pm, bearophileH... at lycos.com wrote: > Paddy: > > >>> _ = [d[x0].append(x1) for x0,x1 in data] Yep, definitely a case of overdoing the list comprehensions when you throw away the list. I'll watch out for that in the future, Ta. - Paddy. > > I think that you probably want: > > for text, num in data: d[text].append(num) > > ardief: > > > thanks to everyone for the help, and the speed of it! It's really > > useful and I will spend some time working on understanding the code > > you posted. I'd be so lost without this group... > > If you have Python 2.5, and if you don't have particular requirements, > I think the best solution is Paddy's. > > Bye, > bearophile From ziga.seilnacht at gmail.com Mon Feb 26 14:49:14 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 26 Feb 2007 11:49:14 -0800 Subject: SystemError: new style getargs format but argument is not a tuple In-Reply-To: References: Message-ID: <1172519353.960277.232450@t69g2000cwt.googlegroups.com> zefciu wrote: > Ok. Now I do it this way: > > c_real = PyFloat_AsDouble(PyTuple_GetItem(coord,0)); > c_imag = PyFloat_AsDouble(PyTuple_GetItem(coord,1)); > > And it worked... once. The problem is really funny - in the interactive > the function fails every second time. > > >>> mandelpixel((1.5, 1.5), 9, 2.2) > > args parsed > coord parsed > ii3>>> mandelpixel((1.5, 1.5), 9, 2.2) > > TypeError: bad argument type for built-in operation>>> mandelpixel((1.5, 1.5), 9, 2.2) > > args parsed > coord parsed > ii3>>> mandelpixel((1.5, 1.5), 9, 2.2) > > TypeError: bad argument type for built-in operation > > etcaetera.... (the "args parsed" "coord parsed" and "i" are effect of > printfs in the code, as you see when it fails, it doesn't even manage to > parse the arguments. The direct solution to your problem is to use the "tuple unpacking" feature of PyArg_ParseTuple by using "(dd)id" as format argument. This is shown in the first example. The second example uses your approach and is a bit more cumbersome, but still works. Could you post your current version of the code? I don't understand where your problem could be. #include "Python.h" static PyObject * mandelpixel1(PyObject *self, PyObject *args) { double z_real = 0, z_imag = 0, z_real2 = 0, z_imag2 = 0; double c_real, c_imag, bailoutsquare; int iteration_number; register int i; if (!PyArg_ParseTuple(args, "(dd)id", &c_real, &c_imag, &iteration_number, &bailoutsquare)) return NULL; for (i = 1; i <= iteration_number; i++) { z_imag = 2 * z_real * z_imag + c_imag; z_real = z_real2 - z_imag2 + c_real; z_real2 = z_real * z_real; z_imag2 = z_imag * z_imag; if (z_real2 + z_imag2 > bailoutsquare) return Py_BuildValue("i", i); } return Py_BuildValue("i", 0); } static PyObject * mandelpixel2(PyObject *self, PyObject *args) { double z_real = 0, z_imag = 0, z_real2 = 0, z_imag2 = 0; double c_real, c_imag, bailoutsquare; int iteration_number; PyObject *coord; register int i; if (!PyArg_ParseTuple(args, "Oid", &coord, &iteration_number, &bailoutsquare)) return NULL; if (!PyTuple_Check(coord)) { PyErr_SetString(PyExc_TypeError, "something informative"); return NULL; } if (!PyArg_ParseTuple(coord, "dd", &c_real, &c_imag)) return NULL; for (i = 1; i <= iteration_number; i++) { z_imag = 2 * z_real * z_imag + c_imag; z_real = z_real2 - z_imag2 + c_real; z_real2 = z_real * z_real; z_imag2 = z_imag * z_imag; if (z_real2 + z_imag2 > bailoutsquare) return Py_BuildValue("i", i); } return Py_BuildValue("i", 0); } static PyMethodDef MandelcMethods[] = { {"mandelpixel1", mandelpixel1, METH_VARARGS, "first version"}, {"mandelpixel2", mandelpixel2, METH_VARARGS, "second version"}, {NULL, NULL, 0, NULL}, }; PyMODINIT_FUNC initmandelc(void) { Py_InitModule("mandelc", MandelcMethods); } Ziga From arkanes at gmail.com Thu Feb 22 14:58:18 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 22 Feb 2007 13:58:18 -0600 Subject: Possible to set cpython heap size? In-Reply-To: <1172172532.503432.223650@v33g2000cwv.googlegroups.com> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <1172172532.503432.223650@v33g2000cwv.googlegroups.com> Message-ID: <4866bea60702221158r5ef03db8pe300f2725f9d9735@mail.gmail.com> On 22 Feb 2007 11:28:52 -0800, Andy Watson wrote: > On Feb 22, 10:53 am, a bunch of folks wrote: > > > Memory is basically free. > > This is true if you are simply scanning a file into memory. However, > I'm storing the contents in some in-memory data structures and doing > some data manipulation. This is my speculation: > > Several small objects per scanned line get allocated, and then > unreferenced. If the heap is relatively small, GC has to do some work > in order to make space for subsequent scan results. At some point, it > realises it cannot keep up and has to extend the heap. At this point, > VM and physical memory is committed, since it needs to be used. And > this keeps going on. At some point, GC will take a good deal of time > to compact the heap, since I and loading in so much data and creating > a lot of smaller objects. > > If I could have a heap that is larger and does not need to be > dynamically extended, then the Python GC could work more efficiently. > I haven't even looked at Python memory management internals since 2.3, and not in detail then, so I'm sure someone will correct me in the case that I am wrong. However, I believe that this is almost exactly how CPython GC does not work. CPython is refcounted with a generational GC for cycle detection. There's a memory pool that is used for object allocation (more than one, I think, for different types of objects) and those can be extended but they are not, to my knowledge, compacted. If you're creating the same small objects for each scanned lines, and especially if they are tuples or new-style objects with __slots__, then the memory use for those objects should be more or less constant. Your memory growth is probably related to the information you're saving, not to your scanned objects, and since those are long-lived objects I simple don't see how heap pre-allocation could be helpful there. From dixkey at gmail.com Mon Feb 26 04:31:54 2007 From: dixkey at gmail.com (dixkey at gmail.com) Date: 26 Feb 2007 01:31:54 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: Message-ID: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> On Feb 26, 6:32 am, Tech HR wrote: > Our > website is currently a LAMP appication with P=Python. We are looking for > bright motivated people who know or are willing to learn Python and/or > Linux, Apache and MySQL system administration skills. (And if you want > to convince us that we should switch over to Postgres, we're willing to > listen.) This is more out of curiosity, but does it mean that you wouldn't be willing to listen about a switch from Python to Lisp? From uymqlp502 at sneakemail.com Wed Feb 21 19:05:38 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 21 Feb 2007 16:05:38 -0800 Subject: jython import search path Message-ID: <1172102737.885288.300090@l53g2000cwa.googlegroups.com> I have a Python program that I want to run in Jython so I can get Java bytecode output. The program runs fine in Python, but when I change the first line of the main program to make it run in Jython, it fails to find some of the imported modules. These are just plain Python imports of code I wrote myself in another directory. Apparently Jython does not use the PYTHONPATH environment variable. I created an environment variable called JYTHONPATH just to see what would happen, but it didn't work either. How am I supposed to tell Jython where to search for imported modules? Thanks. From sjmachin at lexicon.net Wed Feb 7 16:15:00 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 Feb 2007 13:15:00 -0800 Subject: what is wrong with my python code? In-Reply-To: References: Message-ID: <1170882900.152609.210940@a34g2000cwb.googlegroups.com> On Feb 8, 4:43 am, "Dongsheng Ruan" wrote: > I got feed back saying" list object is not callable". But I can't figure out > what is wrong with my code. > > A=[3,5,4,9,6,7] > l=len(A)-1 > > for i in range(l): > print A(i) What the others said, *plus*: (1) you are subtracting 1 off the length, so after the change from () to [], the last item would not be printed. (2) have you considered working through a tutorial? Cheers, John From skip at pobox.com Fri Feb 9 16:01:41 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 9 Feb 2007 15:01:41 -0600 Subject: pygame and python 2.5 In-Reply-To: <1171052486.043598.239470@p10g2000cwp.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171052486.043598.239470@p10g2000cwp.googlegroups.com> Message-ID: <17868.57653.122284.31903@montanaro.dyndns.org> Ben> If someone could explain the limitation in detail, I expect ways Ben> could be found around it. After all, I don't know of any other Ben> systems that require you to recompile all the extensions when you Ben> upgrade the application. Python used to work that way. You'd then silently get errors if the API changed between version A and version B and you neglected to recompile the extensions you compiled against version A. Maybe the Python extension API is mature enough now that it can be frozen, but I sort of doubt it. Skip From steve at REMOVE.THIS.cybersource.com.au Sun Feb 4 11:31:20 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 05 Feb 2007 03:31:20 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> <1170284969.902118.155570@l53g2000cwa.googlegroups.com> <1170453201.616987.65340@k78g2000cwa.googlegroups.com> Message-ID: On Fri, 02 Feb 2007 13:53:21 -0800, manstey wrote: > Hi, > > There was a mistake above, and then I'll explain what we're doing: >>>> insCacheClass = CacheClass(oref) >>>> insCacheProperty = CacheProperty(insOref,'Chapter') > > should have been >>>> insCacheClass = CacheClass(oref) >>>> insCacheProperty = CacheProperty(insCacheClass ,'Chapter') > > Now, to answer some questions. > 1. Cache refers to Intersystems Cache database, an powerful oo dbase > that holds our data. > 2. It comes with a pythonbinding, but unfortunatley the API, written > in C as a python extension, only provides old-style classes, which is > why we wrap the oref (an in-memory instance of a Cache class/table) > with CacheClass. This allows us to add attributes and methods to the > CacheClass, the most important being CacheProperty, which is a class > corresponding to the Cache property/field classes of the dbase. You can add attributes and methods to old-style classes. > 3. The pythonbind also has a strange behaviour, to our view. It gets > and sets values of its properties (which are classes), Are you sure you're using the word "classes" correctly? That seems ... strange. I'm wondering whether the properties are class _instances_. > via the > 'parent' oref, i.e. oref.set('Name','Peter'). But we want a pythonic > way to interact with Cache, such as, insCacheClass.Name='Peter'. and > insOref.Name.Set(). Okay, let me see that I understand what happens. Here's some pseudo-code of what I think you are currently doing: oref = get_a_reference_to_Cache_database() # or whatever # now do work on it using the python bindings. oref.set("Name", "Peter") oref.set("Something", "Else") Here's a wrapper for the bindings, so they work more pythonically: class Oref_Wrapper(object): def __init__(self, oref): self._oref = oref # save the oref for later use # Delegate attribute access to the oref def __setattr__(self, name, value): return self._oref.set(name, value) def __getattr__(self, name): return self._oref.get(name) # or whatever the oref does def __delattr__(self, name): return self._oref.del(name) # or whatever the oref does This is how you use it: oref = get_a_reference_to_Cache_database() # or whatever # re-bind the name to a wrapped version oref = Oref_Wrapper(oref) # now do work on it oref.Name = "Peter" oref.Something = "Else" > The code above (in post 7) does this, but as I > asked, by storing the parent instance (insCacheClass) inside each of > its attributes (insCacheProperty1,2, etc). Do you use insCacheClass and insCacheProperty for anything other than making the bindings more Pythonic? Because for the life of me I can't work out what they're supposed to do! > 4. Another reason we want a new-style class wrapped around the oref, > is that each oref has many methods on the server-side Cache database, > but they are all called the same way, namely, > oref.run_obj_method('%METHODNAME',[lisArgs]). We want to call these in > python in the much better insCacheClass.METHODNAME(Args). E.g. we > prefer insCacheClass.Save() to oref.run_obj_method('%Save',[None]). Using my code above, oref.METHODNAME(args) would resolve to: oref._oref.get("METHODNAME")(args) which may not do what you want. If you know all the possible METHODNAMES, then that's easy enough to fix: create methods at runtime. (If you don't know the methods, the problem becomes too hard for me to work out at 3am, but will probably still be solvable.) Change the __init__ method above to something like this (untested): import new class Oref_Wrapper(object): def __init__(self, oref): self._oref = oref # save the oref for later use METHODNAMES = ["Save", "Clear", "Something"] for name in METHODNAMES: function = lambda self, *args: \ self._oref.run_obj_method("%"+name, args) method = new.instancemethod(function, name) self.__dict__[name] = method then define the __getattr__ etc. methods as before, and (hopefully!) you are done: oref.Save() oref.Clear(1, 2, 3, 7) I hope this was of some help. -- Steven. From ifti_crazy at yahoo.com Fri Feb 16 16:22:14 2007 From: ifti_crazy at yahoo.com (ifti_crazy at yahoo.com) Date: 16 Feb 2007 13:22:14 -0800 Subject: Help Required for Choosing Programming Language Message-ID: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> I am VB6 programmer and wants to start new programming language but i am unable to deciced. i have read about Python, Ruby and Visual C++. but i want to go through with GUI based programming language like VB.net so will you please guide me which GUI based language has worth with complete OOPS Characteristics will wait for the answer hope to have a right direction from you Programmer Regards Iftikhar itzonepk at yahoo.com From lbates at websafe.com Thu Feb 15 15:19:31 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 15 Feb 2007 14:19:31 -0600 Subject: Python code to do the *server* side of digest authentication? In-Reply-To: <1171570425.442828.73170@p10g2000cwp.googlegroups.com> References: <1171570425.442828.73170@p10g2000cwp.googlegroups.com> Message-ID: Dan Lenski wrote: > Hi all, > I've got a very simple HTML proxy server to access the web from my > cell phone (based on this code: http://www.okisoft.co.jp/esc/python/proxy/). > It's a very retarded phone that freezes if there's no Content-Length > header and some other circumstances, so I have to tweak and modify the > headers received slightly. But it works quite well with these hacks. > > Now I'd like to add proxy authentication so that I'm not running this > open proxy all the time. I would like to use Digest authentication > (http://en.wikipedia.org/wiki/Digest_access_authentication) rather > than Basic authentication so as not to expose any plaintext password. > > It appears that there are plenty of Python libraries to do the > *client* side of the authentication (e.g. urllib2) but I have not > found much code that does the *server* side of the authentication. > That is, I am looking for code to generate the WWW-Authentication > header (including appropriate nonce and opaque string) and to verify > the Authorization header sent by the client when it retries. > > It does not look *too* hard to implement, but it does involve crypto > and I'd just as soon use some tried-and-true code rather than roll my > own in this case. Does anyone have any suggestions of where to find > such code? > > Thanks! > > Dan > I think that is because normally the web server does the authentication on the server side. Why not use Apache to do the digest authentication? http://httpd.apache.org/docs/2.0/mod/mod_auth_digest.html -Larry From fuzzyman at gmail.com Fri Feb 16 08:33:59 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Feb 2007 05:33:59 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> Message-ID: <1171632839.412221.274200@s48g2000cws.googlegroups.com> On Feb 16, 12:47 pm, "Edward K Ream" wrote: > > There is also the 2to3 converter. The aim is that this will be > > effective enough that coders should be able to maintain a 2.X (2.6 ?) > codebase, run it through 2to3 and have the result run unchanged on > Python 3. That way there will be no need to maintain two code bases. > > I have offered a proof that the converter must change print to print2 (or > some other name) in order to maintain a common code base. How much clearer > can I be? If a common code base is desired, it *is* the end of print > Why won't it be possible to make 'print' in Python 3 that supports all the functionality of the current print statement, and then translate to that ? I saw an assertion to the effect that it wasn't possible - but no proof. It sounds relatively straightforward for me... Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream... at charter.net > Leo:http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- From steve at REMOVEME.cybersource.com.au Mon Feb 26 01:58:34 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 26 Feb 2007 17:58:34 +1100 Subject: Help on Dict References: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> Message-ID: On Mon, 26 Feb 2007 07:15:43 +0200, Hendrik van Rooyen wrote: > "James Stroud" wrote: > > >> Clement wrote: >> > Can any body tell how Dict is implemented in python... plz tell what >> > datastructure that uses................ >> > >> >> I think it uses a dict. > > "Groan!" - this answer is like Microsoft documentation - > while technically correct, it is useless... : - ) Which I think was deliberate. The Original Poster asked a reasonable question in a stupid way (Python is case-insensitive -- are we supposed to guess what a Dict is? what language is 'plz'?), and I believe James deliberately gave a stupid answer to highlight that. class Dict(dict): pass is what I thought of when I saw the question. I guess James might have thought the same way. Unfortunately, more often than not, the sort of person who uses 'plz' in an email probably isn't going to recognise the subtleties of James' reply. -- Steven D'Aprano From sickcodemonkey at gmail.com Sat Feb 3 14:55:50 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Sat, 3 Feb 2007 14:55:50 -0500 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? In-Reply-To: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Message-ID: <2adc542f0702031155l43f54edbqbba291db8d9c11b3@mail.gmail.com> If you need to extend your PATH variable, I have used this in the past. ~~~~~~~~~~~~~~~~~~ def AddSysPath(new_path): new_path = os.path.abspath(new_path) do = -1 if os.path.exists(new_path): do = 1 # check against all paths currently available for x in sys.path: x = os.path.abspath(x) if sys.platform == 'win32': x = x.lower() if new_path in (x, x + os.sep): do = 0 # add path if we don't already have it if do: sys.path.append(new_path) pass return do On 2/3/07, Stef Mientki wrote: > > Is it possible to change the searchpath for modules on the flight, > under winXP ? > Most preferred is some command to extend the searchpath. > (the environment variable PYTHONPATH needs a reboot) > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From harlinseritt at yahoo.com Sat Feb 17 12:55:56 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 17 Feb 2007 09:55:56 -0800 Subject: Importing from upper directory Message-ID: <1171734956.679327.9550@a75g2000cwd.googlegroups.com> I have a script that I want to import called upper.py. It is 2 directories above the script that will call it - i'll call that one main.py. How am I able to import a script in a directory that is above it? Thanks, Harlin From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Feb 10 07:34:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 10 Feb 2007 13:34:23 +0100 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com><1170872694.018720.301410@m58g2000cwm.googlegroups.com> <52vdp2F1qp2n6U2@mid.individual.net> Message-ID: <535sefF1qoh5lU2@mid.individual.net> Carl J. Van Arsdall wrote: > Not necessarily, if he's on a full duplex ethernet connection, > then there is some parallelity he can take advantage of. He has > upstream and downstream. Partly agreed. There is one bus to the network device, and CPU should be very much faster than the network device itself, so I estimate there'll be no gain. Regards, Bj?rn -- BOFH excuse #353: Second-system effect. From nogradi at gmail.com Mon Feb 26 08:03:34 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 26 Feb 2007 14:03:34 +0100 Subject: [OT] python notation in new NVIDIA architecture Message-ID: <5f56302b0702260503q75a2488fl9d1641df07733880@mail.gmail.com> Something funny: The new programming model of NVIDIA GPU's is called CUDA and I've noticed that they use the same __special__ notation for certain things as does python. For instance their modified C language has identifiers such as __device__, __global__, __shared__, etc. Is it a coincidence? Probably it is. :) From funkyj at gmail.com Mon Feb 26 23:13:01 2007 From: funkyj at gmail.com (funkyj) Date: 26 Feb 2007 20:13:01 -0800 Subject: how to call os.path.join() on a list ... In-Reply-To: <1172549038.422389.296920@q2g2000cwa.googlegroups.com> References: <1172549038.422389.296920@q2g2000cwa.googlegroups.com> Message-ID: <1172549581.848307.161180@h3g2000cwc.googlegroups.com> On Feb 26, 8:03 pm, "funkyj" wrote: > I want to call os.path.join() on a list instead of a variable list of > arguments. I.e. > > [scr-misc] (186:0)$ python > iPython 2.4 (#2, Feb 18 2005, 16:39:27) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more > information. > m>>> > >>> import os > >>> import string > >>> p = os.environ['PWD'] > >>> p > '/tmp/a/b/c/d' > >>> os.path.join(string.split(p, os.sep)) > ['', 'tmp', 'a', 'b', 'c', 'd'] > >>> > > the value returned by os.path.join() is obviously not the desired > result ... > > Sure, I can hack my own version of os.path.join() by using os.sep but > that does not seem very pythonic. > > In lisp one would do something like > > (funcall #'os.path.join (string.split p os.sep)) > > What is the python idiom for callling a function like os.path.join() > that takes a variable number of arguments when you currently have the > arguements in a list variable? > > I'm curious about the answer to the question above but in the meantime > I'll hack "my.path.join()' that takes a single list as an argument and > move on with my little project. > > Regards, > fj figured it out ... I can just do: os.sep.join(string.split(p, os.sep)) it isn't "funcall" but it gets me where I want to go. Regards, --jfc From jojoba12 at hotmail.com Mon Feb 26 16:15:56 2007 From: jojoba12 at hotmail.com (jojoba) Date: 26 Feb 2007 13:15:56 -0800 Subject: is it possible to use ironpython 1.1 in visual studio 2005 Message-ID: <1172524556.739101.245050@v33g2000cwv.googlegroups.com> hi all is it possible to use ironpython 1.1 in visual studio 2005? i have 1.0 running great...but would love to use the newer verision any ideas thank you immenely, jojoba From kavithapython at yahoo.co.in Mon Feb 26 05:06:28 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Mon, 26 Feb 2007 10:06:28 +0000 (GMT) Subject: writing a file:newbie question In-Reply-To: Message-ID: <353077.93084.qm@web7805.mail.in.yahoo.com> Hi All, Thanks for your reply Gabriel ,,, I just had to use a backslash character to write newline in the proper loop.So I could solve that problem.But now my question is I would like to delete the comma at the end. say for example,,i have a file test.txt and the file has the list a,b,c,d, i would like to delete the trailing comma at the end,,, if someone knows pls write to me,,, kavitha Gabriel Genellina wrote: En Mon, 19 Feb 2007 08:02:29 -0300, kavitha thankaian escribi?: > Hi, > i have a file test.txt and it contains a list of strings say,,, > "a","b","c","d","a1","b1","c1","d1","a2","b2","c2","d2", > i would like to write the file as > "a","b","c","d" > "a1","b1","c1","d1 > "a2","b2","c2","d2" > and would like to delete the comma at the end. Not enough info... Does the input file contain only one line, or many lines? Always exactly 12 items? Including a trailing , ? The following may work for 12 items. Use the csv module to read the file: import csv reader = csv.reader(open("test.txt", "r")) writer = csv.writer(open("output.txt", "w")) for row in reader: writer.writerow(row[:4]) writer.writerow(row[4:8]) writer.writerow(row[8:]) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From rNOSPAMon at flownet.com Thu Feb 1 22:48:03 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 01 Feb 2007 19:48:03 -0800 Subject: Python, readline and OS X References: <45c28755$0$322$e4fe514c@news.xs4all.nl> Message-ID: In article <45c28755$0$322$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > Ron Garret wrote: > > I have installed Python 2.5 on my new Intel Mac but I can't for the life > > of me get readline to work. I have libreadline installed, I've tried > > copying readline.so from my Python 2.3 installation into 2.5, I've > > searched the web, and no joy. Could someone please give me a clue? > > > > rg > > Does the info in a blog article that I wrote help? > > http://www.razorvine.net/frog/user/irmen/article/2006-05-08/87 No, because I'm not using Fink. But maybe I can adapt your solution. > I used this when I compiled my Python 2.5 on my mac, and > it seemed to work ;-) > > I'm now using the python.org binary distribution though and that seems to > contain a working readline as well.... ? I'll try that too. rg From millerdev at gmail.com Tue Feb 27 16:37:12 2007 From: millerdev at gmail.com (Daniel) Date: 27 Feb 2007 13:37:12 -0800 Subject: boolean flag vs threading.Event Message-ID: <1172612232.442199.29720@s48g2000cws.googlegroups.com> I have a class similar to this: class MyThread(threading.Thread): def __init__(self): self.terminated = False def run(self): while not self.terminated: pass # do stuff here def join(self): self.terminated = True threading.Thread.join(self) Recently I was reading in the Python Cookbook (9.2 Terminating a Thread) about how to do this sort of thing. That recipe uses a threading.Event object to signal the thread termination. Here's my class recoded to use an event: class MyThread(threading.Thread): def __init__(self): self.event = threading.Event() def run(self): while not self.event.isSet(): pass # do stuff here def join(self): self.event.set() threading.Thread.join(self) If I understand the GIL correctly, it synchronizes all access to Python data structures (such as my boolean 'terminated' flag). If that is the case, why bother using threading.Event for this purpose? Thanks, ~ Daniel From samckain at southslope.net Thu Feb 15 12:52:30 2007 From: samckain at southslope.net (Steve) Date: Thu, 15 Feb 2007 11:52:30 -0600 Subject: list of range of floats References: <1171547865.283724.319990@k78g2000cwa.googlegroups.com> Message-ID: On Thu, 15 Feb 2007 05:57:45 -0800, Bart Ogryczak wrote: > On Feb 14, 6:12 pm, Steve wrote: >> I'm trying to create a list range of floats and running into problems. > > I've tried it the easy way. Works. > map(float,range(a,b)) Thanks Bart, I'll give it a try Steve From sandeep.patil at hcl.in Tue Feb 13 03:53:10 2007 From: sandeep.patil at hcl.in (Sandeep Patil , Bangalore) Date: Tue, 13 Feb 2007 14:23:10 +0530 Subject: hi all Message-ID: I get an error while I try to call python through VB. The error is " Error 429: Active X cant create object" Pls anybody help me to call python through VB. Thanks and Regards. Sandeep Patil HCL Technologies " Expecting the world to treat you fairly coz you are a gud person, is like expecting the Lion not to attack you as you are a Vegetarian. " DISCLAIMER: ----------------------------------------------------------------------------------------------------------------------- The contents of this e-mail and any attachment(s) are confidential and intended for the named recipient(s) only. It shall not attach any liability on the originator or HCL or its affiliates. Any views or opinions presented in this email are solely those of the author and may not necessarily reflect the opinions of HCL or its affiliates. Any form of reproduction, dissemination, copying, disclosure, modification, distribution and / or publication of this message without the prior written consent of the author of this e-mail is strictly prohibited. If you have received this email in error please delete it and notify the sender immediately. Before opening any mail and attachments please check them for viruses and defect. ----------------------------------------------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From attn.steven.kuo at gmail.com Sun Feb 11 11:16:11 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 11 Feb 2007 08:16:11 -0800 Subject: How to find all the same words in a text? In-Reply-To: References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: <1171210571.609726.254260@v33g2000cwv.googlegroups.com> On Feb 11, 5:13 am, Samuel Karl Peterson wrote: > "Johny" on 10 Feb 2007 05:29:23 -0800 didst step > forth and proclaim thus: > > > I need to find all the same words in a text . > > What would be the best idea to do that? > > I make no claims of this being the best approach: > > ==================== > def findOccurances(a_string, word): > """ > Given a string and a word, returns a double: > [0] = count [1] = list of indexes where word occurs > """ > import re > count = 0 > indexes = [] > start = 0 # offset for successive passes > pattern = re.compile(r'\b%s\b' % word, re.I) > > while True: > match = pattern.search(a_string) > if not match: break > count += 1; > indexes.append(match.start() + start) > start += match.end() > a_string = a_string[match.end():] > > return (count, indexes) > ==================== > > Seems to work for me. No guarantees. > More concisely: import re pattern = re.compile(r'\b324\b') indices = [ match.start() for match in pattern.finditer(target_string) ] print "Indices", indices print "Count: ", len(indices) -- Cheers, Steven From noway at ask.me Tue Feb 13 20:09:28 2007 From: noway at ask.me (Giovanni Bajo) Date: Wed, 14 Feb 2007 02:09:28 +0100 Subject: Fast constant functions for Py2.5's defaultdict() In-Reply-To: <1171393305.268249.268580@q2g2000cwa.googlegroups.com> References: <1171393305.268249.268580@q2g2000cwa.googlegroups.com> Message-ID: On 13/02/2007 20.01, Raymond Hettinger wrote: > FWIW, here are three ways of writing constant functions for > collections.defaultdict(): > > d = defaultdict(int) # slowest way; works only for zero > d = defaultdict(lambda: 0) # faster way; works for any constant > d = defaultdict(itertools.repeat(0).next) # fastest way; works > for any constant > > Another approach is to use the __missing__ method for dictionary > subclasses: > > class zerodict (dict): > def __missing__ (self, key): > return 0 # fast on initial miss, but slow on > non-misses; works for any constant > > The itertools.repeat(const).next approach wins on speed and > flexibility. But it's the most unreadable too. I'm surprised that defaultdict(int) is slower than the lambda one though. What's the reason? -- Giovanni Bajo From laurent.pointal at limsi.fr Fri Feb 2 09:51:28 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Feb 2007 15:51:28 +0100 Subject: newbie/ merging lists of lists with items in common In-Reply-To: References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: Neil Cerutti a ?crit : > On 2007-02-02, ardief wrote: > This is a job for... duhn-duhn-DAAAAH! Captain CHAOS! > > Er... I mean itertools.groupby. > > def key_func(t): > return t[0] Not needed: --> from operator import itemgetter See in the example: http://docs.python.org/lib/itertools-example.html So much stuff in libraries, so few we know. Thanks to doc writers, Usenet contributors & Google search engines. From theller at ctypes.org Sat Feb 10 10:50:54 2007 From: theller at ctypes.org (Thomas Heller) Date: Sat, 10 Feb 2007 16:50:54 +0100 Subject: LoadLibrary(pythondll) failed In-Reply-To: References: Message-ID: acncgc schrieb: > I get an following error as I turn on my laptop; > > LoadLibrary(pythondll) failed > > After this error internet browser ( IE or mozilla) doesn't connect. I > can't browse any site. > > Any idea?? > This looks like a message from a broken py2exe'd application. You have to find out where it comes from (AFAIK even viruses or trojaners have been built with Python). Thomas From pierre_marie_durand at yahoo.fr Thu Feb 22 14:40:35 2007 From: pierre_marie_durand at yahoo.fr (pierre_marie_durand at yahoo.fr) Date: 22 Feb 2007 11:40:35 -0800 Subject: Performance project for the SigEx Foundry In-Reply-To: <1172060154.122555.190330@k78g2000cwa.googlegroups.com> References: <1172060154.122555.190330@k78g2000cwa.googlegroups.com> Message-ID: <1172173230.420259.123190@l53g2000cwa.googlegroups.com> On Feb 21, 1:15 pm, p... at sigex.com wrote: > have been testing performances of different scripting languages > fordatabase access, text processing and client application data > transfer. So far, I am getting better performance from PHP, but I > don't have any hard data to back it up compared to others. > > This is a large project for theSigExFoundryand it involves hundreds > of servers. I am looking for articles/studies/benchmarks on the > subject. > > Thank you, > > Pablo > Server Side Developer > Student for theSigExFoundry > funded bySigExVentures Hi Pablo, It's a good question. You want to really understand what you are doing this benchmark for. In my opinion, you should go for the language that fits your needs and focus on performance optimization for that language. I would be more inclined to go with PHP, but that's a personal choice. I'm sure you can search performance for these languages and come up with lots of ressources on the web. Pierre-Marie Durand From GSlusarek at gmail.com Thu Feb 1 07:56:50 2007 From: GSlusarek at gmail.com (Grzegorz Smith) Date: 1 Feb 2007 04:56:50 -0800 Subject: ZSI and WSDL schema In-Reply-To: References: <1170328454.427204.245470@p10g2000cwp.googlegroups.com> Message-ID: <1170334610.820455.324260@q2g2000cwa.googlegroups.com> Ok here goes a detail: I call two methods by soap. The response of that methods is described by xml. Here is first request: (method name QuickSearch, one parameter called name) So here go 1 response (part of the wsdl): and the methods that I call is here: def QuickSearch(name): #here done something by name paramater passed by #and return parameter name return {'name':50} I don't know how to pack returned data to the proper envelope. When I made SOAP call by hand (just like examples from ZSI everything goes well), but when I made SOAP by WSDL everything goes wrong. And here is the second question I descripe response from my second SOAP Method, it looks like this: I have data prepared in Python script, but still don't know how to made proper response envelop with that data. As you see it's complicated type, but I don't what It should look like to be proper response. Any help? Please Gregor Thanks Simon On 1 Lut, 12:42, "Simon Brunning" wrote: > On 1 Feb 2007 03:14:14 -0800, Grzegorz Smith wrote: > > > Hi all. I have problem with ZSI and WSDL schema.I generate from WSDL > > by wsdl2py client method for webservice. I made soap call and > > something goes wrong. > > It might help if you were a little more specific. > > -- > Cheers, > Simon B > s... at brunningonline.nethttp://www.brunningonline.net/simon/blog/ From jeremy at gransdenonline.com Mon Feb 19 15:43:19 2007 From: jeremy at gransdenonline.com (Jeremy Gransden) Date: Mon, 19 Feb 2007 15:43:19 -0500 Subject: How to call a function defined in another py file In-Reply-To: <1171916841.964600.262530@q2g2000cwa.googlegroups.com> References: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> <45da0720$0$3822$5402220f@news.sunrise.ch> <1171916841.964600.262530@q2g2000cwa.googlegroups.com> Message-ID: <67E812CD-41C9-4769-A104-0113C88DD04E@gransdenonline.com> On Feb 19, 2007, at 3:27 PM, silverburgh.meryl at gmail.com wrote: > On Feb 19, 2:22 pm, "Martin Blume" wrote: >> schrieb >> >>> I have a function called 'test' defined in A.py. >>> How can I call that function test in my another file B.py? >> >> In B.py: >> >> import A >> >> A.test() >> >> HTH >> Martin > > But Do I need to put A.py and B.py in the same directory? > if not, where does python look for A.py ? No, they do not have to be in the same directory. A.py needs to be in your path. > And do I need to compile A.py before I can import it to B.py? No jeremy From vithi99 at hotmail.com Sat Feb 17 15:47:23 2007 From: vithi99 at hotmail.com (vithi) Date: 17 Feb 2007 12:47:23 -0800 Subject: how to use Dispatch to open an application in win32com.client In-Reply-To: References: <1171679786.355275.191860@h3g2000cwc.googlegroups.com> Message-ID: <1171745243.399770.259180@k78g2000cwa.googlegroups.com> Hi Since I haven't see any help or tutorial on com there is a application is installed in the server I am login to the server then what code do I have to implement to launch the application registered in a server. how do I write a code to tell my computer to go in to the perticular server and launch program "XYZ " do you think this code alone enough to go and look for xyz application in the server, I don't get it Give me any sample code or more help. It help me a lot. object = win32com.client.Dispatch("xyz.Application") On Feb 16, 11:56 pm, "Gabriel Genellina" wrote: > En Fri, 16 Feb 2007 23:36:26 -0300, vithi escribi?: > > > I am trying to launch an application. When I try like that > > When I try like that Excel is opening > > import win32com.client > > object = win32com.client.Dispatch("Excel.Application") > > object.Visible = 1 > > > But when I try my application which is QeepIt.exe > > which is in the c:\ drive it is not running > > Any body tell me how to give path to open an exectable application in > > Dispatch modules > > I try like that > > object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") > > It give an error. > > The above code is used to launch a COM server registered under the name > "Excel.Application" and then control it. If you don't know what a COM > server is, surely your application can't be used this way. > > For launching another program, perhaps sending it some text, and capturing > its output, look at the subprocess module. If you are only interested in > executing it, with no additional communication, os.system() may be enough. > > -- > Gabriel Genellina From http Fri Feb 16 13:36:37 2007 From: http (Paul Rubin) Date: 16 Feb 2007 10:36:37 -0800 Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <7xd54a6jof.fsf@ruckus.brouhaha.com> Message-ID: <7xlkiy0x1m.fsf@ruckus.brouhaha.com> Paul Rubin writes: > notations for lists and dicts, using list((1,2,3)) and dict((1,2),(3,4)) > for [1,2,3] and {1:2, 3:4} respectively. Actually that would be dict(((1,2), (3,4))), of course. From ruka_at_ at fastmail.fm Fri Feb 16 06:16:01 2007 From: ruka_at_ at fastmail.fm (ruka_at_ at fastmail.fm) Date: 16 Feb 2007 03:16:01 -0800 Subject: KeyboardInterrupt not caught In-Reply-To: References: <1171619263.029325.67550@k78g2000cwa.googlegroups.com> Message-ID: <1171624561.583112.89230@m58g2000cwm.googlegroups.com> On 16 Feb., 11:44, "Gabriel Genellina" wrote: Thanks to all of you, for the fast answers. The code I showed you is actually the code running. I tried to catch eof, cause I read ^C could produce EOF (the self.showtraceback() was just a stupid cut 'n paste). But not even the except that should catch all exceptions is triggered. Thanks again, br Rudi From hardcoded.software at gmail.com Mon Feb 5 06:53:31 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 5 Feb 2007 03:53:31 -0800 Subject: Inheriting str object In-Reply-To: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> References: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> Message-ID: <1170676411.762814.25690@s48g2000cws.googlegroups.com> On Feb 5, 5:48 am, "kungfoo... at gmail.com" wrote: > I want to have a str with custom methods, but I have this problem: > > class myStr(str): > def hello(self): > return 'hello '+self > > s=myStr('world') > print s.hello() # prints 'hello world' > s=s.upper() > print s.hello() # expected to print 'hello WORLD', but s is no longer > myStr, it's a regular str! > > What can I do? To prevent operations with your myStr class to return a simple str instance, you will have to override pretty much all str method, as well as magic methods, such as __add__, __radd__ etc.. Major pain in perspective. You might want to reconsider you developing strategy. From kwatch at gmail.com Fri Feb 2 13:30:01 2007 From: kwatch at gmail.com (kwatch at gmail.com) Date: 2 Feb 2007 10:30:01 -0800 Subject: [Q] result of os.times() is different with 'time' command Message-ID: <1170441001.097986.294510@h3g2000cwc.googlegroups.com> Hi, I have a question about os.times(). os.times() returns a tuple containing user time and system time, but it is not matched to the result of 'time' command. For example, os.times() reports that user time is 39.85 sec, but 'time' command reports that user time is 28.55sec. (machine: Python2.5, MacOS X 10.4 Tiger, MacBook 1.83GHz intel core duo) file: ostimetest.py -------------------- import os ## benchmark function def f(x): if x <= 1: return 1 else: return f(x-1) + f(x-2) ## do benchmark n = 35 t1 = os.times() # start time v = f(n) # end time print "n=%d, v=%d" % (n, v) t2 = os.times() ## print result utime = t2[0] - t1[0] # user time stime = t2[1] - t1[1] # system time print "utime=%s, stime=%s" % (utime, stime) -------------------- Result: ==================== $ python -V Python 2.5 $ time python ostimetest.py n=35, v=14930352 utime=39.85, stime=0.216666666667 real 0m28.554suser 0m23.938ssys 0m0.177s ==================== This shows that os.times() reports that user time is 39.85sec, but time command shows that user time is 23.938sec. Why os.times() reports wrong result? Do I have any mistake? -- kwatch From dixkey at gmail.com Tue Feb 27 09:56:17 2007 From: dixkey at gmail.com (dixkey at gmail.com) Date: 27 Feb 2007 06:56:17 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: <1172588177.556909.246130@z35g2000cwz.googlegroups.com> > Who is the CTO? > > Wade Don't you people have Google in your villag^W universe? From python at hope.cz Fri Feb 16 07:44:32 2007 From: python at hope.cz (Johny) Date: 16 Feb 2007 04:44:32 -0800 Subject: Regex - where do I make a mistake? Message-ID: <1171629872.499083.150140@p10g2000cwp.googlegroups.com> I have string="""55. 128 170 """ where I need to replace 55. 170 by space. So I tried ############# import re string="""55.128170 """ Newstring=re.sub(r'.*'," ",string) ########### But it does NOT work. Can anyone explain why? Thank you L. From dsulkin at mqplp.com Tue Feb 6 10:24:22 2007 From: dsulkin at mqplp.com (David Sulkin) Date: Tue, 6 Feb 2007 09:24:22 -0600 Subject: Format a float and put in a list In-Reply-To: <44FE5DB1D8C46B41A60406A174446E04F5CF93@marquettemail.marquette.local> Message-ID: <44FE5DB1D8C46B41A60406A174446E04F5CFAD@marquettemail.marquette.local> Hello all, I found a workaround solution. I use the items in the list to be placed in a string, so I just formatted the entire string to remove any single quotes. Duh! Thanks ________________________________ From: python-list-bounces+dsulkin=mqplp.com at python.org [mailto:python-list-bounces+dsulkin=mqplp.com at python.org] On Behalf Of David Sulkin Sent: Tuesday, February 06, 2007 6:53 AM To: python-list at python.org Subject: Format a float and put in a list Hello, I have a float that I am trying to format to 2 decimal places, put the formatted float in a list and then output this to a file. My problem is, once I format my float, my float has quotations around the float due to my formatting. I am doing the following: ( "%.2f" % float( list[x] ) ) Is there a way I can format the float so when I see it in the file it looks like [19.45, 20.52, 16.56] instead of ['19.45', '20.52', '16.56']? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From msoulier at gmail.com Thu Feb 1 22:17:10 2007 From: msoulier at gmail.com (msoulier) Date: 1 Feb 2007 19:17:10 -0800 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <1170386230.362937.96870@k78g2000cwa.googlegroups.com> On Jan 24, 2:59 pm, John Nagle wrote: > Python is the only major open source project I've encountered where > there's so much hostility to bug reports. Try telling the Perl community that their debugger is broken. That didn't go well. ;-) Mike From pDOTpagel at gsf.de Thu Feb 22 06:57:50 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Thu, 22 Feb 2007 11:57:50 +0000 (UTC) Subject: Finding a tuple in a tuple References: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> Message-ID: bg_ie at yahoo.com wrote: > t1 = ("ONE","THREE","SIX") > t2 = ("ONE","TWO","THREE") > t3 = ("TWO","FOUR","FIVE","SIX") > t4 = ("TWO",) > t5 = ("TWO","FIVE") > What I want to do is return true if any member of tuple t1 is found in > the remaining tuples. Another way to go instead of using sets, although probably less elegant: >>> True in [x in t1 for x in t2] True >>> True in [x in t1 for x in t3] True >>> True in [x in t1 for x in t4] False >>> True in [x in t1 for x in t5] False cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From mizipzor at gmail.com Sun Feb 4 14:53:19 2007 From: mizipzor at gmail.com (Mizipzor) Date: 4 Feb 2007 11:53:19 -0800 Subject: "Subscribing" to topics? In-Reply-To: <5aoxh.7440$gJ1.6708@newsfe17.lga> References: <5aoxh.7440$gJ1.6708@newsfe17.lga> Message-ID: <1170618799.354069.327210@h3g2000cwc.googlegroups.com> On Feb 4, 10:51 am, hg wrote: > Mizipzor wrote: > > Is there a way to "subscribe" to individual topics? im currently > > getting bombarded with daily digests and i wish to only receive a mail > > when there is activity in a topic that interests me. Can this be done? > > > Thanks in advance. > > Use a news reader and leave the mailing list > > hg I searhed around a little and it seems that not only do i need a newsreader, i need a newsserver to. To fetch all the messages from here. I learned that sometimes the ISP provides one, however, mine do not. But then I discovered that Google has a free newsserver, so I joined this group from there. Sadly, I cant see a feature here that lets me subscribe to an individual topic, so if anyone else is using Google groups and know how to do something like this, please tell me. :) From gigs at hi.t-com.hr Wed Feb 14 17:41:02 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 14 Feb 2007 23:41:02 +0100 Subject: pyscripter Message-ID: How to change syntax color in pyscripter for python interpreter? I have change color in tools>options>editor options and everything is fine till restart pyscripter. After restart only in module is good syntax color, but in interpreter is back to default. thx From knipknap at gmail.com Sun Feb 18 07:26:41 2007 From: knipknap at gmail.com (Samuel) Date: 18 Feb 2007 04:26:41 -0800 Subject: Distutils: Python version information Message-ID: <1171801601.184574.278430@m58g2000cwm.googlegroups.com> In Python cheese shop, there is a field that shows the Python version that is required by a listed package. I have not found this covered in the distutils documentation: How do you add the Python version information into the setup script of a package? Unfortunately, the keyword list: http://docs.python.org/dist/meta-data.html is incomplete (for example, the "provides" and "requires" keywords are not listed, even though covered in the previous chapters of the documentation). -Samuel From a.schmolck at gmail.com Mon Feb 5 12:47:54 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 17:47:54 +0000 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> Message-ID: skip at pobox.com writes: > Gosi> J is in many ways similar to Python. > > Gosi> J has very many advanced operations. > > Gosi> http://www.jsoftware.com/ > > Doesn't look like open source of any variety. If a person uses Python with > various add-ons (RPy, numpy, matplotlib, etc) why would they want to switch > to a closed source product? You wouldn't, if for nothing else because python has far better scientific libraries. If you've got an interest in programming languages as such J (or some other APL) is worth a look though; it's also handy for quick mathematical experimentation (J's array primitives are more expressive than what numpy offers and python doesn't support rationals, so it's not just concise due to perl-style crypticness). For example I once wrote this (slow) code to display part of a mandelbrot fractal: load'viewmat' viewmat+/2&>:|((j.~/~(%~i:)99)&+@:*:)^:(i.32)0 It'll likely require you more typing in python, but then you'd need to do such things quite a lot for seeing an amortization in terms of less time spent with your PC; I think most people will find they need a seizable learning investment to get anywhere with J and python already is very expressive for the kind of things J is good at. 'as From Peter.Mayne at hp.com Mon Feb 19 19:44:24 2007 From: Peter.Mayne at hp.com (Peter mayne) Date: Tue, 20 Feb 2007 00:44:24 GMT Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: Steven D'Aprano wrote: > If Python 3 dropped the print > statement and replaced it with official_print_function(), how would that > help you in your goal to have a single code base that will run on both > Python 2.3 and Python 3, while still using print? Is there any reason why official_print_function isn't sys.stdout.write? I can't remember the last time I used print in actual code (apart from short-lived debugging lines), so I'm bewildered as to why print seems to be so important. PJDM From http Tue Feb 20 02:08:40 2007 From: http (Paul Rubin) Date: 19 Feb 2007 23:08:40 -0800 Subject: SICP video lectures Message-ID: <7xabz95mrr.fsf_-_@ruckus.brouhaha.com> I didn't know about these! Enjoy. http://swiss.csail.mit.edu/classes/6.001/abelson-sussman-lectures/ From deets at nospam.web.de Tue Feb 27 06:35:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Feb 2007 12:35:09 +0100 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> <1172573562.215310.76760@8g2000cwh.googlegroups.com> <54ih3nF2143jeU2@mid.uni-berlin.de> <1172574041.569357.127440@q2g2000cwa.googlegroups.com> Message-ID: <54ijbdF1urdo2U1@mid.uni-berlin.de> boris.smirnov at gmail.com wrote: > On Feb 27, 11:56 am, "Diez B. Roggisch" wrote: >> > Yes that I can deduce, but why I'm asking is why it's different on >> > Windows and Linux. Should it not be platform independent? >> >> It should be. I've got no idea why it seems to work on windows but I can >> say one thing for sure: that would be an artifact that you shouldn't rely >> on. In Qt, you _always_ need a QApplication for anything. So just do as >> it requires you to do: first, construct a QApplication. Then things will >> work. >> >> Diez > > Hmm, as I see the code, I do construct QApplication as first > > if __name__ == '__main__': > a = QApplication (sys.argv) > mywidget = Optimizer() > a.setMainWidget (mywidget) > mywidget.show() > Update_StatusLine(mywidget) > mywidget.setStartconfig() > a.exec_loop () I don't see any QPaintDevice here. Where does that come from? You need to give more information, a stack trace and a reduced example exhibiting the behaviour. Diez From stephan.diehl at gmx.net Fri Feb 9 06:00:07 2007 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Fri, 09 Feb 2007 12:00:07 +0100 Subject: A little more advanced for loop In-Reply-To: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> References: <1171018313.633380.84200@p10g2000cwp.googlegroups.com> Message-ID: Horta wrote: > Hi folks, > > Suppose I have to loop over 3 lists being the same size at the same > time and order. How can I do that without using the range() function > or whatever indexing? > > Example using range: > > a = ['aaa', 'aaaa'] > b = ['bb', 'bbbb'] > c = ['c', 'cccc'] > > for i in range(len(a)): > # using a[i], b[i], and c[i] > > I'm sure there's a elegant way to do that... > > Thanks in advance. > Sure, there is: for a_item, b_item , c_item in zip(a,b,c): # do something From attn.steven.kuo at gmail.com Wed Feb 28 21:04:23 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 28 Feb 2007 18:04:23 -0800 Subject: text wrapping help In-Reply-To: <1172713806.477177.207440@s48g2000cws.googlegroups.com> References: <1172707568.201788.284590@a75g2000cwd.googlegroups.com> <1172712476.946180.63140@t69g2000cwt.googlegroups.com> <1172713806.477177.207440@s48g2000cws.googlegroups.com> Message-ID: <1172714663.426013.68210@q2g2000cwa.googlegroups.com> On Feb 28, 5:50 pm, "Ryan K" wrote: > On Feb 28, 8:27 pm, attn.steven.... at gmail.com wrote: > > > Try: > > > import re > > sample_text = """Personal firewall software may warn about the > > connection IDLE makes to its subprocess using this computer's internal > > loopback interface. This connection is not visible on any external > > interface and no data is sent to or received from the Internet.""" > > > # assume 24 is sufficiently wide: > > > lines = map(lambda x: x.rstrip(), > > re.findall(r'.{1,24}(?:(?<=\S)\s|$)', sample_text.replace("\n", " "))) > > > print "\n".join(lines) > > > -- > > Hope this helps, > > Steven > > That works great but I need to replace the newlines with 24-(the index > of the \n) spaces. > Just left-justify to the appropriate width with the the padding character you wanted: equally_long_lines = map(lambda x: x.ljust(24, ' '), lines) print "\n".join(equally_long_lines) -- Hope this helps, Steven From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Feb 16 12:43:04 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 16 Feb 2007 18:43:04 +0100 Subject: why I don't like range/xrange References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: <53m8p8F1sf1i1U1@mid.individual.net> stdazi wrote: > Many times I was suggested to use xrange and range instead of the > while constructs, and indeed, they are quite more elegant - but, > after calculating the overhead (and losen flexibility) when > working with range/xrange, and while loops, you get to the > conclusion that it isn't really worth using range/xrange loops. How did you calculate that? > b) xrange long int overflow : > > for i in xrange(0, 1 << len(S)) : > ........ > OverflowError: long int too large to convert to int Why do you bit shift a len result here? Just to get a huge number? Try the same with C. You'd get an integer overflow in the first place. But this long int => int issue should not exist in a future python version any more, IIRC int and long int is scheduled to be merged somehow. (Or isn't it?) Regards, Bj?rn -- BOFH excuse #203: Write-only-memory subsystem too slow for this machine. Contact your local dealer. From attn.steven.kuo at gmail.com Wed Feb 21 21:50:20 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 21 Feb 2007 18:50:20 -0800 Subject: Bug in time module - %z works in perl, not in python? In-Reply-To: <1172110679.681182.128350@j27g2000cwj.googlegroups.com> References: <1172110679.681182.128350@j27g2000cwj.googlegroups.com> Message-ID: <1172112620.868130.139560@p10g2000cwp.googlegroups.com> On Feb 21, 6:17 pm, bwooste... at gmail.com wrote: > Following python code prints out incorrect UTC Offset - the python > docs say that %z is not fully supported on all platforms - but on > Linux Fedora FC5, perl code works and python does not - is this a bug > or is this expected behavior? For a EST timezone setup, Perl prints > correct -0500, while Python prints +0000 - this is Python 2.4. > > Perl: > $now_string = strftime "%Y-%m-%d %H:%M:%S %Z%z", localtime; > print $now_string, "(iso local)\n"; > > 2007-02-21 21:16:16 EST-0500 (iso localtime, perl) > > Python: > now_string = time.strftime("%Y-%m-%d %H:%M:%S %Z%z", time.localtime()) > print now_string, " (iso localtime, python)" > > 2007-02-21 21:15:58 EST+0000 (iso localtime, python) > > Is this expected behavior, or a bug? Seems to be a bug. I can duplicate the problem here (Python 2.4.3, Red Hat Desktop release 4). I do see the correct output, however, if I pass just the format string to strftime: >>> print time.strftime("%Y-%m-%d %H:%M:%S %Z %z") 2007-02-21 18:42:03 PST -0800 >>> print time.strftime("%Y-%m-%d %H:%M:%S %Z %z", time.localtime()) 2007-02-21 18:42:11 PST +0000 -- Hope this helps, Steven From elgrandchignon at gmail.com Mon Feb 26 22:01:02 2007 From: elgrandchignon at gmail.com (elgrandchignon at gmail.com) Date: 26 Feb 2007 19:01:02 -0800 Subject: Probably somewhat silly newbie question In-Reply-To: References: <1172544257.686173.180650@p10g2000cwp.googlegroups.com> Message-ID: <1172545262.069372.16960@h3g2000cwc.googlegroups.com> On Feb 26, 6:57 pm, James Stroud wrote: > elgrandchig... at gmail.com wrote: > > Hi all-- > > > Trying to learn Python w/little more than hobbyist (bordering on pro/ > > am, I guess) Perl as a background. > > > My problem is, I have a list of departments, in this instance, things > > like "Cheese", "Bakery", et al. (I work @ a co-op health food store). > > I've populated a list, 'depts', w/these, so that their indexes match > > our internal indexing (which skips a few #'s). > > > Now, I'd like to simply generate-- and be able to refer to-- a bunch > > of other lists-sets (for subdepartments) by iterating through this > > list, and naming each of these subdepartment lists "categoryx", where > > x is the index # from the master 'depts' list. And then be able to > > populate & refer to these lists by accessing their variable-including > > name. > > > In Perl, it's a fairly trivial matter to use a string variable in > > naming some other kind of variable-- not sure about Python though. My > > initial, very weak stab at it (don't laugh!) went something like this: > > > for i in range(len(depts)): > > if depts[i]: > > categorylistdeptname = 'category' + str(i) > > categorylistdeptname = [] > > > Not sure what that wound up doing, but it sure didn't seem to work. > > First, your are rebinding categorylistdeptname in the loop every time. > > But you probably want a dict (in python 2.4 or later): > > deptdict = dict((dept, []) for dept in depts)) > > And this gets what you want, believe it or not. > > Now you can populate each list: > > deptdict['Bakery'].append("Donuts") > deptdict['Bulk'].extend(["Granola", "Rasins"]) > > And work witht the lists by name: > > for item in deptdict['Bulk']: > print item > # prints "Granola", "Rasins", etc. > > James Thanks so much James! I'll give that method a shot. From deets at nospam.web.de Wed Feb 7 13:06:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Feb 2007 19:06:14 +0100 Subject: Why doesn't my heapify work? References: Message-ID: <52uiomF1olkevU1@mid.uni-berlin.de> Dongsheng Ruan wrote: > I want to turn an Array into a heap, but my code just doesn't work: no > change after execution. > > A=[3,5,4,9,6,7] > m=len(A)-1 > > > > for i in range(m,1): > t=(i-1)/2 > if A[i]>A[t]: > A[i],A[t]=A[t],A[i] First of all, there is the module heapq that will just do it. And then you seem to misunderstand how the range-function works. range(m, 1) will always be the empty list. See pydoc range for how it operates. Overall, your code is very unpythonic, to say the least. I suggest you start reading the python tutorial first: http://docs.python.org/tut/ Especially the looping techniques section: http://docs.python.org/tut/node7.html#SECTION007600000000000000000 Diez From rds1226 at sh163.net Thu Feb 22 19:12:27 2007 From: rds1226 at sh163.net (John) Date: Thu, 22 Feb 2007 19:12:27 -0500 Subject: What is the best queue implemetation in Python? Message-ID: I want to write a code for Breadth First Traveral for Graph, which needs a queue to implement. I wonder that for such a powerful language as Python, whether there is a better and simpler implementation for a traditional FIFO queue? Thanks! From michele.simionato at gmail.com Thu Feb 8 07:59:17 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Feb 2007 04:59:17 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: References: <45C9A137.8090009@v.loewis.de> <52vtc4F1pngrdU1@mid.individual.net> Message-ID: <1170939556.975052.128930@a34g2000cwb.googlegroups.com> On Feb 8, 1:04 pm, s... at pobox.com wrote: > greg> When I want to do this, usually I define the parts as ordinary, > greg> separate classes, and then define the main class as inheriting > greg> from all of them. > > Agreed. Maybe it's just my feeble brain, but I find this the most > compelling (and easy to understand) use for multiple inheritance by far. > > Skip That is a common design, but I don't like it, since it becomes very easy to get classes with dozens of methods inherited from everywhere, a modern incarnation of the spaghetti-code concept. I find it much better to use composition, i.e. to encapsulate the various behaviors in different objects and to add them as attributes. In other words, instead of a flat class namespace with hundreds of methods, I prefer a hierarchical namespace, a class with few attributes, which in turns have their own attributes, and so on. In other words, nested is better than flatten ;) Michele Simionato P.S. Of course I mean situations where the methods can be meaningfully grouped together, which I find is the most common case. From horpner at yahoo.com Fri Feb 2 09:41:14 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Feb 2007 15:41:14 +0100 Subject: Writing "pythonish" code References: Message-ID: On 2007-02-02, Toby A Inkster wrote: > Mizipzor wrote: >> One thing is that in c++ im used to have private members in >> classes and no member is altered except through the public >> functions of the class. > > By convention, class members starting with a single underscore > are considered private. An important consideration is that this convention is simply a lower level of enforcement than C++ provides. Private members in C++ are accessible if you use pointers. > Class members starting with a double underscore are "mangled" > which makes it more difficult for other code (even subclasses!) > to access the member. Difficult though -- not impossible. I think it's best to never use such names in new code. Python's mangling is troubled, since it uses unqualified names in the mangle, resulting in ambiguity. -- Neil Cerutti Ushers will eat latecomers. --Church Bulletin Blooper From n.emami at gmail.com Tue Feb 27 07:35:10 2007 From: n.emami at gmail.com (Nader) Date: 27 Feb 2007 04:35:10 -0800 Subject: installing "pysqlite" In-Reply-To: <1172576685.560386.306740@m58g2000cwm.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> Message-ID: <1172579710.514139.103170@s48g2000cws.googlegroups.com> On Feb 27, 12:44 pm, "Paul Boddie" wrote: > On 27 Feb, 10:31, Nader Emami wrote: > > > I have installed "TurboGears" and I would install 'pysqlite' also. I am > > a user on a Linux machine. If I try to install the 'pysqlite' with > > 'easy_install' tool I get the next error message. The error message is > > longer than what I send here. > > [...] > > > src/connection.h:33:21: sqlite3.h: No such file or directory > > [...] > > > Could somebody tell me what I have to do to install 'pysqlite'? > > Install SQLite, perhaps? If the pysqlite build process can't find > sqlite3.h then you either don't have SQLite installed, or you don't > have the headers for SQLite installed. I'd recommend that you check > your installed packages for the SQLite libraries (eg. libsqlite3-0 on > Ubuntu) and/or the user interface (eg. sqlite3) and for the > development package (eg. libsqlite3-dev). > > If you can't install the packages, install SQLite from source (seehttp://www.sqlite.org/) and try and persuade pysqlite to use your own > SQLite installation - there's a setup.cfg file in the pysqlite > distribution which may need to be changed to achieve this, but I don't > know how that interacts with setuptools. > > Paul Thank for your reaction. I don't know also how the interaction sith 'easy_install' is. I think that I have to install 'pysqlite' from source code also, because i can change ther the 'setup.cfg' file and I can give there where the 'libsqlie3' is. Nader From uval at rz.uni-karlsruhe.de Thu Feb 15 03:16:55 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 15 Feb 2007 09:16:55 +0100 Subject: builtin set literal In-Reply-To: <1171505873.114289.226190@v33g2000cwv.googlegroups.com> References: <1171505873.114289.226190@v33g2000cwv.googlegroups.com> Message-ID: faulkner schrieb: > On Feb 14, 11:55 am, Sch?le Daniel wrote: >> Hello, >> >> lst = list((1,2,3)) >> lst = [1,2,3] >> >> t = tupel((1,2,3)) >> t = (1,2,3) >> >> s = set((1,2,3)) >> s = ... >> >> it would be nice feature to have builtin literal for set type >> maybe in P3 .. what about? >> s = <1,2,3> >> >> Regards, Daniel > > sets aren't quite that useful or common. just use a list. > and '<' and '>' already have syntactic meanings. well, I thought about this the empty set <> has the meaning of != now as far as I remember is <> depricated and will disappear When they are gone in P3000, <> could be reused as empty set. > and that would make python look more like C++, which nobody wants. I dont think that actually many people fear this. we have {} for dicts and I doubt anybody mistake them for C++ brakets. In my previuos post I forgot to mention d = dict() d = {} s = set() s = <> why not, on the first sight everybody will see ... here our algorithmus deals with unique things/objects ... put in a set. Regards, Daniel From mail at timgolden.me.uk Wed Feb 28 16:16:28 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 28 Feb 2007 21:16:28 +0000 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> Message-ID: <45E5F12C.4030200@timgolden.me.uk> [... re getting free disk space ...] Sick Monkey wrote: > Here you are: > > >>> from win32com.client import GetObject >>>> wmiObj = GetObject("winmgmts:\\\\MGW01641\\root\\cimv2") >>>> diskinfo = wmiObj.ExecQuery("Select * from Win32_LogicalDisk") >>>> for disk in diskinfo: > ... print disk.Name, disk.FreeSpace > ... > A: None > C: 16978259968 > D: None >>>> Well it's not often someone beats me to a WMI solution :) Just to be different, you can also look at the GetDiskFreeSpace function in the win32api module of the pywin32 extensions. The doc says: """ tuple = GetDiskFreeSpace(rootPath) Retrieves information about the specified disk, including the amount of free space available. Parameters rootPath : string Specifies the root directory of the disk to return information about. If rootPath is None, the method uses the root of the current directory. Win32 API References Search for GetDiskFreeSpace at msdn, google or google groups. Return Value The return value is a tuple of 4 integers, containing the number of sectors per cluster, the number of bytes per sector, the total number of free clusters on the disk and the total number of clusters on the disk. If the function fails, an error is returned. """ TJG From Bulkan at gmail.com Wed Feb 21 22:25:38 2007 From: Bulkan at gmail.com (placid) Date: 21 Feb 2007 19:25:38 -0800 Subject: getting a thread out of sleep In-Reply-To: References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> <1172098070.913952.20730@h3g2000cwc.googlegroups.com> <1172103051.070952.182060@q2g2000cwa.googlegroups.com> Message-ID: <1172114738.832487.193750@v33g2000cwv.googlegroups.com> On Feb 22, 12:08 pm, mark wrote: > On 21 Feb 2007 16:10:51 -0800, placid wrote: > > > On Feb 22, 10:20 am, mark wrote: > > > On 21 Feb 2007 14:47:50 -0800, placid wrote: > > > > > On Feb 22, 3:23 am, mark wrote: > > > > > On 20 Feb 2007 21:26:18 -0800, placid wrote: > > > > > > > On Feb 21, 4:21 pm, "placid" wrote: > > > > > > > On Feb 21, 4:12 pm, mark wrote: > > > > > > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > > > > > > On Feb 21, 3:08 pm, mark wrote: > > > > > > > > > > Right now I have a thread that sleeps for sometime and check if an > > > > > > > > > > event has happened and go back to sleep. Now instead I want the thread > > > > > > > > > > to sleep until the event has occured process the event and go back to sleep > > > > > > > > > > > class eventhndler(threading.Thread): > > > > > > > > > > def __init__(self): > > > > > > > > > > threading.Thread.__init__(self) > > > > > > > > > > def run(self): > > > > > > > > > > while True: > > > > > > > > > > time.sleep(SLEEPTIME) > > > > > > > > > > ''''do event stuff''' > > > > > > > > > > The way i would do this is by using an threading.Event ( > > > > > > > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > > > > > > > > > > > > > class eventhandler(threading.Thread): > > > > > > > > > def __init__(self): > > > > > > > > > threading.Thread.__init__(self) > > > > > > > > > self.event = threading.Event() > > > > > > > > > def run: > > > > > > > > > while True: > > > > > > > > > # block until some event happens > > > > > > > > > self.event.wait() > > > > > > > > > """ do stuff here """ > > > > > > > > > self.event.clear() > > > > > > > > > > > > > > > > > > > the way to use this is to get the main/separate thread to set() the > > > > > > > > > event object. > > > > > > > > > Can you give an example of how to get the main threead to set teh event object? > > > > > > > > this is exactly what i wanted to do! > > > > > > > > thanks a lot! > > > > > > > > mark> > > > > > > oops I've miss-typed the thread variable name the following should > > > > > > work > > > > > > > > > > > > > if __name__ == "__main__": > > > > > > evtHandlerThread = eventhandler() > > > > > > evtHandlerThread.start() > > > > > > > # do something here # > > > > > > evtHandlerThread.event.set() > > > > > > > # do more stuff here # > > > > > > evtHandlerThread.event.set() > > > > > > > > > > > > > Can I have the same thread process two or more events? Can you tell > > > > > how to do this? The code you gave is waiting on one event right. How > > > > > can I do it for more events? > > > > > thanks a lot! > > > > > mark > > > > > I don't think a thread can block on more than one event at a time. But > > > > you can make it block on more then one event one at a time. > > > > > > > > > > class eventhandler(threading.Thread): > > > > def __init__(self): > > > > threading.Thread.__init__(self) > > > > self.events = [threading.Event(), threading.Event()] > > > > self.currentEvent = None > > > > def run: > > > > while True: > > > > for event in self.events: > > > > self.currentEvent = event > > > > # block until some event happens > > > > self.currentEvent.wait() > > > > """ do stuff here """ > > > > self.currentEvent.clear() > > > > > if __name__ == "__main__": > > > > evtHandlerThread = eventhandler() > > > > evtHandlerThread.start() > > > > > # do something here # > > > > evtHandlerThread.currentEvent.set() > > > > > # do more stuff here # > > > > evtHandlerThread.currentEvent.set() > > > > > > > > > > what the thread does is sequentially waits for two events to happen > > > > and then execute the same code. You could change this code to perform > > > > different functions for different event objects. > > > > Once the thread starts it is going to wait on the event that is the > > > first element of the list right? This would mean : > > > This is correct. > > > > evtHandlerThread.currentEvent.set(): that I have only one event right? > > > this means that the current event occurred. > > > > Can you explain how I can have different event objects. I dont see how > > > I can do different functinos for same event. > > > > Thanks a lot! > > > > mark > > > To run different functions for the same event is easy, just write a > > wrapper class around threading.event() and include some method that > > you will run and assign this to different functions for each > > EventWrapper. > > > > > > class EventWrapper(): > > def __init__(self,work ): > > self.event = threading.Event() > > self.eventWork = work > > > def wait(self): > > self.event.wait() > > > def clear(self) > > self.event.clear() > > > def eventWork(self): > > print "no work" > > > class eventhandler(threading.Thread): > > def __init__(self, events = None): > > threading.Thread.__init__(self) > > self.events = events > > self.currentEvent = None > > def run: > > while True: > > if self.events: > > for event in self.events: > > self.currentEvent = event > > # block until the current event happens > > self.currentEvent.wait() > > self.currentEvent.eventWork() > > self.currentEvent.clear() > > > def eventOneWork(): > > # do some event 1 specific work here > > > def eventTwoWork(): > > # do some event 2 specific work here > > > if __name__ == "__main__": > > events = [EventWrapper(eventOneWork),EventWrapper(eventTwoWork)] > > > evtHandlerThread = eventhandler(events) > > evtHandlerThread.start() > > > # do something here # > > evtHandlerThread.currentEvent.set() > > # do more stuff here # > > evtHandlerThread.currentEvent.set() > > > > > > So you have a EventWrapper class that now contains the Event object > > and a workEvent() method which is assigned to a function you create. > > THanks a lot! Does this have to have event1 and event2 occur in > sequence? Will this still work even if only event2 occurs and event1 > never occurs? > thanks > mark well if event1 never occurs then it will block/wait until forever and even if event2 has occurred you never know about it until event1 occurs. You can introduce a timeout to the wait() call on the event object which says, "block X seconds or until event happens (someone calls the set method)" so even if event1 doesnt occur you will execute event1.eventWork() because the timeout occurred. The way to fix this is before you call the eventWork() method check if the event has occurred via the isSet() method of Event objects. http://docs.python.org/lib/event-objects.html Cheers From mensanator at aol.com Mon Feb 5 20:27:21 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 5 Feb 2007 17:27:21 -0800 Subject: Decimating Excel files In-Reply-To: References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> Message-ID: <1170725241.634632.100830@v45g2000cwv.googlegroups.com> On Feb 5, 5:46 pm, "Gabriel Genellina" wrote: > En Sat, 03 Feb 2007 18:52:10 -0300, mensana... at aol.com > escribi?: > > > On Feb 3, 1:43?pm, gonzlobo wrote: > >> We have a data acquisition program that saves its output to Excel's > >> .xls format. Unfortunately, the programmer was too stupid to write > >> files the average user can read. > > >> I'd like some advice on how to go about: > >> 1. Reading a large Excel file and chop it into many Excel files (with > >> only 65535 lines per file) > > > An Excel sheet only has 65535 lines. Or do yo mean it has > > multiple sheets? > > As I understand the problem, the OP has a program that generates the .xls > files, but it's so dumb that writes files too large for Excel to read. My first thought was how would that be possible? But then, nothing's stopping someone from making a million line .csv file (which Excel thinks it "owns") that would be too big for Excel to open. If that's the case, then chasing COM is barking up the wrong tree. > I'd try the "xlrd" package - it is capable of reading Excel files on any > platform. > > -- > Gabriel Genellina From ccurvey at gmail.com Thu Feb 1 14:24:13 2007 From: ccurvey at gmail.com (Chris Curvey) Date: 1 Feb 2007 11:24:13 -0800 Subject: how to make a python windows service know it's own identity In-Reply-To: <45C23B18.5050000@websafe.com> References: <1170264160.124454.6270@j27g2000cwj.googlegroups.com> <45C23B18.5050000@websafe.com> Message-ID: <1170357853.916290.252460@v33g2000cwv.googlegroups.com> On Feb 1, 2:10 pm, Larry Bates wrote: > Chris Curvey wrote: > > Hi all, > > > I have used the win32com libraries to set up a service called > > MyService under Windows. So far, so good. Now I need to run multiple > > copies of the service on the same machine. I also have that working. > > For monitoring and logging, I'd like each instance of the service to > > know it's own identity (MyService1, MyService2, etc.) > > > But I can't quite seem to grasp how to do this. In the code below, > > the command line parameter "-i" gives the service an identity, but how > > do I get the service to understand it's identity when it is started? > > > Many thanks! > > > class MyService(win32serviceutil.ServiceFramework): > > """NT Service.""" > > > _svc_name_ = "MyService" > > _svc_display_name_ = "My Service" > > > _id_ = '' > > > def SvcDoRun(self): > > provider = MyServiceClass(identifier=self._id_) > > provider.start() > > > # now, block until our event is set... > > win32event.WaitForSingleObject(self.stop_event, > > win32event.INFINITE) > > > # __init__ and SvcStop snipped > > > ########################################################################### > > if __name__ == '__main__': > > import optparse > > parser = optparse.OptionParser() > > parser.add_option("-i", "--identifier", dest="identifier") > > (opts, args) = parser.parse_args() > > if opts.number is not None: > > MyService._svc_name_ += opts.identifier > > MyService._svc_display_name_ += opts.identifier > > MyService._provider_id_ = opts.identifier > > > win32serviceutil.HandleCommandLine(MyService, > > customInstallOptions="i:") > > What is your use case for this? Why not make a single server > process multiple providers (store them in a list or other > container)? > > -Larry Bates The use case is that I have a queue of jobs that need to run. My service connects to a central "distributor" server, which hands out jobs to complete. I'd like to be able to run multiple copies of the distributed service so that I can make the most use of each machine where they run. (I'm not certain of the thread safety of some of the libraries I'm using, so I'm leery of going the multi-threaded route) Anyway, when my service gets a job to process, I'd like to know which copy of the service is working on which job. So I want my log messages to look like this: Job 123: Host: alpha Service: MyService A Job 124: Host: alpha Service: MyService B Job 124: Host: beta Service: MyService C Is that clear, or have I muddied the waters? From bj_666 at gmx.net Sat Feb 17 13:09:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 17 Feb 2007 19:09:13 +0100 Subject: WHAT IS THIS? References: Message-ID: In , James Stroud wrote: > Better would be to remove windows xp and get another operating system. Yeah XP is sooo ooold, the OP should install Vista. Or did you mean a real OS instead of just another one? ;-) SCNR, Marc 'BlackJack' Rintsch From bearophileHUGS at lycos.com Wed Feb 14 08:51:40 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Feb 2007 05:51:40 -0800 Subject: replacing substrings within strings In-Reply-To: <53ghdgF1slkirU1@mid.uni-berlin.de> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> <53gcsbF1sbe8oU1@mid.uni-berlin.de> <1171456059.848396.42270@m58g2000cwm.googlegroups.com> <53ghdgF1slkirU1@mid.uni-berlin.de> Message-ID: <1171461100.321811.96180@h3g2000cwc.googlegroups.com> Diez B. Roggisch: > That's the price to pay for immutable strings. Right, but CPython has array.array("c") too. Using Diez Roggisch's code: >>> from array import array >>> arrs = array("c", "010203040506") >>> arrs[:2], arrs[4:5] = arrs[4:6], arrs[:2] >>> arrs.tostring() '0302013040506' Using such arrays is useful if you have to do lot of processing before the final tostring(). Bye, bearophile From danb_83 at yahoo.com Mon Feb 26 23:00:53 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Feb 2007 20:00:53 -0800 Subject: Is type object an instance or class? In-Reply-To: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> References: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> Message-ID: <1172548853.781960.64180@t69g2000cwt.googlegroups.com> On Feb 26, 8:00 pm, "JH" wrote: > Hi > > I found that a type/class are both a subclass and a instance of base > type "object". > > It conflicts to my understanding that: > > 1.) a type/class object is created from class statement > 2.) a instance is created by "calling" a class object. > > A object should not be both a class and an instance at the same time. > > Further I found out there is a special type call "type" that is a > subclass of base type "object". All other types are instances of this > type. Even base type "object" is an instance of this special type. Yes. Python has a much broader definition of "object" than say, Java does. Functions are objects. Modules are objects. And most relevant here, types are objects. So "int" and even "object" are objects, and they have type "type". Confusing, I know, but perfectly logical. From __peter__ at web.de Mon Feb 19 06:54:14 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 12:54:14 +0100 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <1171883522.303348.121760@l53g2000cwa.googlegroups.com> Message-ID: Jay Tee wrote: > On Feb 19, 11:07 am, Peter Otten <__pete... at web.de> wrote: > >> Use a RDBMS (a database), they tend to be good at this kind of >> operations. > > yeah, one of the options is metakit ... sqlite and buzhug both looked > promising but the constraint of pythons 2.2 and 2.3 ruled that out. > disadvantage of metakit is that it's not pure python, meaning possible > integration problems. the system has to be deployed at 200+ sites > worldwide on a mix of RHEL 3 and 4 based systems, with some Debian > clusters thrown in, and running real production ... > > hence my desire to find a pure-python solution if at all possible. > it's looking grim. The following may speed up things a bit if you have enough memory and your data is queried more often than changed. import sys def generate_id(): for i in xrange(sys.maxint): yield i raise ImplementationRestriction get_id = generate_id().next class Record(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) assert not hasattr(self, "_id") self._id = get_id() def __setitem__(self, key, value): raise ImmutableException def __hash__(self): return self._id def __str__(self): items = self.items() items.sort() return ", ".join(["%s: %s" % p for p in items]) records = dict.fromkeys([ Record(user="jack", start=42, state="running"), Record(user="jack", start=47, state="running"), Record(user="jack", start=46, state="queued"), Record(user="jane", start=42, state="running"), Record(user="jane", start=7), ]) def fill_cache(records): cache = {} for record in records: for p in record.iteritems(): cache.setdefault(p, {})[record] = None return cache _cache = fill_cache(records) def select(*data, **kw): [data] = data result = data for p in kw.iteritems(): try: c = _cache[p] except KeyError: c = {} if not c: return {} result = dict.fromkeys([k for k in result if k in c]) if not result: break return result if __name__ == "__main__": for filter in [ dict(user="jack"), dict(state="running"), dict(user="jack", state="running"), dict(state="undefined"), dict(user="jane", state="queued") ]: print "--- %s ---" % Record(filter) result = select(records, **filter) if result: for record in result: print record else: print "#no matching records" print The above code runs with Python 2.3; don't know about 2.2 as I don't have it on my machine. Of course with sets it would look better... Peter From deets at nospam.web.de Sat Feb 3 06:36:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 03 Feb 2007 12:36:54 +0100 Subject: HELP NEEDED ... Regd. Regular expressions PyQt In-Reply-To: References: Message-ID: <52jaemF1oke2rU1@mid.uni-berlin.de> vishal at veriwave.com schrieb: > Hello All: > I am trying to work out a regular expression in a PyQt environment for > time in hh:mm:ss format. Any suggestions? Yes. Read the manual to the re-module. There is _nothing_ special about PyQt and regexes. And provide code. But the most important thing - read this: http://www.catb.org/~esr/faqs/smart-questions.html Diez From paddy3118 at netscape.net Thu Feb 1 00:36:18 2007 From: paddy3118 at netscape.net (Paddy) Date: 31 Jan 2007 21:36:18 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <1170308178.823986.322700@h3g2000cwc.googlegroups.com> On Feb 1, 2:42 am, krypto.wiz... at gmail.com wrote: > How to divide a number by 7 efficiently without using - or / operator. > We can use the bit operators. I was thinking about bit shift operator > but I don't know the correct answer. >>> int.__div__(14,2) 7 >>> Not a minus or division operator in sight ;-) - Paddy. From nagle at animats.com Mon Feb 26 12:03:18 2007 From: nagle at animats.com (John Nagle) Date: Mon, 26 Feb 2007 09:03:18 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: Tech HR wrote: > In article <1172482314.598240.3440 at j27g2000cwj.googlegroups.com>, > dixkey at gmail.com wrote: >>This is more out of curiosity, but does it mean that you wouldn't be >>willing to listen about a switch from Python to Lisp? > > > No, it doesn't mean that. In fact, there is a significant faction in > the technical staff (including the CTO) who would like nothing better > than to be able to use Lisp instead of Python. But we have some pretty > compelling reasons to stick with Python, not least of which is that it > is turning out to be very hard to find Lisp programmers. As someone who knows both languages, I'd stay with Python, although trying to do heavy number crunching in a naive interpreter may be a problem. That's a tough scheduling problem. It took about a year for the NetJets people to develop their application for it. John Nagle From e0225855 at stud4.tuwien.ac.at Fri Feb 9 02:39:06 2007 From: e0225855 at stud4.tuwien.ac.at (Markus Triska) Date: Fri, 09 Feb 2007 08:39:06 +0100 Subject: Overloading the tilde operator? References: <1170924578.362210.242280@a34g2000cwb.googlegroups.com> Message-ID: <87bqk3g4px.fsf@gmx.at> gatti at dsdata.it writes: > Also some flavours of Prolog, as descrived in the classic book by op/3 is part of the Prolog ISO standard: http://pauillac.inria.fr/~deransar/prolog/bips.html#operators so every compliant implementation has it. From robert.kern at gmail.com Wed Feb 14 14:49:26 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 14 Feb 2007 13:49:26 -0600 Subject: try...except...finally problem in Python 2.5 In-Reply-To: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> Message-ID: redawgts wrote: > I keep getting this error "local variable 'f' referenced before > assignment" in the finally block when I run the following code. > > try: > f = file(self.filename, 'rb') > f.seek(DATA_OFFSET) > self.__data = f.read(DATA_SIZE) > self.isDataLoaded = True > except: > self.isDataLoaded = False > finally: > f.close() > > Can someone tell me what's wrong with the code? Am I doing something > wrong? I'm somewhat new to python but this makes sense to me. Move the "f = file(self.filename, 'rb')" above the try:. If opening the file happens to throw an exception, then the assignment will never happen and there will be no 'f' to close. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From B.Ogryczak at gmail.com Fri Feb 16 12:04:33 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 16 Feb 2007 09:04:33 -0800 Subject: output to console and to multiple files In-Reply-To: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> Message-ID: <1171645473.844315.152020@k78g2000cwa.googlegroups.com> On Feb 14, 11:28 pm, "nathan.sh... at gmail.com" wrote: > Hello, > > I searched on Google and in this Google Group, but did not find any > solution to my problem. > > I'm looking for a way to output stdout/stderr (from a subprocess or > spawn) to screen and to at least two different files. > > eg. > stdout/stderr -> screen > stdout -> log.out > stderr -> log.err > > and if possible > stdout/stderr -> screen and log.txt > > 3 files from stdout/stderr I'd derive a class from file, overwrite it's write() method to send a copy to the log, and then assign sys.stdout = newFile(sys.stdout). Same for stderr. From MonkeeSage at gmail.com Wed Feb 28 16:43:12 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 28 Feb 2007 13:43:12 -0800 Subject: Yet another unique() function... In-Reply-To: <1172697024.754286.325450@m58g2000cwm.googlegroups.com> References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <1172647505.784091.193710@q2g2000cwa.googlegroups.com> <7x7iu2niif.fsf@ruckus.brouhaha.com> <1172697024.754286.325450@m58g2000cwm.googlegroups.com> Message-ID: <1172698992.142640.55250@z35g2000cwz.googlegroups.com> Paul, In your case optimized version, in the second try clause using itertools, it should be like this, shouldn't it? return t(g.next()[1] for k,g in groupby(s, lambda (i,v): v)) ^^^ Regards, Jordan From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 14 17:00:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 14 Feb 2007 23:00:48 +0100 Subject: swf format verification? References: <1171489359.975911.222280@j27g2000cwj.googlegroups.com> Message-ID: <53hf4gF1rf12kU1@mid.individual.net> akonsu wrote: > hello, can someone recommend a good library to verify whether a > file is in swf format (and ideally flv as well)? i need it to > enable file uploading on to my web site. Look how GNU "file" does it: #------------------------------------------------------------------------------ # flash: file(1) magic for Macromedia Flash file format # # See # # http://www.macromedia.com/software/flash/open/ # 0 string FWS Macromedia Flash data, >3 byte x version %d 0 string CWS Macromedia Flash data (compressed), >3 byte x version %d # From: Cal Peake 0 string FLV Macromedia Flash Video # # From Dave Wilson 0 string AGD4\xbe\xb8\xbb\xcb\x00 Macromedia Freehand 9 Document Regards, Bj?rn -- BOFH excuse #346: Your/our computer(s) had suffered a memory leak, and we are waiting for them to be topped up. From gagsl-py at yahoo.com.ar Fri Feb 16 05:08:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Feb 2007 07:08:32 -0300 Subject: I'm faint why this can't work References: Message-ID: En Fri, 16 Feb 2007 05:27:46 -0300, escribi?: >> I got this similar sample script from books: >> $ cat sampdict.py >> #!/usr/bin/python >> class SampDict(dict): >> def __init__(self, filename=None): >> self["name"] = filename > > >> Are you sure you copied it exactly as it appears? Where did you find >> it? > Thank you for the help,Gabriel. Sorry, I was wrong. The code as it is (with the right indentation, of course) should work OK. Maybe, you were playing in the interpreter, and you wrote some test class and called it "dict"? Inadvertedly hiding the dict builtin. Try again, it must work... > The codes got by me from the book of "Dive into Python".The original A good book! -- Gabriel Genellina From http Thu Feb 8 13:44:01 2007 From: http (Paul Rubin) Date: 08 Feb 2007 10:44:01 -0800 Subject: Functions, parameters References: Message-ID: <7xzm7obiby.fsf@ruckus.brouhaha.com> Boris Ozegovic writes: > >>> Poll.objects.filter(question__startswith='What') > > This 'question__startswith' is the problem. What is the common idiom for > this type od arguments, so I can Google it? You can refer to function args in Python by name, e.g. define a function def print_power(x, y): print x ** y and you can pass the parameters in by position, like in most languages: print_power(5, 2) # prints "25" You can also pass them by name, saying explicitly which arg is which (called "keyword arguments"): print_power(x=5, y=2) # also prints "25" print_power(y=5, x=2) # prints "32" You can make functions that take arbitrary named parameters. The ** below means that arg gets bound to a dictionary containing all the keyword args: def func(**keyword_args): print 'args are:' for k in keyword_args: print k, '=>', keyword_args[k] func(a=2, b=5, c='whee') prints: a => 2 b => 5 c => whee From jjl at pobox.com Tue Feb 27 20:34:30 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 28 Feb 2007 01:34:30 GMT Subject: Is there a technic to avoid this bug References: <54inn6F2115doU1@mid.uni-berlin.de> Message-ID: <873b4rjc9j.fsf@pobox.com> "Diez B. Roggisch" writes: > hg wrote: [...] > > In a relatively similar domain, I spent a few hours find this bug: > > > > value == self.Get_Value() > > if value == WHATEVER: > > do this > > > > instead of > > value = self.Get_Value() > > if value == WHATEVER: > > do this > > > > Is there a way to avoid such a bug with some type of construct ? > > No. In a language inherent with sideeffects, there is nothing that should > force you to not write that. [...] It's illegal in C#: // -------- compare.cs ---------- class BadComparison { static void Main() { 1 == 2; } } // -------- end ----------------- $ mcs compare.cs compare.cs(3,9): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement Compilation failed: 1 error(s), 0 warnings csharp[0]$ // -------- compare2.cs ---------- class BadComparison { static void Main() { bool falsehood = 1 == 2; } } // -------- end ----------------- $ mcs compare2.cs compare2.cs(3,14): warning CS0219: The variable `falsehood' is assigned but its value is never used Compilation succeeded - 1 warning(s) John From http Sun Feb 25 12:44:01 2007 From: http (Paul Rubin) Date: 25 Feb 2007 09:44:01 -0800 Subject: Find the first element that meets the condition References: <1172397176.024303.257890@t69g2000cwt.googlegroups.com> Message-ID: <7xbqjii13y.fsf@ruckus.brouhaha.com> "jm.suresh at no.spam.gmail.com" writes: > I have a list and I want to find the first element that meets a > condition. I do not want to use 'filter', because I want to come out > of the iteration as soon as the first element is found. > I have implemented it this way, may be, there should be a built in > hiding somewhere in the standard libraries? > > def exists(iterable, condition): To check for existence, use any(condition, iterable). If you actually want the first element, use itertools.ifilter(condition, iterable).next(). The suggestion of using dropwhile isn't so great because it actually consumes the first match, so you have to write your condition to stop immediately before the element you want, not always easy. From jeff at jmcneil.net Mon Feb 26 16:52:45 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Mon, 26 Feb 2007 16:52:45 -0500 Subject: Walk thru each subdirectory from a top directory In-Reply-To: <2adc542f0702261342r7f3a8ff8gffc6e30356c792de@mail.gmail.com> References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <2adc542f0702261342r7f3a8ff8gffc6e30356c792de@mail.gmail.com> Message-ID: <8559DF97-9809-438F-98BD-8EED512CBDE8@jmcneil.net> Isn't this something that os.walk would be good for? import os for t in os.walk(base_dir): for f in t[2]: print "/".join((t[0], f)) Jeff On Feb 26, 2007, at 4:42 PM, Sick Monkey wrote: > I had a do something similar. I had to get a program to traverse > through a directory and delete all files with a specific file > extension. (The program below will delete files, so I do not > recommend you running it without paying close attention to it.) > > This program will start at a given directory and will traverse thru > the subdirectories by using "listdir". > +++++++++++++++++++++++++++++++++++ > #!/usr/bin/python -u > > import sys, time > from os import listdir, unlink > from os.path import isdir, isfile, islink, join, getmtime > deldir = "C:\some\Dir" > delFileType = ".txt" > # ------------------------------------- > def del_entry(_name): > try: > if isdir(_name): > print "This is a directory, do nothing." > else: > #print "now" > unlink(_name) # or remove(_name) > sys.stdout.write("Delete FILE %s\n" % (_name)) > except IOError: > sys.stderr.write("Cannot delete %s\n" % (_name)) > # ------------------------------------- > def list_dir(_dir,_action): > if not isdir(_dir): > print "%s is not a directory" % (_dir) > return > > for file in listdir(_dir): > path = join(_dir, file) > if isdir(path): > list_dir(path, _action) > else: > if path.rfind(delFileType) != -1: > #print path > _action(path) > # ------------------------------------- > # Run it > list_dir(deldir, del_entry) > > On 26 Feb 2007 13:28:20 -0800, silverburgh.meryl at gmail.com > wrote: > > i am trying to use python to walk thru each subdirectory from a top > directory. Here is my script: > > savedPagesDirectory = "/home/meryl/saved_pages/data" > > dir=open(savedPagesDirectory, 'r') > > for file in dir: > if (isdir(file)): > # get the full path of the file > fileName = savedPagesDirectory + file + 'index.html' > print fileName > > $ ./scripts/regressionTest.py > Traceback (most recent call last): > File "./scripts/regressionTest.py", line 12, in ? > dir=open(savedPagesDirectory, 'r') > IOError: [Errno 21] Is a directory > > But I get the above error: > > Can you please tell me what did I do wrong? > > Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Wed Feb 14 03:44:42 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Feb 2007 00:44:42 -0800 Subject: Fast constant functions for Py2.5's defaultdict() In-Reply-To: <1171440696.431692.10110@q2g2000cwa.googlegroups.com> References: <1171393305.268249.268580@q2g2000cwa.googlegroups.com> <1171440696.431692.10110@q2g2000cwa.googlegroups.com> Message-ID: <1171442682.323305.266950@s48g2000cws.googlegroups.com> On Feb 14, 9:11 am, "Raymond Hettinger" wrote: > On Feb 13, 5:09 pm, Giovanni Bajo wrote: > > > > The itertools.repeat(const).next approach wins on speed and > > > flexibility. > > > But it's the most unreadable too. > > Not really. It's unusual but plenty readable (no surprise that > repeat(0) repeatedly gives you zero). I think it more surprising that > int() with no arguments gives you a zero. Well, if I was doing code review of some of my coworkers I would ask them to use them int if the constant was zero and lambda otherwise. If they wanted to use itertools.repeat(const).next they should prove me that the speed increase is absolutely significant in their actual use case and they should put a big comment in the code explaining why they preferred the cryptic defaultdict(itertools.repeat(0).next) over the obvious defaultdict(int). Michele Simionato From nospam at riddergarn.dk Tue Feb 13 08:17:27 2007 From: nospam at riddergarn.dk (NOSPAM plz) Date: Tue, 13 Feb 2007 14:17:27 +0100 Subject: Regex highlight html In-Reply-To: <45D1B976.3080704@riddergarn.dk> References: <45D1B976.3080704@riddergarn.dk> Message-ID: <45D1BA67.8040903@riddergarn.dk> An HTML attachment was scrubbed... URL: From B.Ogryczak at gmail.com Thu Feb 1 05:21:35 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 1 Feb 2007 02:21:35 -0800 Subject: SWIG overhead Message-ID: <1170325295.575450.84340@s48g2000cws.googlegroups.com> Hi, I?m looking for some benchmarks comparing SWIG generated modules with modules made directly with C/Python API. Just how much overhead does SWIG give? Doing profile of my code I see, that it spends quiet some time in functions like _swig_setattr_nondinamic, _swig_setattr, _swig_getattr. From ggg at zzz.it Sat Feb 17 15:33:44 2007 From: ggg at zzz.it (deelan) Date: Sat, 17 Feb 2007 21:33:44 +0100 Subject: Getting a class name In-Reply-To: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> Message-ID: <_DJBh.20322$K8.18088@news.edisontel.com> Harlin Seritt wrote: > Hi, > > How does one get the name of a class from within the class code? I > tried something like this as a guess: > > self.__name__ Get the class first, then inspect its name: >>> class Foo(object): pass ... >>> f = Foo() >>> f.__class__.__name__ 'Foo' >>> HTH -- d. From Michel.Al1 at gmail.com Thu Feb 8 14:48:07 2007 From: Michel.Al1 at gmail.com (k0mp) Date: 8 Feb 2007 11:48:07 -0800 Subject: begin to parse a web page not entirely downloaded In-Reply-To: <45cb73b0$0$6842$4d3efbfe@news.sover.net> References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> <45cb63d4$0$6842$4d3efbfe@news.sover.net> <1170958856.700750.3080@a75g2000cwd.googlegroups.com> <45cb73b0$0$6842$4d3efbfe@news.sover.net> Message-ID: <1170964087.032675.181180@l53g2000cwa.googlegroups.com> On Feb 8, 8:02 pm, Leif K-Brooks wrote: > k0mp wrote: > > It seems to take more time when I use read(size) than just read. > > I think in both case urllib.openurl retrieve the whole page. > > Google's home page is very small, so it's not really a great test of > that. Here's a test downloading the first 512 bytes of an Ubuntu ISO > (beware of wrap): > > $ python -m timeit -n1 -r1 "import urllib" > "urllib.urlopen('http://ubuntu.cs.utah.edu/releases/6.06/ubuntu-6.06.1-desktop-i386.is...)" > 1 loops, best of 1: 596 msec per loop OK, you convince me. The fact that I haven't got better results in my test with read(512) must be because what takes most of the time is the response time of the server, not the data transfer on the network. From S.Mientki-nospam at mailbox.kun.nl Sat Feb 17 17:44:34 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 17 Feb 2007 23:44:34 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <53nt2aF1sn581U1@mid.uni-berlin.de> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> <53nt2aF1sn581U1@mid.uni-berlin.de> Message-ID: >> - designing the GUI will cost me about 2 .. 3 times as much in Python > > You mean delphi here I presume? No, but if that's your believe .. Some examples: - Creating a treeview (like in the M$ explorer), with full edit capabilities and full drag & drop facilities: Delphi takes about 40 lines of code (most of them even ^C ^V). - Creating a graphical overview of relations between database tables, which can be graphical manipulated by the user (like in M$ Access): Delphi 20 lines of code. I wonder what this costs in Python ? >> - Python is not capable of doing everything I need >> (almost all interactive actions are very primitive and crashes a lot) > > I'm not sure what you are talking about here, and I have the deep > impression you yourself don't as well. I'm not an (educated) programmer, so I don't always use the right terms :-( If I look at a well established program like DIA, and see that it still can't repaint it's screen always correctly, ... If I just look at MathPlotLib ;-) But I also know one beautiful program based on wx: KICAD. > > Matter of factly, there is no "the python GUI". There are quite a few > choices. The built-in tkinter, which - while limited in some senses - is > developed by Frederik Lundh, and while I personally haven't done too > much with it, his reputation as one of the most high profiled python > developers doesn't go along pretty well with your assertions above. So > -whatever you used as GUI-toolkit, you either used it wrong, or it > really wasn't good. > > But then there are at least three major other toolkits available, wx, > gtk and Qt. The first two I've only dabbled a bit with and can't comment > on. > > But I've done extensive, cross-platform development with Qt. And can > assert that it is unmatched in productivity and feature richness, > especially when combined with python. And certainly beat VB, and most > probably even delphi (albeit I haven't done too much in that to really > put all my weight behind these words). > > And so I'm under the strong impression that your - undoubtedly correct > from a personal point of view, and I don't think your meaning evil here > - observations are wrong and are based on a lack of experience in python > and it's available gui-options. I've been using Python for just 2 months, and didn't try any graphical design, I've other priorities first. I would love to see: - a comparison between wx and gtk (QT doesn't have a very inviting license ;-) - some Python applications that uses one of these graphical libraries. To give you an impression of some features I'm after, I've prepared an animation (not completely ready yet), of the program I've written in Delphi, with both embedded MatLab and embedded Python, where MatLab or Python does all the real-time numerical analysis. http://oase.uci.kun.nl/~mientki/download/medilab_tot.htm Writing this program, including teaching myself Python (with a lot of help of this group, thank you all !!), and writing the bloodpressure analysis in both MatLab and Python, excluding the ADC-drivers, costed me about 150 .. 200 hours ... ... can that be done be an experienced programmer in Python. cheers, Stef Mientki From bdesth.quelquechose at free.quelquepart.fr Mon Feb 19 16:12:51 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Feb 2007 22:12:51 +0100 Subject: How to call a function defined in another py file In-Reply-To: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> References: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> Message-ID: <45da0b4e$0$10413$426a34cc@news.free.fr> silverburgh.meryl at gmail.com a ?crit : > Hi, > > I have a function called 'test' defined in A.py. > How can I call that function test in my another file B.py? > > Thank you. > # b.py import A A.test() From dimitri.pater at gmail.com Wed Feb 7 18:49:53 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 8 Feb 2007 00:49:53 +0100 Subject: Python editor In-Reply-To: <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> <1170851197.656670.179590@a75g2000cwd.googlegroups.com> <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> Message-ID: > > I read about a free manual with adds, > but I can find it no-where. you can find a tutorial here : http://www.serpia.org/spe You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From ah at hatzis.de Mon Feb 12 07:56:48 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Mon, 12 Feb 2007 13:56:48 +0100 Subject: Progress when parsing a large file with SAX In-Reply-To: <53b0r2F1rqg29U1@mid.uni-berlin.de> References: <1171277000.671586.191250@q2g2000cwa.googlegroups.com> <53b0r2F1rqg29U1@mid.uni-berlin.de> Message-ID: <45D06410.5060706@hatzis.de> Diez B. Roggisch wrote: ... I got the same problem with large XML as Marc. So you deserve also my thanks for the example. :-) > class PercentageFile(object): > > def __init__(self, filename): > self.size = os.stat(filename)[6] > self.delivered = 0 > self.f = file(filename) > > def read(self, size=None): > if size is None: > self.delivered = self.size > return self.f.read() > data = self.f.read(size) > self.delivered += len(data) > return data > I guess some client impl need to call read() on a wrapped xml file until all portions of the file are read. > @property > def percentage(self): > return float(self.delivered) / self.size * 100.0 > @property? What is that supposed to do? Anastasios From jgrzebyta at NO.gazeta.pl.SPAM Tue Feb 6 16:21:46 2007 From: jgrzebyta at NO.gazeta.pl.SPAM (Jacol) Date: Tue, 06 Feb 2007 21:21:46 +0000 Subject: Dlaczego ten destruktor nie dziala [_LONG_] References: <20070204170503.4dbb1b14.sulsa@gazeta.pl> Message-ID: >> self.__class__.__bases__[0].__del__(self) >> Swoj? drog? to nie masz lito?ci pisz?c co? takiego ;) From bignose+hates-spam at benfinney.id.au Fri Feb 16 06:06:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Feb 2007 22:06:09 +1100 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <87fy965plq.fsf@benfinney.id.au> "Gabriel Genellina" writes: > (And I would expect that making a connection to "localhost" actually > does *not* go down up to the network card hardware layer, but I > don't know for real if this is the case or not). It damned well better. That's the entire point of the loopback interface: to get all the network layer code involved, but not to talk on a physical network interface. If a programmer decides on behalf of the user that "localhost" should be treated specially, that programmer is making an error. -- \ "If you can't beat them, arrange to have them beaten." -- | `\ George Carlin | _o__) | Ben Finney From wolf_tracks at invalid.com Thu Feb 8 12:27:25 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 08 Feb 2007 17:27:25 GMT Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> Robert Kern wrote: > W. Watson wrote: > >> I did a search in the python24 folder for sys.exec* (in c:\python24), but >> came up with nothing. [nothing in a search of c:--sys.exec*] I have two >> python folders, c:\python24 and c:\python25. The contents of both folders >> look fairly similar and each have a python.exe. I do not use a PIL or >> Numeric in 2.5. > > I'm sorry. sys is a module. I meant for you to execute the following Python code: > > import sys > print sys.executable > I'm savvy about a number of languages, but not yet about Python. What py file will allow this to be executed? main myprog { import sys print sys.executable pause } ?? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two million years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From pythonnews at nospam.jmbc.fr Mon Feb 5 10:53:59 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Mon, 05 Feb 2007 16:53:59 +0100 Subject: wxPython: TextCtrl delayed update when using TE_RICH(2) In-Reply-To: References: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> <45c5aa41$0$21142$7a628cd7@news.club-internet.fr> Message-ID: <45c7533d$0$21148$7a628cd7@news.club-internet.fr> >> For this kind of stuff, I'd try to put "self.out.WriteText(string)" in >> some 'Idle' event, which avoid to fall in focus loops or other objects >> events management problems not easy to solve. >> > > This doesn't have anything to do with focus loops or otherwise, it's > because the OP isn't familiar with event based programming. > > You're performing a long-running task which is preventing the event > loop from processing, so your text isn't updating and your application > is unresponsive. You need to rewrite your task - either do everything > asynchronously, or use a threaded approach. If you use the thread > approach, be sure to not call the updates directly, you can use the > wx.CallAfter mechanism to call gui functions in a threadsafe manner. So it is an event management problem. The event loop is not yet finished when the program want to display something, potentially initiating a new event loop. If you don't want to bother with threads, the idle event approach is not so bad. Put something to display in a buffer, and display it only one time the gui have nothing else to do. I use it every time I can, and it's very safe and easy to do. Furthermore, you can still step into the program with a debugger, which can be tricky if the program uses threads (I'd say impossible, but I didn't try in fact). Regards jm From cito at online.de Sun Feb 11 16:25:03 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 11 Feb 2007 22:25:03 +0100 Subject: Problem with reimporting modules In-Reply-To: References: <1171209111.551190.146590@a34g2000cwb.googlegroups.com> Message-ID: Thanks for the detailed explanations, Gabriel. > At that time, all values in the module namespace are set to > None (for breaking possible cycles, I presume). print_hello now has a > func_globals with all names set to None. (Perhaps the names could have > been deleted instead, so print_hello() would raise a NameError, but I'm > just describing the current CPython implementation) Yes, that was the thing that confused me a bit. I had expected that an error is raised or that the namespace has a reference to the module and is reestablished when the module has been reloaded. Anyway, I have solved the problem in a different way now. -- Christoph From gagsl-py at yahoo.com.ar Thu Feb 1 18:16:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 20:16:47 -0300 Subject: python executing windows exe References: <1170370679.244079.275530@h3g2000cwc.googlegroups.com> Message-ID: En Thu, 01 Feb 2007 19:57:59 -0300, Kiran escribi?: > I am making python run an executable using the os module. Here is > my question. The executable, once it is running, asks the user to > input a filename that it will process. Now, my question is how do i > automate this. let me make this clear, it is not an argument you pass > in when you type in the exe. An example below illustrates: You can use the subprocess module, or any of the Popen2 variants. Usually they work fine - but depending on how the application behaves, it may not work. -- Gabriel Genellina From thebrasse at brasse.org Tue Feb 27 17:49:32 2007 From: thebrasse at brasse.org (=?iso-8859-1?B?TWF0dGlhcyBCcuRuZHN0cvZt?=) Date: 27 Feb 2007 14:49:32 -0800 Subject: Vector, matrix, normalize, rotate. What package? Message-ID: <1172616572.045690.17550@k78g2000cwa.googlegroups.com> Hello! I'm trying to find what package I should use if I want to: 1. Create 3d vectors. 2. Normalize those vectors. 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in radians. 4. Perform matrix multiplication. It seems to me that perhaps numpy should be able to help me with this. However, I can only figure out how to do 1 and 4 using numpy. Meybe someone knows a way to use numpy for 2 and 3? If not, what Python package helps me with geometry related tasks such as 2 and 3? Any help here would be greatly appreciated! Regards, Mattias From jeremit0 at gmail.com Wed Feb 7 13:58:00 2007 From: jeremit0 at gmail.com (jeremito) Date: 7 Feb 2007 10:58:00 -0800 Subject: How can I use __setitem__ method of dict object? In-Reply-To: References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> <1170795607.938431.144340@p10g2000cwp.googlegroups.com> <45c8f5b5$0$19714$426a74cc@news.free.fr> <1170854927.013819.320020@a75g2000cwd.googlegroups.com> <1170860862.438897.244820@a75g2000cwd.googlegroups.com> Message-ID: <1170874679.984807.245730@l53g2000cwa.googlegroups.com> On Feb 7, 12:48 pm, Jussi Salmela wrote: > jeremito kirjoitti: > > > On Feb 7, 8:28 am, "jeremito" wrote: > >> On Feb 6, 5:10 pm, Bruno Desthuilliers > > >> wrote: > >>> jeremito a ?crit : > >>> > On Feb 6, 2:36 pm, Bruno Desthuilliers > wrote: > >>> (snip) > >>> >>Here's an alternative implementation, so you get the idea. > >>> >>class Xs(dict): > >>> oops ! I meant: > >>> class Xs(object): > >>> of course... > >>> (snip) > >>>> I guess I just > >>>> need more experience. > >>> Possibly - but not only. You may want to have a look at the > >>> FineManual(tm) for all this kind of "magic", starting with :http://docs.python.org/ref/specialnames.htmlhttp://docs.python.org/re... > >>> HTH > >> Thanks again! Sometimes the problem is simply not knowing where to > >> find the documentation, or finding the right portion of the > >> documentation. Your help has been invaluable. > > >> Jeremy > > > One more question. I will be asking for the value of cs.xT *many* > > (~millions) times. Therefore I don't want it's value to be calculated > > on the fly. How can I set the value of xT whenever xS, xF, or xG are > > changed, but not allow it to be set directly? From the example given > > previously, it seems like it can't be done this way. > > > Thans, > > Jeremy > > I'm certainly no wizard in timing, but here goes: > > Using the class definition given to you by Bruno, adding the following > to the end (and 'import timeit' at the start): > > #============ > lst = timeit.Timer('for i in xrange(10): xx=xs.xT', \ > 'from __main__ import Xs;xs = Xs()').repeat(100,1000) > lst.sort() > print lst > print 'Average:', sum(lst)/100 > #============ > > I get the output: > [0.017246605364648282, 0.01727426251101738, 0.017275659336591698, > 0.017290745052793044, 0.01733264982001903, 0.017347735536220377, > > and so on ... > > 0.029063749722380933, 0.029163762433493667, 0.029422733894950315, > 0.029790378386079785] > Average: 0.0182474979362 > > Thus: A 1000 assignments take a little over 18 milliseconds. The largest > values in the list are probably caused bu GC occurring. But even 30 ms / > 1000 iterations i.e. 30 microseconds per fetch seems to be fast enough. > > All this depends of course on the computer used. Mine is on the fast > side, you might test it on your PC. > > The correct way of programming is to find a good simple algorithm and > the data structures needed, to program a clean solution with them and > then when you've got a correctly operating application and THEN IF you > need speed try to do something about it. > > "Premature optimization is the worst evil" or something like that is how > the saying goes. > > Hopefully I'm not leading you astray by being a novice in using the > timeit module. > > HTH, > Jussi Thank you. Once again this mailing list has proven most helpful. I realize it probably isn't worth my time (or stress) to figure out how to avoid calculating xT on the fly-at least not yet. Jeremy From ayaz at dev.slash.null Mon Feb 5 14:52:51 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Tue, 06 Feb 2007 00:52:51 +0500 Subject: Missing member References: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> <1170644122.385780.299920@v33g2000cwv.googlegroups.com> Message-ID: "Paul McGuire" typed: > Here's a suggestion: use new-style classes. Have _BaseEntity inherit > from object, allows you to use super for invoking methods on super > classes. Instead of: > class Entity(_BaseEntity): > def __init__(self, type, x = 0, y = 0): > _BaseEntity.__init__(self, type, x, y) > > You enter: > class Entity(_BaseEntity): > def __init__(self, type, x = 0, y = 0): > super(Entity,self).__init__(type, x, y) > > This makes it easier to update your inheritance hierarchy later. New- > style classes have other benefits too. I am still a beginner to Python, but reading that made me think on impluse, "What happens in case of one class inheriting from two or more different classes?" Having written a small test case and testing it, I find that super().__init__() calls the __init__() of the first of the class in the list of classes from which the calling class inherits. For example: class C(A, B): def __init__(self): super(C, self).__init__() calls A's __init__ explicity when an instance of C is instantiated. I might be missing something. I didn't know that. -- Ayaz Ahmed Khan A witty saying proves nothing, but saying something pointless gets people's attention. From carsten at uniqsys.com Fri Feb 16 09:20:00 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 16 Feb 2007 09:20:00 -0500 Subject: Regex - where do I make a mistake? In-Reply-To: <1171632895.567625.129290@l53g2000cwa.googlegroups.com> References: <1171629872.499083.150140@p10g2000cwp.googlegroups.com> <1171632895.567625.129290@l53g2000cwa.googlegroups.com> Message-ID: <1171635600.3395.28.camel@dot.uniqsys.com> On Fri, 2007-02-16 at 05:34 -0800, Johny wrote: > On Feb 16, 2:14 pm, Peter Otten <__pete... at web.de> wrote: > > Johny wrote: > > > I have > > > string="""55. > > > 128 > > > 170 > > > """ > > > > > where I need to replace > > > 55. > > > 170 > > > > > by space. > > > So I tried > > > > > ############# > > > import re > > > string="""55. > > class="test123">128170 > > > """ > > > Newstring=re.sub(r'.*'," ",string) > > > ########### > > > > > But it does NOT work. > > > Can anyone explain why? > > > > "(?!123)" is a negative "lookahead assertion", i. e. it ensures that "test" > > is not followed by "123", but /doesn't/ consume any characters. For your > > regex to match "test" must be /immediately/ followed by a '"'. > > > > Regular expressions are too lowlevel to use on HTML directly. Go with > > BeautifulSoup instead of trying to fix the above. > > > Yes, I know "(?!123)" is a negative "lookahead assertion", > but do not know excatly why it does not work. It *does* work, it just doesn't do what you think it does. The lookahead assertion is a zero-width match that doesn't match any actual characters from the subject. It matches an imaginary vertical line between two consecutive characters of the subject. Nothing in your pattern matches the string of digits that follows "test", hence the subject fails to match the pattern. Also, please note Peter's advice that Regular Expressions are almost always the wrong tool for working with HTML. It may work in very limited cases, and maybe you have such a limited case, but you'd better make sure that you'll never ever have to handle anything beyond this limited case. -Carsten From irmen.NOSPAM at xs4all.nl Thu Feb 1 19:55:49 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 02 Feb 2007 01:55:49 +0100 Subject: Calculating future dates In-Reply-To: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> References: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> Message-ID: <45c28c3a$0$338$e4fe514c@news.xs4all.nl> Toine wrote: > Hello, > > I'm new to Python so please bare with me... > > I need to calculate a date that is exactly 31 days from the current > date in YYYY-MM-DD format. I know that date.today() returns the > current date, but how can I add 31 days to this result? I'm sure this > task is simple, but I haven't been able to figure it out. >>> import datetime >>> print datetime.date.today()+datetime.timedelta(days=31) 2007-03-05 >>> ---Irmen From john at doe.com Sat Feb 24 10:29:48 2007 From: john at doe.com (John Doe) Date: Sat, 24 Feb 2007 15:29:48 GMT Subject: arf Message-ID: arf From grante at visi.com Thu Feb 8 11:57:07 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Feb 2007 16:57:07 -0000 Subject: help on packet format for tcp/ip programming References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> <12sl6tuhkla8ob2@corp.supernews.com> <1170944844.977214.57350@s48g2000cws.googlegroups.com> Message-ID: <12smlj3quct0228@corp.supernews.com> On 2007-02-08, rattan at cps.cmich.edu wrote: > On Feb 8, 3:40 am, Grant Edwards wrote: >> On 2007-02-08, rat... at cps.cmich.edu wrote: >> >> > struct module pack and unpack will only work for fixed size buffer : >> > pack('>1024sIL', buffer, count. offset) but the buffer size can vary >> > from one packet to the next :-( >> >> Oh for Pete's sake... >> >> struct.pack('>%dsIL' % len(buffer), buffer, count, offset) > > that is great but how does one unpack on the other side? struct.unpack('>%dsIL' % buflen ,packet) -- Grant Edwards grante Yow! Yow! Did something at bad happen or am I in a visi.com drive-in movie?? From steve at REMOVEME.cybersource.com.au Mon Feb 12 01:23:14 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 12 Feb 2007 17:23:14 +1100 Subject: string.replace non-ascii characters References: Message-ID: On Mon, 12 Feb 2007 03:01:55 -0300, Gabriel Genellina wrote: > En Mon, 12 Feb 2007 02:38:29 -0300, Samuel Karl Peterson > escribi?: > > Sorry to steal the thread! This is only related to your signature: > >> "if programmers were paid to remove code instead of adding it, >> software would be much better" -- unknown > > I just did that last week. Around 250 useless lines removed from a 1000 > lines module. [snip] Hot out of uni, my first programming job was assisting a consultant who was writing an application in Apple's "Hypertalk", a so-called "fourth generation language" with an English-like syntax, aimed at non-programmers. Virtually the first thing I did was refactor part of his code that looked something like this: set the name of button id 1 to 1 set the name of button id 2 to 2 set the name of button id 3 to 3 ... set the name of button id 399 to 399 set the name of button id 400 to 400 into something like this: for i = 1 to 400: set the name of button id i to i -- Steven D'Aprano From __peter__ at web.de Tue Feb 13 08:31:03 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Feb 2007 14:31:03 +0100 Subject: Lazy container References: Message-ID: Cristiano Paris wrote: > I'm trying to write a Container which should mimic a list. Basically, > the container pulls items on the fly from an unspecified source through > a function and returns an instance of a given class over the pulled item. > > That is: > > class lazy(object): > def __getitem__(self,index): > return Foo(f(index)) > > lc = lazy() > > Here I see a problem: two consecutive accesses to lc for the same index > would retrieve two different instances of Foo. > > In some scenarios this is not desirable since one wants to have all the > accessors to share the same instance for the same index so as to reduce > memory consumption. > > So, I thought to use an internal dictionary of all the Foo instances > given away so far. Something like: > The problem with this implementation is that the cache never decreases > in length as Foo instances are no longer referenced by the lc accessor > since they're all referenced by the internal cache. You want a WeakValueDictionary: http://docs.python.org/lib/module-weakref.html Peter From george.sakkis at gmail.com Sat Feb 17 17:30:11 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 17 Feb 2007 14:30:11 -0800 Subject: Complex HTML forms Message-ID: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> I'd like to gather advice and links to any existing solutions (e.g. libraries, frameworks, design patterns) on general ways of writing complex web forms, as opposed to the typical {name:value} flat model. A particular case of what I mean by complex is hierarchical forms. For instance, a form that consists of a select list widget, where each item of the list activates a distinct set of other widgets. Think for example of a web frontend to CSV or SVN options and commands, where each command has its own suboptions. The suboptions are hidden (or even inexistent) until the user selects the specific command, and only then they appear (typically by Javascript). When the form is submitted, the selected options are passed in the server in some form that preserves the hierarchy, i.e. not as a flat dict. Is there anything close to such a beast around ? George From Bulkan at gmail.com Wed Feb 21 19:10:51 2007 From: Bulkan at gmail.com (placid) Date: 21 Feb 2007 16:10:51 -0800 Subject: getting a thread out of sleep In-Reply-To: References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> <1172098070.913952.20730@h3g2000cwc.googlegroups.com> Message-ID: <1172103051.070952.182060@q2g2000cwa.googlegroups.com> On Feb 22, 10:20 am, mark wrote: > On 21 Feb 2007 14:47:50 -0800, placid wrote: > > > > > On Feb 22, 3:23 am, mark wrote: > > > On 20 Feb 2007 21:26:18 -0800, placid wrote: > > > > > On Feb 21, 4:21 pm, "placid" wrote: > > > > > On Feb 21, 4:12 pm, mark wrote: > > > > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > > > > On Feb 21, 3:08 pm, mark wrote: > > > > > > > > Right now I have a thread that sleeps for sometime and check if an > > > > > > > > event has happened and go back to sleep. Now instead I want the thread > > > > > > > > to sleep until the event has occured process the event and go back to sleep > > > > > > > > > class eventhndler(threading.Thread): > > > > > > > > def __init__(self): > > > > > > > > threading.Thread.__init__(self) > > > > > > > > def run(self): > > > > > > > > while True: > > > > > > > > time.sleep(SLEEPTIME) > > > > > > > > ''''do event stuff''' > > > > > > > > The way i would do this is by using an threading.Event ( > > > > > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > > > > > > > > > class eventhandler(threading.Thread): > > > > > > > def __init__(self): > > > > > > > threading.Thread.__init__(self) > > > > > > > self.event = threading.Event() > > > > > > > def run: > > > > > > > while True: > > > > > > > # block until some event happens > > > > > > > self.event.wait() > > > > > > > """ do stuff here """ > > > > > > > self.event.clear() > > > > > > > > > > > > > > > the way to use this is to get the main/separate thread to set() the > > > > > > > event object. > > > > > > > Can you give an example of how to get the main threead to set teh event object? > > > > > > this is exactly what i wanted to do! > > > > > > thanks a lot! > > > > > > mark> > > > > oops I've miss-typed the thread variable name the following should > > > > work > > > > > > > > > if __name__ == "__main__": > > > > evtHandlerThread = eventhandler() > > > > evtHandlerThread.start() > > > > > # do something here # > > > > evtHandlerThread.event.set() > > > > > # do more stuff here # > > > > evtHandlerThread.event.set() > > > > > > > > > Can I have the same thread process two or more events? Can you tell > > > how to do this? The code you gave is waiting on one event right. How > > > can I do it for more events? > > > thanks a lot! > > > mark > > > I don't think a thread can block on more than one event at a time. But > > you can make it block on more then one event one at a time. > > > > > > class eventhandler(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > self.events = [threading.Event(), threading.Event()] > > self.currentEvent = None > > def run: > > while True: > > for event in self.events: > > self.currentEvent = event > > # block until some event happens > > self.currentEvent.wait() > > """ do stuff here """ > > self.currentEvent.clear() > > > if __name__ == "__main__": > > evtHandlerThread = eventhandler() > > evtHandlerThread.start() > > > # do something here # > > evtHandlerThread.currentEvent.set() > > > # do more stuff here # > > evtHandlerThread.currentEvent.set() > > > > > > what the thread does is sequentially waits for two events to happen > > and then execute the same code. You could change this code to perform > > different functions for different event objects. > > Once the thread starts it is going to wait on the event that is the > first element of the list right? This would mean : This is correct. > evtHandlerThread.currentEvent.set(): that I have only one event right? this means that the current event occurred. > Can you explain how I can have different event objects. I dont see how > I can do different functinos for same event. > > Thanks a lot! > > mark To run different functions for the same event is easy, just write a wrapper class around threading.event() and include some method that you will run and assign this to different functions for each EventWrapper. class EventWrapper(): def __init__(self,work ): self.event = threading.Event() self.eventWork = work def wait(self): self.event.wait() def clear(self) self.event.clear() def eventWork(self): print "no work" class eventhandler(threading.Thread): def __init__(self, events = None): threading.Thread.__init__(self) self.events = events self.currentEvent = None def run: while True: if self.events: for event in self.events: self.currentEvent = event # block until the current event happens self.currentEvent.wait() self.currentEvent.eventWork() self.currentEvent.clear() def eventOneWork(): # do some event 1 specific work here def eventTwoWork(): # do some event 2 specific work here if __name__ == "__main__": events = [EventWrapper(eventOneWork),EventWrapper(eventTwoWork)] evtHandlerThread = eventhandler(events) evtHandlerThread.start() # do something here # evtHandlerThread.currentEvent.set() # do more stuff here # evtHandlerThread.currentEvent.set() So you have a EventWrapper class that now contains the Event object and a workEvent() method which is assigned to a function you create. Hope this helps. Cheers From casevh at comcast.net Fri Feb 23 18:44:38 2007 From: casevh at comcast.net (casevh at comcast.net) Date: 23 Feb 2007 15:44:38 -0800 Subject: Rational numbers In-Reply-To: <1172273227.863743.155210@p10g2000cwp.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> Message-ID: <1172274278.169015.79910@z35g2000cwz.googlegroups.com> On Feb 23, 3:27 pm, alea... at gmail.com wrote: > On Feb 23, 12:00 pm, cas... at comcast.net wrote: > ... > > > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of > > > > cvs 10 months ago). > > > I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by > > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex > > has not updated cvs with the fix. > > Heh, I see why one might get that impression -- I'm in the process of > moving gmpy from sourceforge (where I find it harder and harder, and > ever more problematic, to work) to code.google.com 's new hosting > facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and > particularly including your fix, Case) is already available athttp://code.google.com/p/gmpy/but I have made no official > announcement yet (partly because what's available is yet limited: > sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX > 10.4 on Macs with intel processors)... building binaries for Windows > (not having a Windows machine or development system) or Universal > binaries for the Mac (due to problems building Universal versions of > the underlying GMP in its latest, 4.2 incarnation... I'm running out > of PPC-based Macs, and have none left with MaxOSX 10.3...) is much > more problematic for me. > > To call this (Google Code) release 1.02, with a "1.04" (?) out from > another source, may be confusing, but I'd rather not "force" the > number upwards > > I do have one new co-owner on the Google Code "version" of gmpy (Chip > Turner, once author of a similar GMP wrapper for perl, now a Python > convert and a colleague of mine) but I suspect that won't make the > building of Windows (and Universal Mac) binaries much easier. If > anybody who has easy access to Microsoft's MSVC++.NET (and is willing > to try building GMP 4.2 with/for it), or a PPC Mac with XCode > installed (possibly with MacOSX 10.3...), wants to volunteer to build > "the missing binaries" for the platforms that the current owners of > gmpy can't easily support, we could complete, test and release the > definitive 1.02, and move on with the development (I could get > enthusiastic about this again, if I could develop just the sources, > and the binaries for the one architecture I really use -- Macs w/intel > -- rather than strive each time with binaries for architectures that > are quite a pain for me...!-). > > Anybody who's interested in helping out is welcome to mail me and/or > use the "wiki" and "issues" entry of the Google Code gmpy site... > > Thanks, > > Alex I can keep building gmpy for Windows. I actually use MINGW since getting GMP compiled under MSVC is "challanging". I should be able to build new binaries for Windows this weekend. And I would be happy to point everyone to a real release. casevh From george.sakkis at gmail.com Mon Feb 19 23:15:47 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 19 Feb 2007 20:15:47 -0800 Subject: exec "def.." in globals(), locals() does not work In-Reply-To: <1171943563.164204.313540@p10g2000cwp.googlegroups.com> References: <1171943563.164204.313540@p10g2000cwp.googlegroups.com> Message-ID: <1171944946.967005.86810@v33g2000cwv.googlegroups.com> On Feb 19, 10:52 pm, xml0... at yahoo.com wrote: > How do I use exec? Before you ask this question, the one you should have an answer for is "why do I (think I) have to use exec ?". At least for the example you gave, you don't; Python supports local functions and nested scopes, with no need for exec: from math import * G = 1 def d(): L = 1 def f(x): return L + log(G) return f(1) >python -V > Python 2.4.3 > > ---- > from math import * > G = 1 > def d(): > L = 1 > exec "def f(x): return L + log(G) " in globals(), locals() > f(1) > ---- > > How do I use exec() such that: > 1. A function defined in exec is available to the local scope (after > exec returns) > 2. The defined function f has access to globals (G and log(x) from > math) > 3. The defined function f has access to locals (L) > > So far I have only been able to get 2 out of the 3 requirements. > It seems that exec "..." in locals(), globals() only uses the first > listed scope. > > Bottomline: > exec "..." in globals(), locals(), gets me 1. and 3. > exec "..." in locals(), globals() gets me 1. and 2. > exec "..." in hand-merged copy of the globals and locals dictionaries > gets me 2. and 3. > > How do I get 1. 2. and 3.? L is local in d() only. As far as f() is concerned, L,G and log are all globals, only x is local (which you don't use; is this a typo?). If you insist on using exec (which, again, you have no reason to for this example), take the union of d's globals and locals as f's globals, and store f in d's locals(): from math import * G = 1 def d(): L = 1 g = dict(globals()) g.update(locals()) exec "def f(x): return L + log(G) " in g, locals() return f(1) George From g950101 at gmail.com Wed Feb 14 22:01:02 2007 From: g950101 at gmail.com (g950101 at gmail.com) Date: 14 Feb 2007 19:01:02 -0800 Subject: A problem of using pyfort Message-ID: <1171508458.876894.17290@s48g2000cws.googlegroups.com> Hi, I faced some problems during using pyfort. The log for installing pyfort is attached: running install running build running build_py running build_scripts copying pyfort -> build/scripts-2.4 changing mode of build/scripts-2.4/pyfort from 644 to 755 running install_lib running install_scripts copying build/scripts-2.4/pyfort -> /usr/bin changing mode of /usr/bin/pyfort to 755 Pyfort Version 8.5.3 It seems to be no errors. However, It cannot work perfectly while applying on the demo. The message is shown as: g77 Wrote project file pyfdemo.pfp Building project pyfdemo.pfp minusg = project_name = pyfdemo command = install fortran_compiler_id = g77 outdir = Reading pyfdemo.pfp Building Pyfort module pyfdemo Generating documentation file Generating Pyfort interface in /root/Pyfort-8.5.3/build/ pyfort_pyfdemo Your extension has been generated in /root/Pyfort-8.5.3/build/ pyfort_pyfdemo. Executing setup install using these arguments: version = '8.5.3' External module specified by: libraries = ['g2c'] sources = ['/root/Pyfort-8.5.3/build/pyfort_pyfdemo/ pyfdemomodule.c'] library_dirs = [] name = 'pyfdemo' name = 'pyfdemo_extension' extra_path = 'pyfdemo_dir' --------------------------------- running install running build running build_ext building 'pyfdemo' extension creating build/temp.linux-i686-2.4 creating build/temp.linux-i686-2.4/root creating build/temp.linux-i686-2.4/root/Pyfort-8.5.3 creating build/temp.linux-i686-2.4/root/Pyfort-8.5.3/build creating build/temp.linux-i686-2.4/root/Pyfort-8.5.3/build/ pyfort_pyfdemo gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,- D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer- size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables - D_GNU_SOURCE -fPIC -fPIC -I/usr/include/python2.4 -c /root/ Pyfort-8.5.3/build/pyfort_pyfdemo/pyfdemomodule.c -o build/temp.linux- i686-2.4/root/Pyfort-8.5.3/build/pyfort_pyfdemo/pyfdemomodule.o /root/Pyfort-8.5.3/build/pyfort_pyfdemo/pyfdemomodule.c:50: warning: 'set_transposed_strides' defined but not used /root/Pyfort-8.5.3/build/pyfort_pyfdemo/pyfdemomodule.c:187: warning: 'do_array_inout' defined but not used /root/Pyfort-8.5.3/build/pyfort_pyfdemo/pyfdemomodule.c:212: warning: 'do_array_create' defined but not used creating build/lib.linux-i686-2.4 gcc -pthread -shared build/temp.linux-i686-2.4/root/Pyfort-8.5.3/build/ pyfort_pyfdemo/pyfdemomodule.o -lg2c -o build/lib.linux-i686-2.4/ pyfdemo.so /usr/bin/ld: cannot find -lg2c collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 I didn't find any solutions via internet. So I really need your help. The OS on my computer is Fedora Core 5. Thanks in advance. From fuzzyman at gmail.com Fri Feb 16 07:31:36 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Feb 2007 04:31:36 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> Message-ID: <1171629096.256958.213180@q2g2000cwa.googlegroups.com> On Feb 16, 11:54 am, "Edward K Ream" wrote: > > In short, if you need to support 2.3, you're not ready to be looking at > > 3.0. > > I hope this turns out not to be true. As a developer, I have no way to > force people to 3.0, and no reason to want to. For me, maintaining two > incompatible code bases is out of the question. > > It will be interesting to see how this plays out. Users, not developers, > will determine when Python 2.x becomes extinct. > As has been mentioned 3.0 will deliberately break backwards compatibilit in a few ways in order to remove cruft and make changes that *can't* be done any other way. That said, the changing of print feels to me like gratutitous breakage - but then I've never had the need to go through old code replacing print with logging code (the need that Guido cites as the reasn for the change). There are various of the 3.0 changes being discussed for inclusion (or at least support) in Python 2.6 so it might be possible to write code that will run unchanged on Python 2.6 and 3.0. (That is *some* code - nt arbitrary code.) There is also the 2to3 converter. The aim is that this will be effective enough that coders should be able to maintain a 2.X (2.6 ?) codebase, run it through 2to3 and have the result run unchanged on Python 3. That way there will be no need to maintain two code bases. Also bear in mind that people using Python 3.0 will be aware that most existing libraries won't work - and it will be a long time (2 to 3 yearsafter the release of 3.0 final ?) before the majority of Python users have switched. This will provide plenty of time for migration patterns and tools to be established. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream... at charter.net > Leo:http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- From gigs at hi.t-com.hr Wed Feb 28 13:15:40 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 28 Feb 2007 19:15:40 +0100 Subject: pyopengl vs directpython In-Reply-To: References: Message-ID: thanks hey, is there any good tutorial for directpython? or maybe you could suggest me the book From bellman at lysator.liu.se Tue Feb 6 03:52:12 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 6 Feb 2007 08:52:12 +0000 (UTC) Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" References: Message-ID: "Gabriel Genellina" wrote: > En Sat, 03 Feb 2007 07:35:22 -0300, Peter Otten <__peter__ at web.de> > escribi?: >> #!/usr/bin/env python2.5 >> >> python2.5 will be that single argument and no options are possible at >> all. >> What might be the reasons for such a seemingly arbitrary limitation? > The shell parses that line, not Python, so you should look into its > documentation. Bzzt! In any modestly recent Unix version (meaning fifteen years old or younger), it has been the kernel that parsed the #! line, not the shell. As for *how* the kernel parses that line, it varies between Unix versions. Linux, at least versions 2.4 and 2.6, takes everything after the interpreter and passes it as a single argument to the interpreter, with leading and trailing whitespace stripped. Thus #! /usr/bin/interpreter foo bar gazonk del will give the parameter "foo bar gazonk del" to the interpreter. SunOS 5.10 (aka Solaris 10) on the other hand, splits the line on whitespace and passes only the first word as parameter, and would thus give only "foo" to the interpreter for the same #! line. I seem to remember having used some Unix flavor that allowed multiple words as arguments, and thus passed the four words "foo", "bar", "gazonk" and "del" as arguments for the above #! line, but I don't remember what Unix that was. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Adde parvum parvo magnus acervus erit" ! bellman @ lysator.liu.se (From The Mythical Man-Month) ! Make Love -- Nicht Wahr! From nathan.shair at gmail.com Fri Feb 16 10:36:29 2007 From: nathan.shair at gmail.com (nathan.shair at gmail.com) Date: 16 Feb 2007 07:36:29 -0800 Subject: output to console and to multiple files In-Reply-To: References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171498259.757320.127100@q2g2000cwa.googlegroups.com> <1171554821.510472.313950@s48g2000cws.googlegroups.com> <1171558306.121792.169430@h3g2000cwc.googlegroups.com> <1171578909.944542.188190@a75g2000cwd.googlegroups.com> Message-ID: <1171640189.520097.119180@l53g2000cwa.googlegroups.com> On Feb 15, 5:48 pm, "Gabriel Genellina" wrote: > En Thu, 15 Feb 2007 19:35:10 -0300, Matimus escribi?: > > > > >> I think you should be able to use my or goodwolf's solution with the > >> subprocess module. Something like this (untested): > > >> [code] > >> class TeeFile(object): > >> def __init__(self,*files): > >> self.files = files > >> def write(self,txt): > >> for fp in self.files: > >> fp.write(txt) > > > I tried this at lunch and it doesn't work. Some version of this method > > may work, but Popen tries to call the 'fileno' method of the TeeFile > > object (at least it did on my setup) and it isn't there. This is just > > a preemptive warning before someone comes back to let me know my code > > doesn't work. > > I don't think any Python only solution could work. The pipe options > available for subprocess are those of the underlying OS, and the OS knows > nothing about Python file objects. > > -- > Gabriel Genellina I've tried the subprocess method before without any luck. Thanks for all your suggestions. I guess it's time to rethink what I want to do. From gagsl-py at yahoo.com.ar Thu Feb 8 20:22:09 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Feb 2007 22:22:09 -0300 Subject: Fwd: Python new user question - file writeline error References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> <1170954351.593141.94290@v33g2000cwv.googlegroups.com> <2dc0c81b0702080920w63b6b323v387c711051913abc@mail.gmail.com> Message-ID: En Thu, 08 Feb 2007 14:20:57 -0300, Shawn Milo escribi?: > On 8 Feb 2007 09:05:51 -0800, Gabriel Genellina > wrote: >> On 8 feb, 12:41, "Shawn Milo" wrote: >> >> > I have come up with something that's working fine. However, I'm fairly >> > new to Python, so I'd really appreciate any suggestions on how this >> > can be made more Pythonic. >> >> A few comments: >> >> You don't need the formatDatePart function; delete it, and replace >> newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) >> with >> newDate = ",%04.4d-%02.2d-%02.2d," % (yearNum,monthNum,dayNum) >> >> and before: >> dayNum, monthNum, yearNum = [int(num) for num in >> someDate[1:-1].split('/')] >> >> And this: outfile.writelines(line) >> should be: outfile.write(line) >> (writelines works almost by accident here). >> >> You forget again to use () to call the close methods: >> infile.close() >> outfile.close() >> >> I don't like the final replace, but for a script like this I think >> it's OK. >> >> -- >> Gabriel Genellina >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > Gabriel, > > Thanks for the comments! The new version is below. I thought it made a > little more sense to format the newDate = ... line the way I have it > below, although I did incorporate your suggestions. Looks pretty good for me! Just one little thing I would change, the variables monthNum, dayNum etc.; the suffix might indicate that they're numbers, but they're strings instead. So I would move the int(...) a few lines above, where the variables are defined. But that's just a cosmetic thing and just a matter of taste. > Also, the > formatting options you provided seemed to specify not only string > padding, but also decimal places, so I changed it. Please let me know > if there is some other meaning behind the way you did it. No, it has no meaning, at least for this range of values. > As for not liking the replace line, what would you suggest instead? You already have scanned the line to find the matching fragment; the match object knows exactly where it begins and ends; so one could replace it with the reformatted value without searching again, wich takes some more time, at least in principle. But this makes the code a bit more complex, and it would only make sense if you were to process millions of lines, and even then, the execution might be I/O-bound so you would gain nothing at the end. That's why I think it's OK as it is now. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Thu Feb 8 15:17:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 21:17:06 +0100 Subject: Functions, parameters In-Reply-To: References: <45cb6def$0$1014$426a74cc@news.free.fr> Message-ID: <45cb7e15$0$26748$426a74cc@news.free.fr> Boris Ozegovic a ?crit : > Bruno Desthuilliers wrote: > > >>Why don't you just read the source code ? Django is free software, you >>know !-) > > Yes, I know. :) > >>What about something like: > > >>def filter(self, **kw): >> for argname, value in kw.items(): >> fieldname, op = argname.split('__', 1) > > > Yes, this is what confused me in the first place: how to separate > arguments. If you call split, and split returns list of String, then you > have fieldname = 'question' and op == 'startswith' > and startwith = 'what', and not references at > question and startwith, or am I missing something big. The reference to 'question' is quite easy to get, since question is an attribute of the Poll class. Usually, one uses getattr(object, name), but IIRC Django model classes have a 'fields' dict (or dict-like) storing attributes describing the DB schema. Getting a reference to str.startswith() would be as easy, but it's not even needed. Remember, all this is used to build the WHERE clause of a SQL query... From GSlusarek at gmail.com Fri Feb 2 06:59:20 2007 From: GSlusarek at gmail.com (Grzegorz Smith) Date: 2 Feb 2007 03:59:20 -0800 Subject: simple SOAP method doesn't work, Message-ID: <1170417560.403995.163390@m58g2000cwm.googlegroups.com> Hi All. I 'm learning ZSI to use SOAP and I desperately need help. I'm working on example from tutorial -> (examples/server/send_response/ simple/wsdl/). Here are my wsdl files -> http://pastebin.com/873488. I made wsdl2py wsdl2py --complexType --file=binding.wsdl and get Example_services.py and Example_Services_types.py. Here is the Example_services.py -> http://pastebin.com/873492 and Example_Services_types.py -> http://pastebin.com/873494 Now I use cgi script for getting request/ sending response. Script is runned by apache2.0. It looks like this: #!c:\opt\python24\python from Example_services import EchoResponse def echo(message): response = EchoResponse() response._Message = message return response from ZSI import dispatch dispatch.AsCGI() Now i write 2 scripts to test my Soap webservices. First is write just like in guide.html from Example_services import * loc = ExampleServiceLocator() port = loc.getExample() req = EchoRequest() req._Message='test' resp = port.echo(req) print resp and I get: Traceback (most recent call last): File "test.py", line 9, in ? resp = port.echo(req) File "I:\Prace\PRYWATNE\test\Example_services.py", line 41, in echo response = self.binding.Receive(typecode) File "I:\Prace\PRYWATNE\test\client.py", line 497, in Receive File "I:\Prace\PRYWATNE\test\client.py", line 397, in ReceiveSOAP File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI \parse.py", line 59, in __init__ File "c:\opt\python24\lib\site-packages\PyXML-0.8.4-py2.4-win32.egg \_xmlplus\dom\ext\reader\__init__.py", line 60, in fromString return self.fromStream(stream, ownerDoc) File "c:\opt\python24\lib\site-packages\PyXML-0.8.4-py2.4-win32.egg \_xmlplus\dom\ext\reader\PyExpat.py", line 65, in f romStream success = self.parser.ParseFile(stream) xml.parsers.expat.ExpatError: unclosed token: line 12, column 152 Second looks like this: import sys from ZSI.client import Binding b = Binding(url='http://127.0.0.1/cgi-bin/cgi.py', tracefile=sys.stdout) print b.echo('test') and i get: _________________________________ Fri Feb 02 13:05:06 2007 REQUEST: test _________________________________ Fri Feb 02 13:05:07 2007 RESPONSE: 200 OK ------- Date: Fri, 02 Feb 2007 12:05:06 GMT Server: Apache/2.0.59 (Win32) DAV/2 PHP/5.1.6 mod_python/3.2.10 Python/ 2.4.3 SVN/1.4.2 Content-Length: 453 Content-Type: text/xml; charset="utf-8" test Traceback (most recent call last): File "testSoap.py", line 12, in ? zPalca() File "testSoap.py", line 7, in zPalca print b.echo('test') File "I:\Prace\PRYWATNE\test\client.py", line 42, in __call__ File "I:\Prace\PRYWATNE\test\client.py", line 171, in RPC File "I:\Prace\PRYWATNE\test\client.py", line 502, in Receive File "I:\Prace\PRYWATNE\test\client.py", line 436, in Receive File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI \parse.py", line 323, in Parse File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI \TC.py", line 573, in parse File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI \TC.py", line 542, in parse_into_dict_or_list File "C:\opt\Python24\lib\site-packages\zsi-2.0_rc3-py2.4.egg\ZSI \TC.py", line 572, in parse ZSI.EvaluateException: Any cannot parse untyped element [Element trace: /SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:echoResponse/ Message] Can anyone tell me what I'm doing wrong? I read guide and think do everything in right way, but it's not working Thanks for any help I really ned this From http Mon Feb 5 13:39:45 2007 From: http (Paul Rubin) Date: 05 Feb 2007 10:39:45 -0800 Subject: Python does not play well with others References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> Message-ID: <7xodo85tzi.fsf@ruckus.brouhaha.com> John Nagle writes: > > The GIL doesn't affect seperate processes, and any large server that > > cares about stability is going to be running a pre-forking MPM no > > matter what language they're supporting. > > Pre-forking doesn't reduce load; it just improves responsiveness. > You still pay for loading all the modules on every request. For > many AJAX apps, the loading cost tends to dominate the transaction. I think the idea is that each pre-forked subprocess has its own mod_python that services multiple requests serially. New to me is the idea that you can have multiple separate Python interpreters in a SINGLE process (mentioned in another post). I'd thought that being limited to one interpreter per process was a significant and hard-to-fix limitation of the current CPython implementation that's unlikely to be fixed earlier than 3.0. From S.Mientki-nospam at mailbox.kun.nl Tue Feb 20 16:16:55 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 20 Feb 2007 22:16:55 +0100 Subject: ANN: PyDSTool now compatible with numpy 1.0.1, scipy 0.5.2 and 64-bit CPUs. In-Reply-To: References: Message-ID: <2ff9b$45db652f$d443bb3a$29705@news.speedlinq.nl> Sounds GREAT ! thank you ! I just took a quick look, the comparison to SimuLink looks good, now if someone could make a comparison with Modelica ;-) cheers, Stef Mientki Rob Clewley wrote: > We are pleased to announce version 0.84 of PyDSTool, an open-source > dynamical systems simulation, modeling, and analysis package. > > This long-overdue release is primarily intended to bring existing > PyDSTool functionality up to date with the latest numpy and scipy releases > (previous versions required scipy 0.3.2, numarray, numeric, etc). > Also, PyDSTool is now compatible with 64-bit CPUs. > > While we have added a few new features and made several fixes, major > improvements to functionality are in the pipeline for version 0.90. > > Please see http://pydstool.sourceforge.net for release notes and > documentation, > and http://sourceforge.net/projects/pydstool for downloading. As ever, > please > send us feedback if you have any problems with this new release or ideas > and > code contributions for future releases. > > Regards, > > Rob, Erik, and Drew. > Center for Applied Mathematics, > Cornell University. > > ****************** > > PyDSTool is an integrated simulation, modeling and analysis package > for dynamical systems, written in Python (and partly in C). It is > being developed at Cornell University, and the source code is > available under the terms of the BSD license. PyDSTool runs on Linux, > Windows, and Macs, and aims to have a minimal number of package > dependencies. From gagsl-py at yahoo.com.ar Mon Feb 5 18:46:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:46:32 -0300 Subject: confused about resizing array in Python References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: En Sat, 03 Feb 2007 21:34:19 -0300, Dongsheng Ruan escribi?: > This seems to be clever to use reference for list. > > Is it unique to Python? > > How about the traditional programming languages like C, Pascal or C++? Python is written in C - so obviously it can be done in plain C. Delphi (Pascal) has a similar thing; lists hold only a reference to the object, and grow in discrete steps when needed. And in C++ you have several container variants in the STL to choose from. In all cases, there is a library behind, and a fairly good amount of code. The good news is that it's already done for python: you get a lot of data structures ready to use in Python. -- Gabriel Genellina From SSchukat at dspace.de Wed Feb 14 10:32:30 2007 From: SSchukat at dspace.de (Stefan Schukat) Date: Wed, 14 Feb 2007 16:32:30 +0100 Subject: [pywin32] - Excel COM problem In-Reply-To: Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB902339A@exchange2003.dspace.de> "Characters" is a parameterized property. So you can't call it without a generated wrapper. see inside the wrapper: # Result is of type Characters # The method GetCharacters is actually a property, but must be used as a method to correctly pass the arguments def GetCharacters(self, Start=defaultNamedOptArg, Length=defaultNamedOptArg): .... so in your case: xlsapp = gencache.EnsureDispatch("Excel.Application") wb = xlsapp.Workbooks.Add() sheet = wb.Sheets[0] myShape = sheet.Shapes.AddShape(1, 315, 200, 400, 300) myShape.Select() xlsapp.Selection.Characters.Text = finalText[0:200] xlsapp.Selection.GetCharacters(200).Insert(finalText[200:400]) excelfile = "Hello.xls" wb.SaveAs(excelfile) wb.Close() xlsapp.Quit() Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Andrea Gavana > Sent: Friday, February 09, 2007 9:59 PM > To: python-list at python.org > Subject: [pywin32] - Excel COM problem > > Hi All, > > I have a very simple python script that tries to put a > rectangular shape in a worksheet and then add some text > inside that shape. The main problem, is that as usual Excel > doesn't like input strings longer than 200 and something > characters. So, by just recording a macro in Excel, I tried > to append the text in the shape by dividing it in chunks. For > example, I tried this little script: > > #---------------------------------- > from win32com.client import Dispatch > > finalText = "A"*1250 > > xlsapp = Dispatch("Excel.Application") > wb = xlsapp.Workbooks.Add() > sheet = wb.Sheets[0] > > myShape = sheet.Shapes.AddShape(1, 315, 200, 400, 300) > myShape.Select() > > xlsapp.Selection.Characters.Text = finalText[0:200] > xlsapp.Selection.Characters(200).Insert(finalText[200:400]) > > excelfile = "Hello.xls" > wb.SaveAs(excelfile) > wb.Close() > xlsapp.Quit() > > #---------------------------------- > > And it crashes with an impossible error: > > Traceback (most recent call last): > File "D:\MyProjects\pywin32.py", line 13, in > xlsapp.Selection.Characters(200).Insert(finalText[200:400]) > File > "C:\Python25\lib\site-packages\win32com\client\dynamic.py", > line 172, in __call__ > return > self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_. > defaultDispatchName,None) > pywintypes.com_error: (-2147352573, 'Member not found.', None, None) > > However, the macro I recorded in Excel does exactly that: it > appends chunks of the string with a maximum length of 200 chars. > Am I missing something here? > This is with Python 2.5, PythonWin 2.5 (r25:51908, Sep 19 2006, > 09:52:17) [MSC v.1310 32 bit (Intel)] on win32, Windows XP SP2. > > Thank you for your consideration. > > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.virgilio.it/infinity77/ > -- > http://mail.python.org/mailman/listinfo/python-list > From steven.bethard at gmail.com Mon Feb 19 21:22:29 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 19 Feb 2007 19:22:29 -0700 Subject: New-style classes (was Re: Checking for EOF in stream) In-Reply-To: References: <45DA39B0.7020403@gentlemail.com> <45DA4F53.90505@gentlemail.com> Message-ID: GiBo wrote: > One more question - is it likely that StringIO will be turned into > new-style class in the future? The reason I ask is whether I should try > to deal with detection of new-/old-style classes or take the > old-styleness for granted and set in stone instead. In Python 3.0, everything will be new-style classes. In Python 2.X, it is extremely unlikely that anything will be upgraded to a new-style class. That would raise a number of backwards incompatibilities with relatively little benefit. STeVe From bwooster47 at gmail.com Thu Feb 22 11:29:04 2007 From: bwooster47 at gmail.com (bwooster47 at gmail.com) Date: 22 Feb 2007 08:29:04 -0800 Subject: Bug in time module - %z works in perl, not in python? In-Reply-To: <1172112620.868130.139560@p10g2000cwp.googlegroups.com> References: <1172110679.681182.128350@j27g2000cwj.googlegroups.com> <1172112620.868130.139560@p10g2000cwp.googlegroups.com> Message-ID: <1172161744.824760.187190@m58g2000cwm.googlegroups.com> On Feb 21, 9:50 pm, attn.steven.... at gmail.com wrote: > On Feb 21, 6:17 pm, bwooste... at gmail.com wrote: ... > > 2007-02-21 21:15:58 EST+0000 (iso localtime, python) > Seems to be a bug. I can duplicate the > problem here (Python 2.4.3, Red Hat Desktop release 4). I searched the bug database, found this issue was closed as not a bug. I don't know if I should enter a new bug, for now, have just added a comment to the above closure, not sure if anyone will look into whether this issue should be reopened. http://sourceforge.net/tracker/index.php?func=detail&aid=1493676&group_id=5470&atid=105470 [above bug says that %z (small z) is not supported by Python - that seems to be incorrect, atleast to me. Capital Z may be deprecated, but not small z as far as I can tell.] Can we confirm whether this issue is not a python issue? We are talking about small z, not capital Z. >From Python docs at http://docs.python.org/lib/module-time.html : "The use of %Z is now deprecated, but the %z escape that expands to the preferred hour/minute offset is not supported by all ANSI C libraries." Most current C libraries support %z, it is in fact the preferred way to do things, would be bad to see python reject this. Even then - isn't the above a bug? If not supported, %z should always provide a empty character, but not print out totally incorrect data as +0000 for EST. From rdm at rcblue.com Sat Feb 3 06:50:18 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 03 Feb 2007 03:50:18 -0800 Subject: Python 2.5 Quick Reference Message-ID: <20070203115525.BD9701E4008@bag.python.org> Is this reliable? (Looks good to me, but...) Thanks, Dick Moores From sjmachin at lexicon.net Sat Feb 24 21:22:32 2007 From: sjmachin at lexicon.net (John Machin) Date: 24 Feb 2007 18:22:32 -0800 Subject: Referencing Items in a List of Tuples In-Reply-To: References: Message-ID: <1172370152.905573.76220@v33g2000cwv.googlegroups.com> On Feb 25, 1:01 pm, rshep... at nospam.appl-ecosys.com wrote: > While working with lists of tuples is probably very common, none of my > five Python books or a Google search tell me how to refer to specific items > in each tuple. I find references to sorting a list of tuples, but not > extracting tuples based on their content. > > In my case, I have a list of 9 tuples. Each tuple has 30 items. The first > two items are 3-character strings, the remaining 28 itmes are floats. > > I want to create a new list from each tuple. But, I want the selection of > tuples, and their assignment to the new list, to be based on the values of > the first two items in each tuple. > > If I try, for example, writing: > > for item in mainlist: item is one of your 30-element tuples, ... > if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': so do this: if item[0] == 'eco' and item[1] == 'con': > ec.Append(mainlist[item][2:]) and ec.append(item[2:]) # note append, not Append > > python doesn't like a non-numeric index. If nothing. Python doesn't like a non-numeric index, quite irrespective of what you do :-) > I would really appreciate a pointer Sorry, only nasty languages have pointers :-) > so I can learn how to manipulate lists > of tuples by referencing specific items in each tuple (string or float). HTH, John From steve at REMOVEME.cybersource.com.au Sun Feb 25 19:37:47 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 26 Feb 2007 11:37:47 +1100 Subject: Nested Parameter Definitions References: <1172426430.984638.63920@m58g2000cwm.googlegroups.com> Message-ID: On Sun, 25 Feb 2007 10:00:31 -0800, Paddy wrote: > I wondered if those of you with some Python experience new of nested > parameters and don't use them; or just forgot/don't know it is > possible? I learnt about this some time ago. I don't often use it, although it makes sense to write this: def parrot(x, (y, z)): pass instead of this: def parrot(x, a2tuple): y, z = a2tuple pass -- Steven D'Aprano From __peter__ at web.de Fri Feb 16 08:01:32 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Feb 2007 14:01:32 +0100 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> Message-ID: Edward K Ream wrote: >> There is also the 2to3 converter. The aim is that this will be > effective enough that coders should be able to maintain a 2.X (2.6 ?) > codebase, run it through 2to3 and have the result run unchanged on > Python 3. That way there will be no need to maintain two code bases. > > I have offered a proof that the converter must change print to print2 (or > some other name) in order to maintain a common code base. How much > clearer > can I be? If a common code base is desired, it *is* the end of print There could be something like from __future__ import print_function to remove the print keyword in 2.x. Peter From B.Ogryczak at gmail.com Fri Feb 2 11:21:08 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 2 Feb 2007 08:21:08 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170334830.137876.248230@h3g2000cwc.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> Message-ID: <1170433268.115386.189280@k78g2000cwa.googlegroups.com> On Feb 1, 2:00 pm, "Nicko" wrote: > precision and the answer that they were looking for was: > a = (b * 04444444445L) >> 32 > Note that the constant there is in octal. 04444444445L? Shouldn?t it be 04444444444? Or more generally, const = (1<>bitPrecision From bkamrani at gmail.com Thu Feb 22 10:27:16 2007 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: 22 Feb 2007 07:27:16 -0800 Subject: list/get methods/attributes of a class? Message-ID: <1172158035.977029.188980@q2g2000cwa.googlegroups.com> Hello, Sorry guys for this newbie questions. But I wonder if there is a standard or build-in method to know the methods of a class? I'm not originally a progrommer and I have worked with python/qt in a basic level. Now I work a package which has many predefined classes which I'm going to resue by importing them. I would like to know more about each imported class, what methods exists and so on. Printing the object or type(object) doesn't say so much. Any hint or helps is really appreciated! /Ben From steven.bethard at gmail.com Fri Feb 16 16:11:53 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 16 Feb 2007 14:11:53 -0700 Subject: can't load a dll in python 2.5 In-Reply-To: <1171656997.423604.175410@v45g2000cwv.googlegroups.com> References: <1171656997.423604.175410@v45g2000cwv.googlegroups.com> Message-ID: dwmaillist at gmail.com wrote: > I am on WindowsXP. I have a dll that I can load in python 2.3 but > when trying to load it into python 2.5 it complains that there is > nothing by that name. Is there some aspect of the dll loading > mechanism between python 2.3 and 2.5 that has changed preventing me > from loading the dll in 2.5? Thanks in advance for your suggestions. Don't know if this is your problem, but as of Python 2.5, ".dll is no longer supported as a filename extension for extension modules. .pyd is now the only filename extension that will be searched for". (That's the last line on http://docs.python.org/whatsnew/ports.html) HTH, STeVe From mathiasDOTfranzius at webDELETEME.de Tue Feb 13 13:17:09 2007 From: mathiasDOTfranzius at webDELETEME.de (Mathias) Date: Tue, 13 Feb 2007 19:17:09 +0100 Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: > Hi, it would be helpful if you posted a minimalistic code snippet > which showed the problem you describe. > > Daniel I wish I could! If I knew exactly where the effect takes place I could probably circumvent it. All I know know is that it happens under high load and with a lot of waitstates I can reduce the propability of crashing. So there must be some race condition somewhere I think. Is there a way to analyze where the crash took place? I guess I can have a core dumped and somehow analyze it, but that's probably very hard to do. Would a profiler work which records the function call structure? Does someone have experience with threading in python - are there non-threadsafe functions I should know about? Thanks, Mathias From usenet200701 at tobyinkster.co.uk Fri Feb 2 08:08:02 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Fri, 2 Feb 2007 13:08:02 +0000 Subject: Writing "pythonish" code References: Message-ID: Mizipzor wrote: > One thing is that in c++ im used to have private members in classes and > no member is altered except through the public functions of the class. By convention, class members starting with a single underscore are considered private. This is much the same as the convention that on UNIX, files that start with a dot are considered hidden -- there is nothing actually *preventing* a programme from showing you these files in a directory listing, but by convention it won't, unless you explicitly ask to see them. Class members starting with a double underscore are "mangled" which makes it more difficult for other code (even subclasses!) to access the member. Difficult though -- not impossible. -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From bjourne at gmail.com Mon Feb 5 08:39:27 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 5 Feb 2007 14:39:27 +0100 Subject: Inheriting str object In-Reply-To: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> References: <1170672488.530515.181340@k78g2000cwa.googlegroups.com> Message-ID: <740c3aec0702050539u6d8b086elc2f655a8f66de07a@mail.gmail.com> On 5 Feb 2007 02:48:08 -0800, kungfoobar at gmail.com wrote: > I want to have a str with custom methods, but I have this problem: > > class myStr(str): > def hello(self): > return 'hello '+self > > s=myStr('world') > print s.hello() # prints 'hello world' > s=s.upper() > print s.hello() # expected to print 'hello WORLD', but s is no longer > myStr, it's a regular str! You could use the proxy pattern: class GreeterString(object): def __init__(self, str): self.proxy = str def hello(self): return 'hello ' + self.proxy def __getattr__(self, attr): if attr in dir(self.proxy): proxy_attr = getattr(self.proxy, attr) if callable(proxy_attr): def wrapper(*args, **kwargs): return self.__class__(proxy_attr()) return wrapper def __str__(self): return self.proxy.__str__() gs = GreeterString('world') print gs.upper().hello() Magic methods has to be overridden manually, I think. -- mvh Bj?rn From steve at holdenweb.com Sun Feb 11 08:46:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 13:46:11 +0000 Subject: How to access an absolute address through Python? In-Reply-To: <1171198707.889681.177270@h3g2000cwc.googlegroups.com> References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> <1171197574.776135.96980@k78g2000cwa.googlegroups.com> <1171198707.889681.177270@h3g2000cwc.googlegroups.com> Message-ID: volcano wrote: > On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch wrote: [...] >> What's your goal? What do you expect at the memory address you want to >> access? >> >> Ciao, >> Marc 'BlackJack' Rintsch > > My goal is to sync program with external equipment through a register > defined as an absolute physical address. I know how to do it from C - > was curious if it may be done from Python. Can it be done? > No. You'd have to use a compiled extension. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From robin at NOSPAMreportlab.com Mon Feb 5 19:02:10 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Tue, 06 Feb 2007 00:02:10 +0000 Subject: ctypes.com.IUnknown In-Reply-To: <45C5C0F3.9050308@jessikat.plus.net> References: <45C4F24C.7060204@jessikat.plus.net> <1170585495.897502.148500@v45g2000cwv.googlegroups.com> <45C5C0F3.9050308@jessikat.plus.net> Message-ID: <45C7C582.5090700@jessikat.plus.net> Robin Becker wrote: > Giles Brown wrote: >> ........ >> >> What about downloading the spin-off library? >> http://sourceforge.net/projects/comtypes/ >> >> (I think this was created to move the com stuff out of ctypes?) > ........ > > Thanks I didn't know that; I'll give it a whirl. I tried, but failed to get venster to go; seems like some things have gone from the original ctypes. -- Robin Becker From paul at boddie.org.uk Tue Feb 6 08:59:12 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Feb 2007 05:59:12 -0800 Subject: when will python 2.5 take in mainstream? In-Reply-To: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> References: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> Message-ID: <1170770352.236380.220600@j27g2000cwj.googlegroups.com> On 6 Feb, 13:45, "Ben Sizer" wrote: > > Perhaps the C API remains the same but the real > issue is the binary API between extensions and Python changes every > couple of years or so. That's why I run 2.4 anywhere that needs > extensions. > > It would be great if someone could invest some time in trying to fix > this problem. I don't think I know of any other languages that require > recompilation of libraries for every minor version increase. On the python-dev mailing list there was discussion of some of these issues in the context of the Linux Standard Base specifications: http://mail.python.org/pipermail/python-dev/2006-November/070027.html Despite the specificity implied by the LSB name, I think such work would produce benefits for all Python developers with similar concerns, regardless of their chosen platforms. Paul From horpner at yahoo.com Wed Feb 21 08:00:09 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 21 Feb 2007 14:00:09 +0100 Subject: f---ing typechecking References: <1171487277.739415.291740@h3g2000cwc.googlegroups.com> Message-ID: On 2007-02-21, Hendrik van Rooyen wrote: > "Nick Craig-Wood" wrote: >> Ie >> >> x += a >> >> does not equal >> >> x = x + a >> >> which it really should for all types of x and a > > One would hope so , yes. > > However, I think that the first form is supposed to update in place, > while the second is free to bind a new thing to x > >> (That is the kind of statement about which I'm sure someone >> will post a perfectly reasonable counterexample ;-) > > I don't think its reasonable - its just an accident of implementation.. Yup. It's analogous to the way you can do hill-starts with a manual transmission, but not with an automatic transmission. -- Neil Cerutti From http Sat Feb 3 20:43:08 2007 From: http (Paul Rubin) Date: 03 Feb 2007 17:43:08 -0800 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <7xbqkb2pmt.fsf@ruckus.brouhaha.com> Message-ID: <7xodoaelzn.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > Paul> Yeah well, the Wxpython, PyQt, PyGTK etc. people may feel slighted > Paul> that Tkinter got included and their stuff didn't, and the Eric, > Paul> Eclipse, Komodo etc. people may feel slighted that IDLE got > Paul> included, but that doesn't stop Tkinter and IDLE from being useful > Paul> and worth shipping in Python. > > They were both pretty much the only games in town when they were included > with Python. If they were developed in today's environment I doubt they > would be included. That would diminish Python's popularity since being able to write GUI apps without having to download additional crap is a Python selling point, and IDLE is a considerably more pleasant Python editor than Notepad is. > Paul> Basic competitive analysis. People ask here all the time "I'm > Paul> trying to write application XYZ, should I use language L or should > Paul> I use Python" (L is usually Java or PHP but can be other things). > > So every time some lame ass PHP refugee gripes about something they think > Python is missing which PHP includes we should scan the horizon for all the > candidates and toss them in the next release? No, just the functions that are requested frequently, like database adapters. From S.Mientki-nospam at mailbox.kun.nl Mon Feb 19 18:18:10 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 20 Feb 2007 00:18:10 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <45da0e70$0$31502$426a34cc@news.free.fr> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com><14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl><45d626f5$0$19811$426a74cc@news.free.fr><53nt2aF1sn581U1@mid.uni-berlin.de> <45d85388$0$29060$426a74cc@news.free.fr> <45da0e70$0$31502$426a34cc@news.free.fr> Message-ID: > > It's now the *3rd* time I mention Glade, wxGlade and QTDesigner in this > thread. Hendrik, I know *exactly* what Stef is talking about - been > here, done that. Doubt, that know what I'm talking about ... ... Glade, wxGlade, QTDesigner are not my choice ;-) ... at the moment I tend towards VisualWX + openGL for the future. cheers, Stef From sudipta.referral at gmail.com Wed Feb 28 20:09:22 2007 From: sudipta.referral at gmail.com (Sudipta Chatterjee) Date: Wed, 28 Feb 2007 19:09:22 -0600 Subject: Image not displaying in Text widget Message-ID: <5530eb260702281709y10aae111ha6b932aa267d2133@mail.gmail.com> Hi all, I am facing a strange problem when I try to embed images in a text widget. After reading the file via PhotoImage() and then using text.image_create(INSERT, image=img), I get a blank place instead of the image. The size of the blank area under highlighting via the mouse select comes to exactly the size of the image itself, but the contents of the image are not displaying. I have pack() -ed the text widget already and text around this image_create() function are displaying just fine. But the image's contents just don't show up! :( Any ideas? Thanks a lot, Sudipta -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Mon Feb 19 12:51:06 2007 From: http (Paul Rubin) Date: 19 Feb 2007 09:51:06 -0800 Subject: timeout in urllib.open() References: Message-ID: <7xabza829h.fsf@ruckus.brouhaha.com> Stefan Palme writes: > is there a way to modify the time a call of > > urllib.open(...) > > waits for an answer from the other side? Have a tool which > automatically checks a list of websites for certain content. The > tool "hangs" when one of the contacted websites behaves badly and > "never" answers... Other than by using socket timeouts, at least in Un*x, you can also use signal.alarm. You can only have one OS-provided alarm pending at a time, so if you want multiple overlapping timeouts you have to schedule them yourself with a single alarm. From srikrishnamohan at gmail.com Fri Feb 9 13:52:45 2007 From: srikrishnamohan at gmail.com (km) Date: Sat, 10 Feb 2007 00:22:45 +0530 Subject: Best Free and Open Source Python IDE In-Reply-To: <1171046580.351974.108150@v33g2000cwv.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> <1171046580.351974.108150@v33g2000cwv.googlegroups.com> Message-ID: check out SPE (StanisPpython Editor) KM On 9 Feb 2007 10:43:00 -0800, Bastos wrote: > > On Feb 8, 10:03 am, "Srikanth" wrote: > > Yes, > > > > All I need is a good IDE, I can't find something like Eclipse (JDT). > > Eclipse has a Python IDE plug-in but it's not that great. Please > > recommend. > > > > Thanks, > > Srikanth > > Gedit and some plugins, definitely. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dale at nospam.riverhall.co.uk Wed Feb 14 12:27:06 2007 From: dale at nospam.riverhall.co.uk (Dale Strickland-Clark) Date: Wed, 14 Feb 2007 17:27:06 +0000 Subject: list of range of floats References: Message-ID: Steve wrote: > I'm trying to create a list range of floats and running into problems. > I've been trying something like: > > a = 0.0 > b = 10.0 > > flts = range(a, b) > > fltlst.append(flts) > > When I run it I get the following DeprecationWarning: integer argument > expected, got float. How can I store a list of floats? > > TIA > Steve range only does ints. If you want floats, you'll have to write your own version. From jstroud at mbi.ucla.edu Wed Feb 28 06:13:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 28 Feb 2007 11:13:47 GMT Subject: random textimage In-Reply-To: <1172660299.114009.42950@a75g2000cwd.googlegroups.com> References: <1172660299.114009.42950@a75g2000cwd.googlegroups.com> Message-ID: gert wrote: > import string > import random > import PIL > from PIL import Image, ImageFont, ImageDraw > from PIL import ImageEnhance, ImageOps, ImageStat > from StringIO import StringIO > import os > > pwd = os.path.dirname(os.path.abspath(__file__)) > fpath=os.path.join(pwd,'img.ttf') > iname=os.path.join(pwd,'pass.jpg') > > def gen(): > text = str(random.randint(0,1000)) > im = Image.new("RGB", (125, 34), "#fff") > ttf = ImageFont.truetype(fpath, 16) > draw = ImageDraw.Draw(im) > draw.text((10,10), text, font=ttf, fill="green") > img = StringIO() > im.save(img, "JPEG") > f = open(iname) > f.write(im) > f.close() > return text > > if __name__ == "__main__": > print gen() > > gert at gert:~/Desktop/svn/xhtml$ python2.5 textimg.py > Traceback (most recent call last): > File "textimg.py", line 27, in > print gen() > File "textimg.py", line 22, in gen > f.write(im) > TypeError: argument 1 must be string or read-only character buffer, > not instance > gert at gert:~/Desktop/svn/xhtml$ > > i am stuck anybody can help me ? > Are you sure you don't want f.write(img) ? James From gagsl-py2 at yahoo.com.ar Tue Feb 27 00:11:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 Feb 2007 02:11:22 -0300 Subject: a=b change b a==b true?? References: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> <1172498883.061877.123340@k78g2000cwa.googlegroups.com> <1172500003.797450.7960@v33g2000cwv.googlegroups.com> Message-ID: En Mon, 26 Feb 2007 11:26:43 -0300, escribi?: > It works great now. Thank you for all of your incredibly quick > replies. Now that you have solved your immediate problem, you could read: http://effbot.org/zone/python-objects.htm -- Gabriel Genellina From stj911 at rock.com Sat Feb 3 10:24:45 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 3 Feb 2007 07:24:45 -0800 Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. In-Reply-To: References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170482833.643671.254640@s48g2000cws.googlegroups.com> <1170488368.634755.138920@m58g2000cwm.googlegroups.com> Message-ID: <1170516285.308948.134410@a34g2000cwb.googlegroups.com> On Feb 3, 1:08 am, "John Barrett" wrote: > wrote in message > > news:1170488368.634755.138920 at m58g2000cwm.googlegroups.com... > > > > > On Feb 2, 10:32 pm, "John Barrett" wrote: > >> wrote in message > > >> >> > [snip] > >> >> > Run your "experiment" again but add some pure oxygen such as was > >> >> > escaping from the on-board breathing oxygen tanks on the > >> >> > airplanes that were crashed into the WTC. > > >> > No need to do it. We have the pictures of live humans waving from the > >> > gaping holes in the towers where the planes crashed. We have the > >> > testimonies of the fire fighters that the fires were not that hot and > >> > minor. The fuel of the plane which is mainly in the wings were severed > >> > outside the netting and much of them burnt outside in the fireball > >> > that is visible in all the videos. Futhermore, the black soot that was > >> > visible to the naked eye is indicative of bloody cold flame. Also, the > >> > probability of the oxygen tanks oriented in such a way to inject > >> > oxygen onto the steel as in a oxygen cutting torch is extremely low. > >> > These cylinders have a 1000-3000psi of pressure which makes them into > >> > a rocket or an explosive under uncontrolled gas release. And they > >> > would not contaminate the molten metal with any sulfur. Either the > >> > atmosphere inside was oxidising or reducing. If it was oxidising, how > >> > did the sulfur in huge quantities contaminate the molten metal pools? > >> > The official lies to explain sulfur is from the plaster wall. But that > >> > requires a reducing atmosphere with finely divided and intimately > >> > mixed reactants in a calciner where they are continuously rotated and > >> > run for several hours. Yet the fires ran not even for an hour before > >> > the building collapsed. > > >> OK - given all that -- you are left with only one conclusion (or at least > >> I > >> am) -- progressive structural failure, the loss of support where the > >> plane > >> hit was sufficient to put excessive stress on the remaining structural > >> members, resulting in a catastrophic sequential failure > > > I dont think you have seen any actual structural failures, esp > > progressive. > > That happens often in earthquake and they have stacked floors. There > > is > > famous picture of an earthquake on these websites and in the videos. > > Futhermore > > due to erratic stops and goes in the progressive failure, the > > structure falls on the side esp a big bldg like WTC1&2 should have > > fallen from the tipping torque to one side. That did not happen. only > > controlled demolition bldgs fall down straight. > > >> -- it doesnt take > >> exotic chemical mixes to put excessive mechanical stress on a system... > >> just > >> chop out enough supports.. it may take time for the remaining supports to > >> deform enough to reach the failure point.. but they will get there, as > >> demonstrated -- occams razor dude -- the least hypothesis is usually the > >> right one -- and I get enough conspiracy theory crap out of my dad -- > >> makes > >> a good movie -- but doesnt pan out in real life -- too many > >> whistle-blowers > >> around !! > > > Occams razor is applicable to nature's works. human works are not > > amenable to it. Besides, the official fairy tale is the conspiracy > > theory. > > >> The city I live in is installing those red-light cameras to catch > >> light-runners -- my dad likes to claim that they manipulate the yellow > >> time > >> to catch people in the intersection and increase revenue from traffic > >> tickets -- I told him to shut up until he got out there with a stop watch > >> and proved it -- and I say the same to you -- PROVE it -- then make some > >> noise -- conjecture and conspiracy theories without proof are a waste of > >> everyones time. -- how do you know the sulphur was in large quantities ?? > >> did you do a chemical analysis ?? or can you produce one done by a > >> reputable > >> metalurgy company ?? > > > These pillars are not machinable steel. the sulfur here was excessive. > > we are talking about intergranular corrosion, not that teeny amount > > used for imparting machinability and that is not nowadays needed. It > > only for cheap and rough chinese type crap and i am not sure even > > there if someone would ruin their steel mills by adding this kind of > > corrosive sulfur shit. come on dude ... dont mix categories. > > >> Ohhh and by the way -- high sulphur steels are regularly used for > >> machined > >> components -- was the amount of sulphur detected incosistent with what > >> may > >> have been present due to the use of high sulphur steels ?? (where is that > >> metalurgy report again ??) > > > yeah a damn fool would put sulfur in the bolts and load bearing > > elements such as the bolts of aircrafts and space shuttle. > > > Besides how do you explain the completely pulverized building ?????? > > if not for explosives. > > lets try that again :) > > http://www.tms.org/pubs/journals/JOM/0112/Eagar/Eagar-0112.html Yeah, I know eager very well. He runs the welding lab at MIT. > A very concise and MUCH more believable explanation of the structural > failure modes involved WITH numbers that MAKE SENSE !! (and interestingly > enough, a progressive failure as I surmised earlier.. one thing (one one > thing) leads to another !!) Pal, I am sorry to say that your knowledge is extremely obsolete. He was refuted centuries ago. Even NIST disowned his pancake theory subsequently. > and a VERY good explanation of why it fell straight down instead of to the > side !! > > It even explains the speed of collapse, which given the masses involved > (which they detail), will allow you to compute the energy of impact that so > complexly pulverized the structure > > (remember what I said about RESEARCH -- try it some time !! It didn't take > me and hour to find that one !! Google "world trade center structure") that exactly explains why your finding was such an obsolete one. > And so I wield Occam's Razor -- the simplest explanation that makes sense !! The newsgroups such as this are now being used mainly for announcements of new findings, but not tutorials. I have already given link to www.st911.org and there you will get to all the down-pyramid sites where all your obsolete objections have been answered ad nauseum with detailed papers and research. Eager was the first one to refuted. He has'nt dared to open his mouth since then for fear or ruining the reputation of MIT that such unsubstantiated research could come out of there. Do not forget, 911 is a crime. Science there is only a part of it. There are other pieces of evidence such as the presence of FEMA just the day BEFORE the event. The power shutdowns to disable the security cameras. The removal of bomb sniffing dogs. Just weeks prior to 911. Bush family incharge of security. Dont bother to post unless you have done enough research by first reading through the sites to the CURRENT STATE OF RESEARCH. Ever watched the following videos: Loose change Terror storm start from there and then go to the current state of research. Explain the presence of potassium in the molten steel and also manganese. They came from the potassium permanganate oxidiser of thermate. And then the Bush video: There's always time for politics ... Laughing out Loud. I already posted the short video links for you. From __peter__ at web.de Wed Feb 14 13:02:02 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Feb 2007 19:02:02 +0100 Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171360113.585827.17440@v45g2000cwv.googlegroups.com> <1171382544.431125.299020@v45g2000cwv.googlegroups.com> Message-ID: massimo s. wrote: > On 13 Feb, 12:46, Peter Otten <__pete... at web.de> wrote: >> Well, what problems ocurring with >> >> class A: pass >> class B: pass >> class C(A, B): pass >> >> could be avoided by writing >> >> class A: pass >> class B(A): pass >> class C(B): pass >> >> instead? Classes have to be designed for subclassing, so essentially you >> get two interfaces, one for subclasses and one for client code instead of >> just the latter. A more relevant mantra governing inheritance is "Flat is >> better than nested". > > I am truly getting lost. Are you saying that doing A-->B(A)--C(B) is > better than C(A,B)? And isn't the former thing nested? Or are you > saying that C(A,B) is better than A,B(A),C(B)? And in both cases:why? Neither. I wanted to express that I don't buy the "mantra" you mentioned above. Just because it uses only single inheritance code doesn't become magically more robust. Use whatever works best to solve the actual problem. > And why "classes have to be designed for subclassing"? I often do > classes that are not thought to be subclassed. That's fine. If (and only if) you expect a class to be subclassed you better spend some thought on what methods should be overriden etc. This increases the effort spent on the class significantly. Distinct classes are often easier to write and maintain. Hope-I'm-clear-this-time, Peter From skip at pobox.com Sat Feb 3 16:44:07 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 3 Feb 2007 15:44:07 -0600 Subject: Python does not play well with others In-Reply-To: <87k5yzkuxm.fsf@gmail.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> <7xk5yz2q42.fsf@ruckus.brouhaha.com> <52jt3eF1p85tbU1@mid.uni-berlin.de> <7xy7nf1850.fsf@ruckus.brouhaha.com> <87k5yzkuxm.fsf@gmail.com> Message-ID: <17861.551.38589.889225@montanaro.dyndns.org> Jorge> So we should get a better egg support. Then it would all be just Jorge> a matter of easy_install . I'm all in favor of that... Skip From lance at augustmail.com Fri Feb 9 09:02:50 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Fri, 09 Feb 2007 14:02:50 GMT Subject: excel find last column In-Reply-To: <1170981163.874220.27660@h3g2000cwc.googlegroups.com> References: <1170981163.874220.27660@h3g2000cwc.googlegroups.com> Message-ID: I ran makepy.py and loaded Microsoft Excel Object Library 11.0 I have imported: import win32com.client from win32com.client import constants import re import codecs,win32com.client import time import datetime import win32com.client.dynamic using this expression lastcol = sh.UsedRange.Find("*", "A1", win32com.client.constant.SearchOrder=xlByColumns, win32com.client.constants.SearchDirection=xlPrevious).Column I get error: , line 245 lastcol = sh.UsedRange.Find("*", "A1", win32com.client.constant.SearchOrder=xlByColumns, win32com.client.constants.SearchDirection=xlPrevious).Column SyntaxError: keyword can't be an expression Tool completed with exit code 1 Guess I am getting closer to the solution? LOL Sorry for being ignorant but I am a newbie and I don't understand all this python/excel stuff. Lance Luap777 at gmail.com wrote: >> I get the error that xlPrevious is not defined. >> > > If you are using pythonwin, run the COM Makepy utility on Microsoft > Excel Object Library. Then you have access to the defined constants as > follows. > >>>> import win32com.client >>>> win32com.client.constants.xlPrevious > 2 > > Hope this helps. > > Paul > > From hpk at trillke.net Wed Feb 14 10:53:35 2007 From: hpk at trillke.net (holger krekel) Date: Wed, 14 Feb 2007 16:53:35 +0100 Subject: ANN: py lib 0.9.0: py.test, distributed execution, microthreads ... Message-ID: <20070214155335.GE16146@solar.trillke> py lib 0.9.0: py.test, distributed execution, greenlets and more ====================================================================== Welcome to the 0.9.0 py lib release - a library aiming to support agile and test-driven python development on various levels. Main API/Tool Features: * py.test: cross-project testing tool with many advanced features * py.execnet: ad-hoc code distribution to SSH, Socket and local sub processes * py.magic.greenlet: micro-threads on standard CPython ("stackless-light") * py.path: path abstractions over local and subversion files * rich documentation of py's exported API * tested against Linux, OSX and partly against Win32, python 2.3-2.5 All these features and their API have extensive documentation, generated with the new "apigen", which we intend to make accessible for other python projects as well. Download/Install: http://codespeak.net/py/0.9.0/download.html Documentation/API: http://codespeak.net/py/0.9.0/index.html Work on the py lib has been partially funded by the European Union IST programme and by http://merlinux.de within the PyPy project. best, have fun and let us know what you think! Holger Krekel, Maciej Fijalkowski, Guido Wesdorp, Carl Friedrich Bolz From tactics40 at gmail.com Thu Feb 22 18:32:33 2007 From: tactics40 at gmail.com (tac-tics) Date: 22 Feb 2007 15:32:33 -0800 Subject: is it possible to remove the ':' symbol in the end of lines starting with 'if', 'while' etc? In-Reply-To: References: <1172144943.794384.73270@s48g2000cws.googlegroups.com> Message-ID: <1172187153.711933.37870@m58g2000cwm.googlegroups.com> Tip: don't try learning perl. I agree the colon is largely redundant, but it's not unreasonable. From gagsl-py at yahoo.com.ar Thu Feb 8 21:46:29 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Feb 2007 23:46:29 -0300 Subject: strange problem using modules from my own package. References: Message-ID: En Thu, 08 Feb 2007 18:40:39 -0300, krishnakant Mane escribi?: > I found a very strange kind of behaviour in python with my own package. > I created a package in which there were 4 modules and one __init__.py > file > I created the entire project in eclipse (pydev). > it works fine there with the ide. > but now when I try running the code without eclipse, that is when I > run the individual .py file from a command promt it gives me error. > for example I have mainwindow.py, customer.py, stock.py and of course > __init__p.py in my package > the app is in wxpython which is not important in the context of this > problem. > never the less I go in the directory called pbcf which is the name of > my package > there I have all the above mentioned files and the mainwindow.py file > is the one I run for testing all the menus. > but here the moment I run the file, it starts giving me an error > saying pbcf is not a module. > I find that the same code runs without any problem in eclipse. > in mainwindow.py I have from pbcf import * and in __init__.py I have > of course included MySQLdb and wx > and in __init__.py I have a connection object called CONCSS. > now when I have all the imports in mainwindow, it does work in eclipse > but does not on a normal command prompt. > why is this? > regards. > Krishnakant. It's a bit hard to tell from your description - would be better if you had copied the exact error messages. But the overall architecture looks wrong - a package is a *library*, and it is *used* by others. Your main application should be a standalone script that uses (imports) the package. Look at how other Python applications are structured. -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Fri Feb 16 05:51:24 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Feb 2007 21:51:24 +1100 Subject: I'm faint why this can't work References: Message-ID: <87r6sq5qab.fsf@benfinney.id.au> JStoneGT at aol.com writes: > The codes got by me from the book of "Dive into Python".The original > codes are below: > > class FileInfo(dict): > "store file metadata" > def __init__(self, filename=None): > self["name"] = filename You've put the lines of code in your message without indentation. Please remember that Python uses indentation syntactically. If you're showing code examples in your message, you must make sure that the indentation survives correctly. The best way to do that is to use only tabs, *or* only spaces, for indentation; many programs will mangle tabs in different ways, so spaces are usually safest. -- \ "My aunt gave me a walkie-talkie for my birthday. She says if | `\ I'm good, she'll give me the other one next year." -- Steven | _o__) Wright | Ben Finney From arkanes at gmail.com Fri Feb 2 11:09:25 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 2 Feb 2007 10:09:25 -0600 Subject: asyncore DoS vulnerability In-Reply-To: <1170430334.170669.215150@q2g2000cwa.googlegroups.com> References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> <1170422700.309941.203320@a34g2000cwb.googlegroups.com> <1170430334.170669.215150@q2g2000cwa.googlegroups.com> Message-ID: <4866bea60702020809oed5c08co74fd4a55892bd664@mail.gmail.com> On 2 Feb 2007 07:32:14 -0800, billie wrote: > > This is not a CRASH, It looks an exception with a "Traceback", this is > > the normal way python report problems, nothing wrong with that. > > You can handle it with a try: except: > > I think that such a thing should be handled by asyncore itself. > Handled by doing what, exactly? > > 512 is probably a fixed limit into XP, win2k3 or win2k server will > > accept more. > > Maybe It's possible to increase this value somewhere in the registry. > > If not this is how microsoft justify the difference between server and > > workstation products :-) > > Yeah, maybe... > > >> Why does this exception isn't handled inside asyncore.py? > > To do what ? To raise a custom asyncore error ? > > asyncore aims to be a framework, right? > I think that when select() limit is reached asyncore should just drop > other connections. That's all. Silently rejecting connections in a way that is invisible to the application is clearly the wrong thing to do. > > > You can can probably run over this limit by starting multiple of your > > server process (not thread, process). > > Hope you're joking... > Why should I have to run multiple processes / threads to avoid such a > problem? Thats like asking why you should have to move your fingers to type or why you should have to eat food in order to not starve. Windows is placing a limit of 512 descriptors per process. Call Microsoft if you want to go over that. Or, you can volunteer to write a win32 port of asyncore that uses native winsock functions instead of the BSD compatibility functions. > And what if my system / inteprepter does not support multiple > processes / threads? > What if it doesn't support sockets? This is a platform limitation, not an arbitrary Python one. Nothing Python is going to do is going to convince Windows to select() on more than 512 file descriptors per process. From shanekwon at gmail.com Thu Feb 22 21:04:40 2007 From: shanekwon at gmail.com (agent-s) Date: 22 Feb 2007 18:04:40 -0800 Subject: python not returning true In-Reply-To: References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171444128.138234.50640@l53g2000cwa.googlegroups.com> Message-ID: <1172196280.509299.128900@p10g2000cwp.googlegroups.com> Wow. I didn't realize you guys took this so seriously. From blancmunier1 at yahoo.FR Thu Feb 1 04:17:34 2007 From: blancmunier1 at yahoo.FR (blancmunier1 at yahoo.FR) Date: 1 Feb 2007 01:17:34 -0800 Subject: retrbinary ! how does it work ? Message-ID: <1170321454.210348.91370@a75g2000cwd.googlegroups.com> Hello dear community ! I'm a bit ashamed to ask such an easy question, but I didn't find my answer on previous posts. I'd like to copy files with FTP protocol in a subdirectory. So far, my code look like that : import ftplib session = ftplib.FTP('222.33.44.55','usr','pwd') session.cwd('/') files = session.nlst() for file in files: session.retrbinary('RETR '+file, open(file, 'wb').write) It does work but the files are copied in the same directory as the python file. And I would like to copy the file in this relative directory : ../archives For example, if the python file is in this directory : C:\SCOR\Bat\, the FTP files gotta be in C:\SCOR\archives\ . Can anyone help me. Thanks a lot by advance. Yvan Blancmunier From istvan.albert at gmail.com Sun Feb 4 21:13:50 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 4 Feb 2007 18:13:50 -0800 Subject: Return images with matplotlib? In-Reply-To: <45c684e2$1@griseus.its.uu.se> References: <45c684e2$1@griseus.its.uu.se> Message-ID: <1170641630.264455.267050@s48g2000cws.googlegroups.com> On Feb 4, 8:18 pm, Jan Danielsson wrote: > def barchart(req, params): > some_format = matplotlib.generate_fancy_graph(params) > png_buf = make_png_buffer(some_format) > return png_buf > > Is this possible? If so -- how? savefig does that. You can save to a file name or a buffer. http://matplotlib.sourceforge.net/matplotlib.pylab.html#-savefig i. From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 16:40:42 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 22:40:42 +0100 Subject: Object type check In-Reply-To: <1170879597.935278.240000@m58g2000cwm.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <45ca32ed$0$32232$426a74cc@news.free.fr> <1170879597.935278.240000@m58g2000cwm.googlegroups.com> Message-ID: <45ca4035$0$4321$426a74cc@news.free.fr> king kikapu a ?crit : > at first, thanks you all for your help! > > So, i will follow your advice.In a moment though, i thought that "ok, > do not check anything of the parameter's type but do a try/catch at > the calls inside the function" And so what ? Once an exception got caught, what are you going to do ? Raise another exception ? Re-raise the same exception ? In both cases, you usually don't gain much - and sometimes loose (time, simplicity, readability, and a usefull traceback). Unless you know how to handle it, it's usually better to let the exception propagate. Usually, the person coding the *application* (ie: the coder using your lib) will wrap the whole thing into a catch-all exception handler at the higher level, so he can log the full traceback, display a nice error to the end user, and crash gracefully. As a library programmer, you should not care about this. > But this way, i would rather defeat the purpose because i have to try/ > catch in *every* call inside the func. > So, i suppose that i wouldn't want to do that and just try to make the > call in whatever they passed me in. You're starting to see the light, my friend !-) > Strange world the dynamic one.... If that's too dynamic for you, then run for your life - this is just the visible part of the iceberg. From rocky at panix.com Sat Feb 3 21:20:17 2007 From: rocky at panix.com (R. Bernstein) Date: 03 Feb 2007 21:20:17 -0500 Subject: Debugging SocketServer.ThreadingTCPServer References: Message-ID: "Stuart D. Gathman" writes: > On Tue, 16 Jan 2007 09:11:38 -0500, Jean-Paul Calderone wrote: > > > On Tue, 16 Jan 2007 00:23:35 -0500, "Stuart D. Gathman" > > wrote: > >>I have a ThreadingTCPServer application (pygossip, part of > >>http://sourceforge.net/projects/pymilter). It mostly runs well, but > >>occasionally goes into a loop. How can I get a stack trace of running > >>threads to figure out where the loop is? Is there some equivalent of > >>sending SIGQUIT to Java to get a thread dump? If needed, I can import > >>pdb and set options at startup, but there needs to be some external way > >>of triggering the dump since I can't reproduce it at will. The problem here is that signals are handled only in the main thread. If that thread is blocked for some reason, your signals will also be blocked. Given that you were considering using pdb let me suggest instead pydb - http://bashdb.sf.net/pydb; pdb has no notion of threads but pydb does if you give it the --threading option. (It's thread support might stand a bit of improvement, but at least it's there and is as good or better than any other Python debugger that I am aware of.) > > > > Grab the gdbinit out of Python SVN Misc/ directory. Apply this patch: > > > > http://jcalderone.livejournal.com/28224.html > > > > Attach to the process using gdb. Make sure you have debugging symbols > > in your build of Python. Run 'thread apply all pystack'. > > Did this. gdb displays main thread fine (waiting on accept(), duh). But > gdb goes into a loop displaying the first worker thread. There are no > extension modules other than the batteries included ones. In this > application, I believe, only _socket. (I.e. a pure python server.) > > I will try for a C stack trace next time it loops. > > Also, the looping server needs kill -9. SIGTERM and SIGINT won't stop it. > And after it dies with SIGKILL, the port is still in use for 5 minutes or > so (and the server cannot be restarted). See again above why SIGTERM and SIGINT might not necessarily do anything. But if you get into pydb with thread support, at least you should be able to determine if you are blocked in the main thread; so you can know if a SIGTERM or SIGINT will be seen. And in pydb one can kill specific threads, but you do this at your own risk because you could cause a deadlock here. As a convenience, there is a debugger "kill" command so you don't have to remember the pid. And that's there because it is really the only reliable way I know how to terminate the program. There is also a "signal" debugger command if you wanted to issue SIGTERM or SIGINT signals. > > This is really making me appreciate Java. Note that Java has preemptive threads, Python does not. From naima.mans at gmail.com Tue Feb 27 13:14:10 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 27 Feb 2007 10:14:10 -0800 Subject: spawnl and waitpid In-Reply-To: References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> Message-ID: <1172600050.794986.47140@m58g2000cwm.googlegroups.com> On 27 f?v, 18:54, Thinker wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > naima.m... at gmail.com wrote: > > i have tried as you said (cf bellow) and same result... is there > > any link which explain how a server Web read script and send the > > answer ? > > ------------------------------------------------------------------------- > > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > > \python.exe","python","Main.py") > > print 'please wait...' > > > ret = os.waitpid(pid,0) > > You have missed my idea. > Since os.waitpid will be blocked, you should print your message before > calling os.waitpid(). > > - -- > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF5HA61LDUVnWfY8gRAu8sAJ4n1dogsw7RzTxH8Ke3xnNX6gXnRQCeMOKf > /dsGHttcJc/KGpx414I7rxw= > =E3o7 > -----END PGP SIGNATURE----- hello ha ok... i tried this one and the browser don't write the message at once... I have alos tried with thread and have the same result... :( ---------------------------------------------- pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python","Main.py") print 'please wait...' sys.stdout.flush() ret = os.waitpid(pid,0) # retourne le process id if ( ret[1] != 0): print """ wait %i """ %ret[1] sys.stdout.flush() else: print """ end %i """ %ret[1] sys.stdout.flush() ----------------------------- --------- WITH THREAD ---------------- class AsyncLaunch(threading.Thread): def __init__(self, infile): threading.Thread.__init__(self) self.infile = infile def run(self): os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python",self.infile) print 'Fin background' print """please wait...""" sys.stdout.flush() sys.stdout.close() ###### # print "
fichier de log " %config.nom_log background = AsyncLaunch('Main.py') background.start() ###### print """The main program continues to run in foreground. wait...""" print """ clic""" background.join() # Wait for background task to finish print """Main program waited until background was done.""" ------------------- ----------------------- From marco.giusti at gmail.com Sat Feb 10 08:42:18 2007 From: marco.giusti at gmail.com (Marco Giusti) Date: Sat, 10 Feb 2007 14:42:18 +0100 Subject: How to find all the same words in a text? In-Reply-To: <1171114163.781621.263210@s48g2000cws.googlegroups.com> References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: <20070210134218.GB25935@localhost> On Sat, Feb 10, 2007 at 05:29:23AM -0800, Johny wrote: >I need to find all the same words in a text . >What would be the best idea to do that? >I used string.find but it does not work properly for the words. >Let suppose I want to find a number 324 in the text > >'45 324 45324' > >there is only one occurrence of 324 word but string.find() finds 2 >occurrences ( in 45324 too) >>> '45 324 45324'.split().count('324') 1 >>> ciao marco -- reply to `python -c "print 'moc.liamg at itsuig.ocram'[::-1]"` -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From sjmachin at lexicon.net Tue Feb 20 10:22:24 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 07:22:24 -0800 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: <12tm3hpom0tkqc7@corp.supernews.com> References: <12tm3hpom0tkqc7@corp.supernews.com> Message-ID: <1171984944.698061.248220@j27g2000cwj.googlegroups.com> On Feb 21, 2:05 am, Grant Edwards wrote: > On 2007-02-20, joanne matthews (RRes-Roth) wrote: > > > I'm getting different results when I add up a list of floats depending > > on the order that I list the floats. > > Don't use floating point if you expect exact results. It's not the floating point that's the problem, it's the radix, in this case 2, not being able to express n/10 exactly. As the tutorial points out, radix-10 has problems representing n/3 (and n/7 and ...) exactly. Another take: Don't expect exact results. If the input is exact to 1 or two decimal places, don't expect the sum to be exact to 15 or more decimal places. From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 17:12:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 23:12:58 +0100 Subject: Question about a single underscore. In-Reply-To: References: <45c24a89$0$19929$426a74cc@news.free.fr> Message-ID: <45c25ef1$0$29465$426a34cc@news.free.fr> Steven W. Orr a ?crit : > On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers: > (snip) > =>irrational_const = const.__class__() > =>even_const = const.__class__() > => > =>Now while I find this hack interesting, it's also totally unpythonic > =>IMHO. The usual convention is to use ALL_UPPER names for (pseudo) > =>symbolic constants, and I don't see any reason to forcefit B&D languages > =>concepts into Python. > > Ok. Now *maybe* we're getting to where I want to be. My const.py now looks > like this: > > class _const: > class ConstError(TypeError): pass > def __setattr__(self,name,value): > if self.__dict__.has_key(name): > raise self.ConstError, "Can't rebind const(%s)"%name > self.__dict__[name]=value > > import sys > sys.modules[__name__]=_const() > > and in a seperate module call key_func_consts I say: > > import const > # Define constants for Key Function Field. > KeyFuncConst = const.__class__() > KeyFuncConst.NotDefined = 0x00 > > And in my main module I have > #! /usr/bin/python > import const Note that you don't need it if you don't use it directly. > import key_func_consts > print KeyFuncConst.MSK > > > but the last print fails with A NameError, of course. key_func_consts is the module, KeyFuncConst is an attribute of this module. You either need to 1/ use a fully qualified name: import key_func_consts print key_func_consts.KeyFuncConst.MSK or 2/ import the KeyFuncConst name directly: from key_func_consts import KeyFuncConst print KeyFuncConst.MSK or 3/ use the same dirty hack as in the const module - but this is starting to be very ugly and unpythonic, so I won't give an implementation example !-) Also, note that since you did not define KeyFuncConst.MSK in the key_func_const module, you'll then have an AttributeError !-) > The goal is to be able to create classes of global constants. Then just define your "constants" in the module and import it: # key_func_const.py NOT_DEFINED = 0x00 MSK = 42 # main.py import key_func_const print key_func_const.NOT_DEFINED print key_func_const.MSK > Do I need to get the KeyFuncConst object into sys.modules somehow? I know > I'm close. Nope. You're going the wrong direction. It's a typical case of arbitrary overcomplexification. Please re-read the last paragraph of my previous post. By convention, in Python, ALL_UPPER names means "constant value, dont touch". The example I give you above is the Pythonic way of doing things, it's dead simple, and *it just works* - so why bother messing with sys.modules hacks ? From sjmachin at lexicon.net Tue Feb 27 16:51:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 27 Feb 2007 13:51:33 -0800 Subject: import parent In-Reply-To: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> References: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> Message-ID: <1172613093.793708.291850@q2g2000cwa.googlegroups.com> On Feb 28, 8:01 am, Greg Hoover wrote: > How does one get access to the class that imported a module. For example: > foo imports bar -- how does bar access foo? It shouldn't (in any language, not just Python). Callees should not in general need to inspect their caller's data structures, and should not uninvitedly alter their caller's data structures. Given Foo is a class in module foo, in general it is preferred that all operations on instances of Foo are carried out by methods of the Foo class. Given oof is such an instance, and there is a documented attribute zot, then you *may* pass oof as an arg to a bar.some_function which may do things like if oof_arg.zot > 42: oof_arg.zot = 42 but this is not the preferred way. Your subject "import parent" is "interesting". In what way is foo considered to be the parent of bar? foo imports bar which imports foo is called a "circular import". Google in this newsgroup should dredge up some threads on this topic. Bottom line: if what you want to do really would involve a circular import, then you have a design mess -- foo+bar needs to be refactored by moving functionality into different modules so that you don't get a circular import. The result may be 1, 2 (different), or 3 modules. If you tell us a bit more about what you are trying to do, we may be able to help you more. Cheers, John From http Thu Feb 8 11:51:19 2007 From: http (Paul Rubin) Date: 08 Feb 2007 08:51:19 -0800 Subject: idea for testing tools References: <87ejp1mzla.fsf@arcor.de> <45ca5f5a$0$26771$426a74cc@news.free.fr> <8764adm2jw.fsf@arcor.de> Message-ID: <7xfy9gfv94.fsf@ruckus.brouhaha.com> Jens Theisen writes: > def test_some(): > assert a == b > > didn't reveal the values for a and b, though some more complex cases > showed something. I usually use assert a == b, (a,b) From kumar.mcmillan at gmail.com Wed Feb 28 11:05:50 2007 From: kumar.mcmillan at gmail.com (Kumar McMillan) Date: Wed, 28 Feb 2007 10:05:50 -0600 Subject: PyCon blogs? In-Reply-To: References: <17892.52858.798903.806121@montanaro.dyndns.org> Message-ID: > > Was anybody blogging about PyCon (talks and/or sprints)? Got any > > pointers? or ... if you're lazy like me, read them all in one place! http://planetpython.org/ http://www.pythonware.com/daily/ http://planet.python.org/ ps. http://flickr.com/search/?q=pycon2007 :) From kernel1983 at gmail.com Thu Feb 8 21:37:50 2007 From: kernel1983 at gmail.com (kernel1983) Date: 8 Feb 2007 18:37:50 -0800 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: <1170988167.356729.187920@v33g2000cwv.googlegroups.com> References: <1170988167.356729.187920@v33g2000cwv.googlegroups.com> Message-ID: <1170988670.576168.205640@v33g2000cwv.googlegroups.com> On Feb 9, 10:29 am, "Klaas" wrote: > On Feb 6, 11:07 am, Jean-Paul Calderone wrote: > > > On Tue, 06 Feb 2007 08:40:40 -0700, Steven Bethard wrote: > > >Jean-Paul Calderone wrote: > > > > Huge amounts of my pure Python code was broken by Python 2.5. > > > >Interesting. Could you give a few illustrations of this? (I didn't run > > >into the same problem at all, so I'm curious.) > > > There are about half a dozen examples linked from here: > > > http://twistedmatrix.com/trac/ticket/1867 > > > Check out the closed ticket linked from there or the changesets for more > > detail. > > The changes listed dont' seem particularly huge considering the size, > complexity, and boundary-pushingness of Twisted, coupled with the > magnitude of the 2.5 release. > > -Mike Just keep using python2.4 From irmen.NOSPAM at xs4all.nl Mon Feb 26 18:20:47 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 27 Feb 2007 00:20:47 +0100 Subject: pickle problem - frexp() out of range In-Reply-To: <1172529903.332360.124400@z35g2000cwz.googlegroups.com> References: <1172529903.332360.124400@z35g2000cwz.googlegroups.com> Message-ID: <45e36b7d$0$339$e4fe514c@news.xs4all.nl> ahaldar wrote: > Hi: > > I have some large data structure objects in memory, and when I attempt > to pickle them, I get the following error: > > SystemError: frexp() out of range > > Are there some objects that are just too large to serialize, and if > so, is there an easy workaround without breaking up the object and > reconstructing it during deserialization? > > Here's the code I use to pickle the object: > > f = open(dir+file, "w+b") > pickle.dump(structure, f, protocol=2) # throws error > f.close() > > - abhra > Could it be that your data contains floating point numbers, where at least one of them is Inf or NaN? I think these floats cannot be pickled reliably. --Irmen From bearophileHUGS at lycos.com Thu Feb 1 21:21:57 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Feb 2007 18:21:57 -0800 Subject: A* search implementation in Python In-Reply-To: References: Message-ID: <1170382917.837428.247930@s48g2000cws.googlegroups.com> Reid Priedhorsky: > I'm looking for an open-source Python implementation of A* search for use > in a mapping application. You can try this one: http://aima.cs.berkeley.edu/python/search.html Bye, bearophile From laurent.pointal at wanadoo.fr Mon Feb 5 13:38:04 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Mon, 05 Feb 2007 19:38:04 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p7h2F1pg9igU1@mid.uni-berlin.de> Message-ID: <45c778b9$0$25928$ba4acef3@news.orange.fr> Diez B. Roggisch wrote: > m =: >@(0&{) > v =: >@(1&{) > h =: >@(2&{) > qu =: >@(3&{) > z =: i. at 0: > ret =: |.@}: > init =: z;z;z;i. > f1m =: (m,{. at qu);v;h;}. at qu > f5m =: (z;(v,{:@m);h;qu,ret at m) @ (f1m^:5) > f1h =: (z;z;(h,{:@v);(qu,ret at v)) @ (f5m^:12) > f12h =: (z;z;z;qu,ret at h,{:@h) @ (f1h^:12) > perm =: qu @ f12h @ init > ord =: *./ @ (#&>"_) @ C. > days =: -: @ ord @ perm > > > http://www.jsoftware.com/jwiki/Essays/The_Ball_Clock_Problem > > > Diez Why dont they call it "smiley" ? Operators: :-) :) :o) :-$ *_< =_= o_o X_X -_o ;) $_$ <_< >_> o_0 ><_>< ?_? '_' O.O $.$ T.T ._. u.u >-<" =] {-_-} (source: http://en.wikipedia.org/wiki/Smiley ) From Robert.Katic at gmail.com Sun Feb 18 12:14:41 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 18 Feb 2007 09:14:41 -0800 Subject: Getting a class name In-Reply-To: References: <1171744164.512365.136970@t69g2000cwt.googlegroups.com> <1171783233.733860.143500@k78g2000cwa.googlegroups.com> Message-ID: <1171818881.871094.295870@v33g2000cwv.googlegroups.com> On Feb 18, 9:17 am, "Gabriel Genellina" wrote: > En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf > escribi?: > > > I suppose that you wont get class name into its code (or before > > definition end) but not into a method definition. > > > import sys > > > def getCodeName(deap=0): > > return sys._getframe(deap+1).f_code.co_name > > > class MyClass (object): > > name = getCodeName() + '!' > > What's the advantage over MyClass.__name__? > > -- > Gabriel Genellina >>> class C(object): ... name = C.__name__ ... Traceback (most recent call last): File "", line 1, in ? File "", line 2, in C NameError: name 'C' is not defined >>> From LISTSERV at LISTSERV.SLACKINC.COM Sat Feb 3 10:40:14 2007 From: LISTSERV at LISTSERV.SLACKINC.COM (SLACK Incorporated LISTSERV Server (14.3)) Date: Sat, 3 Feb 2007 10:40:14 -0500 Subject: Message ("Your message dated Sat, 3 Feb 2007 10:40:10 -0500...") Message-ID: Your message dated Sat, 3 Feb 2007 10:40:10 -0500 with no subject has been submitted to the moderator of the IDN-L list: IDN-SysAdmin at SLACKINC.COM. From silovana.vjeverica at com.gmail Thu Feb 8 14:03:32 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Thu, 8 Feb 2007 20:03:32 +0100 Subject: Functions, parameters References: <45cb6def$0$1014$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Why don't you just read the source code ? Django is free software, you > know !-) Yes, I know. :) > What about something like: > def filter(self, **kw): > for argname, value in kw.items(): > fieldname, op = argname.split('__', 1) Yes, this is what confused me in the first place: how to separate arguments. If you call split, and split returns list of String, then you have fieldname = 'question' and startwith = 'what', and not references at question and startwith, or am I missing something big. -- http://www.nacional.hr/articles/view/23894/23 From gigs at hi.t-com.hr Thu Feb 8 14:16:09 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 08 Feb 2007 20:16:09 +0100 Subject: default mutable arguments Message-ID: I read that this is not the same: if arg is None: arg = [] arg = arg or [] def functionF(argString="abc", argList = None): if argList is None: argList = [] # < this ... def functionF(argString="abc", argList=None): argList = argList or [] # and this ... Why? thanks !!! From aleaxit at gmail.com Tue Feb 27 10:33:55 2007 From: aleaxit at gmail.com (Alex Martelli) Date: Tue, 27 Feb 2007 07:33:55 -0800 Subject: gmpy moving to code.google.com In-Reply-To: <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> References: <5f56302b0702261230y644b039dmc574112830cff771@mail.gmail.com> <5f56302b0702270259i446e1c32w5fffaf00354051b5@mail.gmail.com> Message-ID: On Feb 27, 2007, at 2:59 AM, Daniel Nogradi wrote: > Hi Alex, > > I did another test, this time with python 2.4 on suse and things are > worse than in the previous case (which was python 2.5 on fedora 3), > ouput of 'python gmp_test.py' follows: Interesting! gmpy interacts with decimal.Decimal by "monkey- patching" that class on the fly; clearly the monkey-patching isn't working with 2.4 on SuSE, so all the addition attempts are failing (all 6 of them). So the issue is finding out why this strategy is failing there, while succeeding on other Linux distros, Mac, and Windows. To that end, I have added a feature in the latest svn trunk (revision 11) to set gmpy's own options.debug flag from an environment variable named GMPY_DEBUG at startup (if that environment variable is set). If you could please svn up and rebuild, then running with GMPY_DEBUG set in the environment should give something like: brain:~/gmpy alex$ GMPY_DEBUG=1 python -c 'import gmpy' 2>&1 | tail -5 mp_allocate( 4->8 ) mp_allocate( 4->8 ) ->0x60b8b0 gmpy_module at 0x63390 gmpy_module imported decimal OK gmpy_module tweaked decimal OK This is the expected behavior when module decimal is present, while, when it's absent, you should see something like: brain:~/gmpy alex$ GMPY_DEBUG=1 python2.3 -c 'import gmpy' 2>&1 | tail -5 Initing new not in zcache mp_allocate( 4->8 ) mp_allocate( 4->8 ) ->0x3017d0 gmpy_module at 0x6de70 gmpy_module could not import decimal In each case, what matters is the last line or two after "gmpy_module at" -- the rest of the copious debugging output is irrelevant here. Module decimal is expected to be present from 2.4 forward (though it could also be explicitly installed on 2.3). However, from the test failures you report, it looks like SuSE's 2.4 does not have decimal available for importing when gmpy is starting up -- so I'd like to confirm that first. If it's confirmed, it will be interesting to discover how this happens (but that requires a SuSE installation, which I don't have) and secondarily what is gmpy to do about it -- maybe offer a warning on startup when module decimal is unexpectedly not importable but then skip the relevant unittests in that case? (Note that the tests ARE already skipped if module decimal is not importable _at test time_ -- what's really weird is that apparently on SuSE decimal CAN be imported by the tests but CANNOT be imported earlier while gmpy is loading, which is truly puzzling). I'd appreciate reports about this behavior on as many Python/Linux installations as possible -- yours, of course (to check my guess that the problem is that decimal can't be imported while gmpy is loading), but also others' (to see how widespread the problem is, etc, etc). Thanks again for reporting this, and thanks in advance to anybody who'll lend a hand in tracking down this little strangeness!!! Alex From davihigh at gmail.com Sat Feb 10 10:26:53 2007 From: davihigh at gmail.com (David Xiao) Date: 10 Feb 2007 07:26:53 -0800 Subject: Please recommend library for multithread download Message-ID: <1171121213.759544.274870@q2g2000cwa.googlegroups.com> Hello there, I am looking for library (small better) that can fetch URL and download to local file in multi-threads. urllib2 is not thread safe as I tested. What will be? From JStoneGT at aol.com Wed Feb 7 11:01:18 2007 From: JStoneGT at aol.com (JStoneGT at aol.com) Date: Wed, 7 Feb 2007 11:01:18 EST Subject: Socket and array Message-ID: Hello, How to send an array via socket to the other end?Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Tue Feb 20 01:05:38 2007 From: http (Paul Rubin) Date: 19 Feb 2007 22:05:38 -0800 Subject: threading and multicores, pros and cons References: Message-ID: <7x4pphfjnx.fsf@ruckus.brouhaha.com> Nikita the Spider writes: > note, there a (sort of) new module available that allows interprocess > communication via shared memory and semaphores with Python. You can find > it here: > http://NikitaTheSpider.com/python/shm/ This is from the old shm module that was floating around several years ago? Cool, I remember trying to find it recently and it seemed to have disappeared--the original url was dead and it wasn't mirrored anywhere. How about putting it in CheeseShop or some other such repository? Having it in the stdlib would be even better, of course. From eopadoan at altavix.com Fri Feb 16 06:53:20 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 16 Feb 2007 09:53:20 -0200 Subject: Pep 3105: the end of print? In-Reply-To: References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: On 2/15/07, Edward K Ream wrote: > > Isn't the very concept of major releases (1.x, 2.x, 3.x) that they *can* > > be not backwards-compatible with previous releases? > > Not at all. [...] It is the only intent of Python 3.0: be free of backward compatibity constraints. There are a tool called "2to3" that translates things like "print foo" to print(foo). -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From kleiner at hora-obscura.de Mon Feb 19 04:36:43 2007 From: kleiner at hora-obscura.de (Stefan Palme) Date: Mon, 19 Feb 2007 10:36:43 +0100 Subject: timeout in urllib.open() Message-ID: Hi all, is there a way to modify the time a call of urllib.open(...) waits for an answer from the other side? Have a tool which automatically checks a list of websites for certain content. The tool "hangs" when one of the contacted websites behaves badly and "never" answers... Thanks and regards -stefan- From kirk at nospam.jobsluder.net Sun Feb 4 11:02:48 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Sun, 04 Feb 2007 16:02:48 GMT Subject: Definitions of editor and IDE? References: <20070203224824.0CC7C1E400A@bag.python.org> <1170587864.512288.217940@h3g2000cwc.googlegroups.com> Message-ID: In article <1170587864.512288.217940 at h3g2000cwc.googlegroups.com>, "Paddy" wrote: > On Feb 4, 9:01 am, Necmettin Begiter > wrote: > > Can't give definitions, but here is the difference: if you use an editor, > > you > > will have to run your script or program from outside the editor; if you use > > an IDE, you will press a key or key combination in the IDE (say F9 or F5) > > and > > your program/script will run... > > Hmm, is vim an editor or an IDE? > By the above definition it would be an IDE because under the tools > menu you can run make or compilers/interpreters. > It has probably got to the stage that its a continuum from something > like Eclipse or SPE that are definitely IDE's through to ed and > notepad which are editors. I would define an IDE as a system that supports multiple tasks of the development process using a related set of interfaces. Some of these tasks may include: Searching and browsing reference documentation. Writing source code. Building/compiling projects. Evaluation using a shell or REPL. Debugging and testing. Production of graphical elements. Production of documentation. Packaging. Project management and version tracking. I'll agree that it's a spectrum with the most comprehensive IDEs supporting more different tasks of the development process. > > - Pad. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Feb 27 19:33:42 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 28 Feb 2007 01:33:42 +0100 Subject: threading a thread References: <54jm2pF20dq64U2@mid.individual.net> Message-ID: <54k0v7F1nt481U1@mid.individual.net> tubby wrote: > Have you tried it? Nmap is sequential. RTFM? | NMAP(1) Nmap Reference Guide NMAP(1) | [...] | TIMING AND PERFORMANCE | [...] While Nmap utilizes parallelism and many advanced | algorithms to accelerate these scans, the user has ultimate | control over how Nmap runs. | | --min-hostgroup ; --max-hostgroup | (Adjust parallel scan group sizes) | [...] | --min-parallelism ; --max-parallelism | (Adjust probe parallelization) | [...] > I can do the same thing in roughly 15 minutes with Python or Ruby > using threads. Have fun. > Also remember that we're dealing with IPv4 networks now. How will > we deal with larger IPv6 address spaces. Besides clustering and > distributed processing (mapreduce), it seems that threads may help > deal with some of the scaling issues I face right now. Please observe that there are simpler and easier (in many cases) means of parallelisation. For example Unix' select(). Regards, Bj?rn -- BOFH excuse #368: Failure to adjust for daylight savings time. From larry.bates at websafe.com Thu Feb 1 18:49:43 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Feb 2007 17:49:43 -0600 Subject: how to make a python windows service know it's own identity In-Reply-To: <1170357853.916290.252460@v33g2000cwv.googlegroups.com> References: <1170264160.124454.6270@j27g2000cwj.googlegroups.com> <45C23B18.5050000@websafe.com> <1170357853.916290.252460@v33g2000cwv.googlegroups.com> Message-ID: Chris Curvey wrote: > On Feb 1, 2:10 pm, Larry Bates wrote: >> Chris Curvey wrote: >>> Hi all, >>> I have used the win32com libraries to set up a service called >>> MyService under Windows. So far, so good. Now I need to run multiple >>> copies of the service on the same machine. I also have that working. >>> For monitoring and logging, I'd like each instance of the service to >>> know it's own identity (MyService1, MyService2, etc.) >>> But I can't quite seem to grasp how to do this. In the code below, >>> the command line parameter "-i" gives the service an identity, but how >>> do I get the service to understand it's identity when it is started? >>> Many thanks! >>> class MyService(win32serviceutil.ServiceFramework): >>> """NT Service.""" >>> _svc_name_ = "MyService" >>> _svc_display_name_ = "My Service" >>> _id_ = '' >>> def SvcDoRun(self): >>> provider = MyServiceClass(identifier=self._id_) >>> provider.start() >>> # now, block until our event is set... >>> win32event.WaitForSingleObject(self.stop_event, >>> win32event.INFINITE) >>> # __init__ and SvcStop snipped >>> ########################################################################### >>> if __name__ == '__main__': >>> import optparse >>> parser = optparse.OptionParser() >>> parser.add_option("-i", "--identifier", dest="identifier") >>> (opts, args) = parser.parse_args() >>> if opts.number is not None: >>> MyService._svc_name_ += opts.identifier >>> MyService._svc_display_name_ += opts.identifier >>> MyService._provider_id_ = opts.identifier >>> win32serviceutil.HandleCommandLine(MyService, >>> customInstallOptions="i:") >> What is your use case for this? Why not make a single server >> process multiple providers (store them in a list or other >> container)? >> >> -Larry Bates > > The use case is that I have a queue of jobs that need to run. My > service connects to a central "distributor" server, which hands out > jobs to complete. I'd like to be able to run multiple copies of the > distributed service so that I can make the most use of each machine > where they run. (I'm not certain of the thread safety of some of the > libraries I'm using, so I'm leery of going the multi-threaded route) > Anyway, when my service gets a job to process, I'd like to know which > copy of the service is working on which job. So I want my log > messages to look like this: > > Job 123: Host: alpha Service: MyService A > Job 124: Host: alpha Service: MyService B > Job 124: Host: beta Service: MyService C > > Is that clear, or have I muddied the waters? > Ok, makes more sense now. You will be running each service on a different computer. If I'm understanding all you need is to supply an attribute to the service that represents its internal name (the one you will use to do the logging). If I wanted to do this I would create a .INI file and read it (using ConfigParser) during service class __init__ method. Assign self.servicename=. Then use self.servicename to do my logging. I have a service somewhat like you describe and this works fine for me. -Larry From deets at nospam.web.de Mon Feb 26 09:26:35 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Feb 2007 15:26:35 +0100 Subject: Copy a module build to another machine References: <1172498509.462232.242990@t69g2000cwt.googlegroups.com> Message-ID: <54g90rF210hj6U1@mid.uni-berlin.de> bg_ie at yahoo.com wrote: > Hi, > > I have downloaded the source for PyXML-0.8.4, which has no binaries > available for Python 2.5. Therefore I built it myself doing something > like this - > > python2.5 setup.py build > python2.5 setup.py install > > having installed cygwin (with gcc). Now lets say I'd like to install > PyXML-0.8.4 on a number of other machines running the same os, what > files would I need to copy, and to where, in order to install PyXML > with just the line - > > python2.5 setup.py install > > In other words, I don't want to have to install cygwin on all these > machines and build for each machine. Instead I want to create a simple > install. I'm not sure if that really works out. You can create eggs as distribution format if you ahve setuptools installed like this: easy_install-2.5 . in the PyXML-dir. This should create an egg that you then can install on all other machines using easy_install-2.5 However, given that you used the GCC, I doubt you can really omit cygwin. If you do things with the mingw though, it might work out. Diez From bruno.desthuilliers at gmail.com Fri Feb 9 05:11:24 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 9 Feb 2007 02:11:24 -0800 Subject: Thanks for the help In-Reply-To: <1171003398.302212.232790@m58g2000cwm.googlegroups.com> References: <1171003398.302212.232790@m58g2000cwm.googlegroups.com> Message-ID: <1171015883.942971.6150@p10g2000cwp.googlegroups.com> On 9 f?v, 07:43, "azrael" wrote: > On Feb 9, 4:06 am, "Reid" wrote: > > > Hello All > > > Thanks for taking the time to answer my question. I do not need 3d stuff. > > Just a couple of buttons and menu's. The reason I am looking at python is it > > is free to download. I cannot afford VB or other commercial languages. > > > Reid > > there is also other free stuff. c, c++, c#, java,...... > i also prefere python. > > i don't want to bring you to stupid ideas, but what about illegal > software. It's a stupid idea IMHO. From no at spam.it Wed Feb 28 13:44:56 2007 From: no at spam.it (Pablo was Paolo) Date: Wed, 28 Feb 2007 19:44:56 +0100 Subject: Reading csv files using SQL Message-ID: <45e5cda7$0$17940$4fafbaef@reader1.news.tin.it> Hi, exists a Python library that allows to interface to csv files as if you manage a database, using SQL language? Something like csvjdbc in Java, where table name is file name and the field's names are in first row. Thanks! Paolo From gagsl-py at yahoo.com.ar Fri Feb 2 15:56:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Feb 2007 17:56:47 -0300 Subject: Checking default arguments References: Message-ID: En Fri, 02 Feb 2007 15:30:53 -0300, Igor V. Rafienko escribi?: >> I was wondering whether it was possible to find out which parameter > value is being used: the default argument or the user-supplied one. > That is: > > def foo(x, y="bar"): > # how to figure out whether the value of y is > # the default argument, or user-supplied? > > foo(1, "bar") => user-supplied > foo(1) => default You can use None as a flag: def foo(x, y=None): if y is None: y="bar" ... If None is valid, use your own flag: _marker=object() def foo(x, y=_marker): if y is _marker: y="bar" ... -- Gabriel Genellina From grante at visi.com Mon Feb 19 19:33:21 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 20 Feb 2007 00:33:21 -0000 Subject: Checking for EOF in stream References: Message-ID: <12tkgeh32duee72@corp.supernews.com> On 2007-02-19, GiBo wrote: > Hi! > > Classic situation - I have to process an input stream of unknown length > until a I reach its end (EOF, End Of File). How do I check for EOF? The > input stream can be anything from opened file through sys.stdin to a > network socket. And it's binary and potentially huge (gigabytes), thus > "for line in stream.readlines()" isn't really a way to go. > > For now I have roughly: > > stream = sys.stdin > while True: > data = stream.read(1024) if len(data) == 0: break #EOF > process_data(data) -- Grant Edwards grante Yow! CALIFORNIA is where at people from IOWA or NEW visi.com YORK go to subscribe to CABLE TELEVISION!! From cjw at sympatico.ca Sun Feb 4 13:59:08 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 04 Feb 2007 13:59:08 -0500 Subject: Python does not play well with others In-Reply-To: <7xirek9pdt.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "George Sakkis" writes: >>> What does "batteries included" mean to you? To me, it means you don't >>> have to install add-ons. >> So let's make a 500MB executable and add Numpy, Zope, Django, PIL, >> pretty much everything actually. Even better, make CheeseShop just a >> frontend to a build system that adds and updates automatically >> submitted packages to the core. Problem solved ! . > > Numpy should certainly be included and I think there are efforts in > that direction. As I understand it, the effort is directed towards elaborating the current array module so that it handles multi-dimensional array. This would be a good step but numpy os much more and is of minority interest and so should probably not, in my opinion, be included in the Python core. Colin W. There is also a movement to choose a web framework to > include and Django might be a good choice. I think the Zope > maintainers want to keep Zope separate and I think PIL has an > incompatible license. I'm not sure what you mean about making > CheeseShop a front end to a build system, but I certainly don't think > random user contributions should get added to the core automatically. > Including a module in the core should carry with it the understanding > that the module has undergone some reasonable evaluation by the core > maintainers and is maintained. > > I do think the core should have more stuff than it does, so that its > functionality can be on a par with competing language distros like > J2SE and PHP. Both of those distros include database connectvity > modules and web frameworks. It could be that those other packages can > include more stuff because they have more active developer communities > and can therefore expend more resources maintaining their libraries. > But if that's the case, since the Java and PHP languages themselves > suck compared with Python, we have to ask ourselves why Python has not > been able to attract similar levels of effort and what it could be > doing differently. From franz.steinhaeusler at gmx.at Tue Feb 27 03:45:42 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 27 Feb 2007 09:45:42 +0100 Subject: Python Source Code Beautifier Message-ID: Hello, I did not find any reasonable pyhton source code beautifier program (preferable gui). Some would ask why? Program it immediatly good. (BTW: Would be a nice project, if I would have more spare time). Ich have some foreign source, which are programed in a way I don't like, so I would like to have a tool, which automatically processes following options: Use Spaces, size: 4 convert structs like: if (a > b): to if a > b: fill in spaces, but not in functions between operators: a+=1 => a += 1 p(t + 1) => p(t+1) convert: self.scriptcount = self.scriptcount + 1 => self.scriptcount += 1 from "is" to "==" and "is not" to "!=" (ok a find replace could do that easily also), but in a program that would be more comfortable. break long lines (in a reasonable way) make from: if len(string) > 0: => if string: and if if len(string) < 1 orr if string == "" => if not string detect mixed line ending detect tabs mixed with space trim trailing whitespaces. .... .... Is there such a tool around? Running Pylint or Pycheck automatically afterwards would be the coronation. :) From jakub.stolarski at gmail.com Wed Feb 21 08:02:41 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 21 Feb 2007 05:02:41 -0800 Subject: PLY for standard library In-Reply-To: References: Message-ID: <1172062961.384337.295280@j27g2000cwj.googlegroups.com> On 20 Lut, 19:29, "Alan Isaac" wrote: > If not, what module providing substantially similar functionality is? > AFAIK there's no parser generator module in standard library. I would like to see PLY in standard library too. -- Jakub Stolarski From bj_666 at gmx.net Sat Feb 3 14:56:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 03 Feb 2007 20:56:43 +0100 Subject: Determining encoding of a file References: Message-ID: In , Tony Houghton wrote: > In Linux it's possible for filesystems to have a different encoding from > the system's setting. Given a filename, is there a (preferably) portable > way to determine its encoding? No. Ciao, Marc 'BlackJack' Rintsch From sturlamolden at yahoo.no Wed Feb 7 13:24:54 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 7 Feb 2007 10:24:54 -0800 Subject: multithreading concept In-Reply-To: References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> Message-ID: <1170872694.018720.301410@m58g2000cwm.googlegroups.com> On Feb 7, 6:17 pm, John Nagle wrote: > Multithread compute-bound programs on multiple CPUs are > how you get heavy number-crunching work done on multiprocessors. In the scientific community, heavy CPU-bound tasks are either parallelized using MPI and/or written in Fortran 90/95 and parallelized using an expensive vectorizing compiler. > Of course, that's not something you use Python for, at least not > until it gets a real compiler. That is also not correct: 1. Using Python does not change the complexity of the algorithm. Big-O is still the same, and Big-O is still the main determinant of performance. 2. I value my own time more than extra CPU cycles (and so does those who pay my salary). If "Python is to slow", it is less expensive to compensate by using more CPUs than using a less productive language like Java or C++. 3. Only isolated bottlenecks really gain from being statically compiled. These are usually very small parts of the program. They can be identified with a profiler (intuition usually do not work very well here) and rewritten in Pyrex, Fortran 95, C or assembly. 4. There is NumPy and SciPy, which can make Python fast enough for most CPU-bound tasks. http://www.scipy.org/PerformancePython 5. "Premature optimization is the root of all evil in computer science." (Donald Knuth) 6. Pyrex (the compiler you asked for) does actually exist. C and Fortran compilers can produce efficient code because they know the type of each variable. We have do a Python compiler that can do the same thing. It is called 'Pyrex' and extends Python with static types. Pyrex can therefore produce code that are just as efficient as hand-tuned C (see the link above). One can take the bad-performing Python code, add type declarations to the variables that Pyrex needs to generate efficient code (but all variables need not be declared), and leave the rest to the compiler. But this is only required for very small portions of the code. Transforming time-critical Python code to Pyrex is child's play. "First make it work, then make it fast." At the University of Oslo, the HPC centre has been running Python courses for its clients. Python does not perform any worse than C or Fortran, one just has to know (1) how to use it, (2) when to use it, and (3) when not to use it. 99% of benchmarks showing bad performance with Python is due to programmers not understanding which operations are expensive in interpreted languages, and trying to use Python as if it were C++. The typical example would be code that use a loop instead of using the built-in function 'map' or a vectorized array expression with NumPy. > It's also the direction games are going. I believe that is due to ignorance. Threads are implemented to be in an idle blocking state 99% of the time. > The XBox 360 forced > game developers to go that way, since it's a 3-CPU shared memory > multiprocessor. That translates directly to multicore desktops > and laptops. MPI works on SMPs. MPI does not use threads on SMPs because it performs worse than using multiple processes. From alan.franzoni_invalid at geemail.invalid Thu Feb 1 10:42:02 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Thu, 1 Feb 2007 16:42:02 +0100 Subject: Ubunu - Linux - Unicode - encoding References: <9204s2hj5eb5g7alsc8c765bltl8ti9g4f@4ax.com> Message-ID: <1m4tymklxmhra.1lcm42759ok57.dlg@40tude.net> Il Thu, 01 Feb 2007 16:02:52 +0100, Franz Steinhaeusler ha scritto: > The case: > I have a file on a WindowsXP partition which has as contents german > umlauts and the filename itself has umlauts like i????k.txt Could you please tell us a) which filesystem is that partition using (winxp may be installed on fat32 or ntfs partitions) and b) which driver are you using to read that partition (may be vfat, ntfs or fuse/ntfs-3g) and, last but not least, c) which options are passed to that driver? -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From emami at knmi.nl Tue Feb 27 04:31:03 2007 From: emami at knmi.nl (Nader Emami) Date: Tue, 27 Feb 2007 10:31:03 +0100 Subject: installing "pysqlite" Message-ID: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> I have installed "TurboGears" and I would install 'pysqlite' also. I am a user on a Linux machine. If I try to install the 'pysqlite' with 'easy_install' tool I get the next error message. The error message is longer than what I send here. % easy_install pysqlite Searching for pysqlite Reading http://cheeseshop.python.org/pypi/pysqlite/ Reading http://pysqlite.org/ Reading http://cheeseshop.python.org/pypi/pysqlite/2.3.3 Best match: pysqlite 2.3.3 Downloading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/pysqlite-2 .3.3.tar.gz Processing pysqlite-2.3.3.tar.gz Running pysqlite-2.3.3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-71B-Y0 /pysqlite-2.3.3/egg-dist-tmp-Wj2VRc warning: no files found matching 'doc/*.html' In file included from src/module.c:24: src/connection.h:33:21: sqlite3.h: No such file or directory In file included from src/module.c:24: src/connection.h:38: error: parse error before "sqlite3" Could somebody tell me what I have to do to install 'pysqlite'? With regards, Nader From rschroev_nospam_ml at fastmail.fm Tue Feb 27 16:56:43 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 27 Feb 2007 21:56:43 GMT Subject: Pixel Array => Bitmap File In-Reply-To: References: Message-ID: Jason B schreef: > Hi all, > > I'm somewhat new to Python and I'm trying to figure out the best way to > accomplish the following: > > From an array of pixel data in an XML file (given the format, width and > height of the image as attributes) I must read in the data and save it off > as a bmp file. > > I've gotten the PIL and Win32 packages and it seems that using > functionallity from each I should be able to do this, but I haven't yet > figured out how. > > Scouring the internet for a tutorial hasn't netted me anything so far, so I > was hoping someone here could point me in the right direction... - read your pixels from the XML file and assemble them in the correct format in a buffer - use Image.frombuffer() or Image.fromstring() (from PIL) to create an image from that data - use Image.save() (also from PIL) to save it as a bmp. Have a look at http://www.pythonware.com/library/pil/handbook/image.htm for the details on those methods. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From steve at REMOVEME.cybersource.com.au Sun Feb 4 22:44:46 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 05 Feb 2007 14:44:46 +1100 Subject: Parameter lists References: Message-ID: On Sun, 04 Feb 2007 17:45:04 +0100, Mizipzor wrote: > Consider the following snippet of code: > > ========================== > > class Stats: > def __init__(self, speed, maxHp, armor, strength, attackSpeed, imagePath): > self.speed = speed > self.maxHp = maxHp > self.armor = armor > self.strength = strength > self.attackSpeed = attackSpeed > self.originalImage = loadTexture(imagePath) > > ========================== > > I little container for holding the stats for some rpg character or > something. Now, I dont like the looks of that code, there are many > function parameters to be sent in and if I were to add an attribute, i > would need to add it in three places. Add it to the function > parameters, add it to the class and assign it. > > Is there a smoother way to do this? There usually is in python, hehe. There is no "right way" to handle the issue of initialising attributes. The above way is very common, easy, self-documenting and doesn't have that many disadvantages unless you have lots of parameters to deal with. > I recall when reading python tutorials that you could do something > like this: > > foo(*list_of_parameters): > > To send many parameters as a list or a tuple. Then I could assign them > like this: > > class Stats: > def __init__(self, *li): > self.speed = li[0] > self.maxHp = li[1] > (...) That's even worse. Which is correct? Stats(..., armour, stealth, ...) Stats(..., stealth, armour, ...) You have to read the code to find out. Not just the function definition, but you actually have to read through all the assignments. Bad bad bad. > Or maybe there is an even niftier way that lets me iterate through > them? Hmm... but that may lead to that I need to store them in a way > that makes it cumbersome to access them later. def __init__(self, **kwargs): for key in kwargs: if hasattr(self, key): # key clashes with an existing method or attribute raise ValueError("Attribute clash for '%s'" % key) self.__dict__.update(kwargs) === Advantages === (1) you can create new attributes without changing any code; (2) creating an instance is self-documenting: Stats(armour="chainmail", stealth=2, strength=4, ...) (3) attributes can be added in any order; (4) easy to modify the class so it inherits sensible defaults: class Stats: armour = "leather" wisdom = 10 dexterity = 10 weapon = "sword" def __init__(self, **kwargs): for key in kwargs: if self.__dict__.has_key(key): raise ValueError("Attribute clash for '%s'" % key self.__dict__.update(kwargs) === Disadvantages === (1) You have to put in the attribute name, always: Stats(armour="chainmail", stealth=2, strength=4, ...) instead of Stats("chainmail", 2, 4, ...) (2) Typos can cause strange bugs which are hard to find: Stats(armour="chainmail", stealth=2, stregnth=4, ...) Now your character is unexpectedly strong because it inherits the default, and you don't know why. (3) Easy to break your class functionality: Stats(name_that_clashes_with_a_method="something else", ...) If you've got lots of attributes, you're better off moving them to something like a INI file and reading from that: class Stats: defaults = "C:/path/defaults.ini" def __init__(self, filename=None, **kwargs): if not filename: filename = self.__class__.defaults self.get_defaults(filename) # an exercise for the reader for key in kwargs: if not self.__dict__.has_key(key): raise ValueError("Unknown attribute '%s' given" % key) self.__dict__.update(kwargs) Notice that here I've changed from testing for attributes which clash to testing for attributes which *don't* match a key in the INI file. Which is the "best" behaviour, I leave up to you to decide. -- Steven D'Aprano From answer at tnoo.net Fri Feb 9 18:24:32 2007 From: answer at tnoo.net (Martin =?iso-8859-1?Q?L=FCthi?=) Date: Sat, 10 Feb 2007 00:24:32 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52q04iF1pl3l8U1@mid.individual.net> <1171016992.962017.10540@m58g2000cwm.googlegroups.com> Message-ID: <87mz3mlxsf.fsf@tnoo.net> Alexander Alexander Schmolck writes: > I can think of two nice ways in J, 13 and 16 characters long respectively and > each expressing something essential and non-trival about the problem in a way > that would be more cumbersome in python. > > Here's the first one: > > (,,.~)^:4,'*' NB. due to Cliff Reiter, slightly adapted Well, not as interesting as your solution, but definitively less mind-boggling and much more flexible/extendible ==================================================== l = [True] pr = {True: '*', False: ' '} for k in range(15): print ''.join([pr[x] for x in l]) l = [True] + [l[i+1]^l[i] for i in range(len(l)-1)] + [True] ==================================================== more elegant solutions sought! tnoo From simon at brunningonline.net Thu Feb 1 06:42:16 2007 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 1 Feb 2007 11:42:16 +0000 Subject: ZSI and WSDL schema In-Reply-To: <1170328454.427204.245470@p10g2000cwp.googlegroups.com> References: <1170328454.427204.245470@p10g2000cwp.googlegroups.com> Message-ID: <8c7f10c60702010342p24a55f97id314b17565593cfa@mail.gmail.com> On 1 Feb 2007 03:14:14 -0800, Grzegorz Smith wrote: > Hi all. I have problem with ZSI and WSDL schema.I generate from WSDL > by wsdl2py client method for webservice. I made soap call and > something goes wrong. It might help if you were a little more specific. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From devicerandom at gmail.com Mon Feb 12 10:48:33 2007 From: devicerandom at gmail.com (devicerandom at gmail.com) Date: 12 Feb 2007 07:48:33 -0800 Subject: multiple inheritance of a dynamic list of classes? Message-ID: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Hi, I am currently using the Cmd module for a mixed cli+gui application. I am starting to refactor my code and it would be highly desirable if many commands could be built as simple plugins. My idea was: - Load a list of plugin names (i.e. from the config file, or from the plugins directory) - Import all plugins found dynamically: and this is easy, since I can do, for example: PLUGIN_NAMES=['foo', 'bar'] PLUGIN_MODULES = map(__import__, PLUGIN_NAMES) PLUGINS = [item.Commands for item in PLUGIN_MODULES] Now, what I have to do is to define my command line class. This is usually done by subclassing cmd.Cmd: class MyCli(cmd.Cmd): .... Now I want to add the commands defined in foo.Commands and bar.Commands. foo.Commands contains the functions corresponding to the new commands this way: #foo.py class Commands def do_this(self,args): ... def do_that(self,args): ... I've seen I can do it by explicitely import them and using multiple inheritance: class MyCli(cmd.Cmd , foo.Commands, bar.Commands) .... so that do_this and do_that are now methods of a Cmd command line. Now: - how can I instead have MyCli inherit from a dynamic list of modules? - is there a better way than using multiple inheritance to plug-in dynamically commands in a Cmd command line? I hope it's all clear. Thanks, Massimo From steve at REMOVE.THIS.cybersource.com.au Sat Feb 24 00:01:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 24 Feb 2007 16:01:23 +1100 Subject: Solved: Question about idiomatic use of _ and private stuff. References: Message-ID: On Fri, 23 Feb 2007 23:17:32 -0500, Steven W. Orr wrote: > On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr: > > =>I understand that two leading underscores in a class attribute make the > =>attribute private. But I often see things that are coded up with one > =>underscore. Unless I'm missing something, there's a idiom going on here. > => > =>Why do people sometimes use one leading underscore? > > I found the answer. Not quite. > It turns out that if you say: > > import foo > > then you get access to all of the attributes that are not mangled. A > single leading underscore does not cause mangling. > > If you say > > from foo import _fooa, _foob, > > then the import will fail because the _ is used only by the import to > decide that you shouldn't see _fooa or _foob. Incorrect. Let's try it. From the shell: $ cat data.py fear = "The chief weapon of the Spanish Inquisition" _parrot = "A green bird" __spam = "A nasty treat" And then from Python: >>> from data import fear, _parrot, __spam >>> fear 'The chief weapon of the Spanish Inquisition' >>> _parrot 'A green bird' >>> __spam 'A nasty treat' Python only ignores _names when you call "from module import *". Here are the underscore rules: (1) In the interactive interpreter, the name "_" is automatically set to the result of the last command. (2) Names with a SINGLE lead underscore are ignored when you say "from module import *". They are imported if you ask for them directly, and in the normal "import module" form. (3) Class attributes, but not other objects, with TWO leading underscores have their names mangled by Python. E.g. Parrot.__method is mangled to Parrot._Parrot__method. (4) Names with two leading underscores and two trailing underscores may be reserved for special methods (e.g. __init__, __str__, etc.) and objects (e.g. __all__ in packages, __name__, etc.). While Python doesn't prohibit you from creating your own methods with leading and trailing underscores, it is discouraged. (5) If you want to give an object a name which clashes with a built-in, the convention is to append a single TRAILING underscore to the name (e.g. print_). Hope that's clear now. -- Steven. From deets at nospam.web.de Sun Feb 18 04:50:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Feb 2007 10:50:37 +0100 Subject: PyDev on Mac In-Reply-To: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> Message-ID: <53qlrtF1tm3brU1@mid.uni-berlin.de> Ahmer schrieb: > I've been trying to set up PyDev on my new MacBook Pro, but i have not > had an success. > > Could you please help! Just wait until my crystal ball comes back from the cleaners, and I will start looking at your problem. As you can lay back and do nothing while that happens, I suggest you take this highly entertaining read: http://www.catb.org/~esr/faqs/smart-questions.html Diez From max at alcyone.com Thu Feb 1 03:25:58 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Feb 2007 00:25:58 -0800 Subject: how to "free" an object/var ? In-Reply-To: References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> <1170264406.588032.116550@s48g2000cws.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Ste_ph_en??? > > I know the ph-form of the name is marginally more popular, but dammit my > name is right there just two lines above where Paddy started typing, how > hard is it to get it right? > > It's not like I spell my name with four M's and a silent Q like the famous > author Farles Wickens *wink* "I knew a guy whose first name was Ed. He was so cool, he spelled it with a hyphen." -- George Carlin -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From bignose+hates-spam at benfinney.id.au Tue Feb 27 20:59:07 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Feb 2007 12:59:07 +1100 Subject: Is there a technic to avoid this bug References: Message-ID: <87fy8rxct0.fsf@benfinney.id.au> hg writes: > I spent a few hours find this bug: > > value == self.Get_Value() > if value == WHATEVER: > do this > > instead of > value = self.Get_Value() > if value == WHATEVER: > do this > > Is there a way to avoid such a bug with some type of construct ? Use pylint to check your code for common mistakes. ===== bad_assign.py ===== """ Demonstrate a logical error """ value = None value == 10 if value == 10: print "Yep" else: print "Nope" ===== $ python ./bad_assign.py Nope $ pylint ./bad_assign.py ************* Module bad_assign C: 2: Invalid name "value" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) W: 4: Statement seems to have no effect [...] -- \ "When I was crossing the border into Canada, they asked if I | `\ had any firearms with me. I said, 'Well, what do you need?'" | _o__) -- Steven Wright | Ben Finney From Tiziano.Ferrero at gmail.com Fri Feb 16 11:36:27 2007 From: Tiziano.Ferrero at gmail.com (Urlet) Date: 16 Feb 2007 08:36:27 -0800 Subject: CENSURING FEMALE SHALLOWNESS Message-ID: <1171643787.520878.139120@j27g2000cwj.googlegroups.com> A thought-provoking, yet genuine document supporting recognition of the role of true fathers, even if ex-lifeguards at the Hotel Riviera. Against Blondes' momentary hanky-panky that, however, has long-term consequences. http://www.youtube.com/watch?v=RtDfdlsgREI From http Tue Feb 6 03:01:48 2007 From: http (Paul Rubin) Date: 06 Feb 2007 00:01:48 -0800 Subject: Taint (like in Perl) as a Python module: taint.py References: <1170713584.199237.22210@v33g2000cwv.googlegroups.com> <87iregcacw.fsf@benfinney.id.au> Message-ID: <7xwt2vvhn7.fsf@ruckus.brouhaha.com> "Gabriel Genellina" writes: > I'm not convinced at all of the usefulness of tainting. > How do you "untaint" a string? By checking some conditions? In perl? I don't think you can untaint a string, but you can make a new untainted string by extracting a regexp match from the tainted string's contents. > Let's say, you validate and untaint a string, regarding it's future > usage on a command line, so you assume it's safe to use on os.system > calls - but perhaps it still contains a sql injection trap (and being > untainted you use it anyway!). Well, ok, you didn't check it carefully enough, but at least you made an attempt. Taint checking is a useful feature in perl. > Tainting may be useful for a short lived string, one that is used on > the *same* process as it was created. And in this case, unit testing > may be a good way to validate the string usage along the program. Unit testing is completely overrated for security testing. It checks the paths through the program that you've written tests for. Taint checking catches errors in paths that you never realized existed. > - for sql injection, use parametrized queries, don't build SQL > statements by hand. > - for html output, use any safe template engine, always quoting inputs. > - for os.system and similar, validate the command line and arguments > right before being executed. and so on. Right, but it's easy to make errors and overlook things, and taint checking catches a lot of such mistakes. From steve at REMOVEME.cybersource.com.au Mon Feb 12 02:55:33 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 12 Feb 2007 18:55:33 +1100 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> <1171264811.509582.224870@p10g2000cwp.googlegroups.com> Message-ID: On Sun, 11 Feb 2007 23:20:11 -0800, John Machin wrote: > Now for the algorithm: all of that testing to see if you are about to > sail off the end of the world is a bit ugly and slow. You can use bit- > bashing, as Paul suggested, even though it's on Steven D'Aprano's list > of 6 deadly sins :-) Heh. Being a smart-alec is number 7 :-P Seriously, this is Python. Are you *sure* bit-bashing is going to be faster than the alternative? If this was C, or assembly, you'd almost certainly be right. But Python is heavily object-oriented, and bit manipulations are just methods, with all the overhead that entails. >>> import timeit >>> timeit.Timer("3 | 2", "").repeat() [0.33678007125854492, 0.33447504043579102, 0.33331012725830078] >>> timeit.Timer("3 < 2", "").repeat() [0.30328893661499023, 0.29070115089416504, 0.28839397430419922] The problem with bit-bashing, masking etc. is that except for the most simple cases it is quite obfuscated. If you aren't going to gain a serious performance boost, why bother? -- Steven D'Aprano From nathan.shair at gmail.com Fri Feb 16 18:37:50 2007 From: nathan.shair at gmail.com (nathan.shair at gmail.com) Date: 16 Feb 2007 15:37:50 -0800 Subject: output to console and to multiple files In-Reply-To: <1171667267.259758.68440@k78g2000cwa.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> <1171645473.844315.152020@k78g2000cwa.googlegroups.com> <1171667267.259758.68440@k78g2000cwa.googlegroups.com> Message-ID: <1171669070.320984.283550@q2g2000cwa.googlegroups.com> On Feb 16, 4:07 pm, garri... at gmail.com wrote: > On Feb 16, 3:28 pm, "Gabriel Genellina" wrote: > > > > > That's ok inside the same process, but the OP needs to use it "from a > > subprocess or spawn". > > You have to use something like tee, working with real file handles. > > I'm not particularly familiar with this, but it seems to me that if > you're trying to catch stdout/stderr from a program you can call with > (say) popen2, you could just read from the returned stdout/stderr > pipe, and then write to a series of file handles (including > sys.stdout). > > Or am I missing something? =) > > ~G That works, but it isn't live streaming of stdout/stderr. Most of the time, if you stream both, one could lock the process, or have the stdout/stderr printed in the wrong order. From popuser at christest2.dc.k12us.com Wed Feb 21 12:27:23 2007 From: popuser at christest2.dc.k12us.com (Pop User) Date: Wed, 21 Feb 2007 12:27:23 -0500 Subject: Regex Speed In-Reply-To: <1172049029.217002.55560@v33g2000cwv.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172049029.217002.55560@v33g2000cwv.googlegroups.com> Message-ID: <45DC80FB.5010409@christest2.dc.k12us.com> John Machin wrote: > Or a Glushkov NFA simulated by bit parallelism re module ... see > http://citeseer.ist.psu.edu/551772.html > (which Russ Cox (author of the paper you cited) seems not to have > read). > NR-grep looks interesting, I'll read that. Thanks. > Cox uses a "pathological regex" (regex = "a?" * 29 + "a" * 29, in > Python code) to make his point: grep uses a Thompson gadget and takes > linear time, while Python perl and friends use backtracking and go off > the planet. > > It might be pathological but based on the original posters timings his situation seems to relate. My main point was that its quite possible he isn't going to get faster than grep regardless of the language he uses and if grep wins, use it. I frequently do. > Getting back to the "It would be nice ..." bit: yes, it would be nice > to have even more smarts in re, but who's going to do it? It's not a > "rainy Sunday afternoon" job : One of these days. :) From mail at timgolden.me.uk Fri Feb 23 06:48:48 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 23 Feb 2007 11:48:48 +0000 Subject: CSV(???) In-Reply-To: References: Message-ID: <45DED4A0.4030301@timgolden.me.uk> Philipp Pagel wrote: > David C. Ullrich wrote: >> Is there a csvlib out there somewhere? > > How about csv in the standard library? > >> (Um: Believe it or not I'm _still_ using >> python 1.5.7. > > I have no idea if csv was part of the standard library backin those > days... > > But even if not: either upgrade to something less outdated or see if you > can get todays csv to work with the oldtimer. You might have a look at the Object Craft CSV module, from which the stdlib one is loosely descended, but you'd have to compile it yourself if you're on 1.5.2. http://www.object-craft.com.au/projects/csv/ TJG From kevinliu23 at gmail.com Wed Feb 28 15:26:31 2007 From: kevinliu23 at gmail.com (kevinliu23 at gmail.com) Date: 28 Feb 2007 12:26:31 -0800 Subject: How to check for remaining hard drive space in Windows? Message-ID: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> HI, I am new to Python and wanted to know how to check for the remaining disk space on my Windows machine using Python? I was thinking of using the command line "dir" and trying to extract the output from there. But I'm not sure how to extract command line strings using Python either. Anyway help would be appreciated. :) From roger.miller at nova-sol.com Wed Feb 21 15:21:56 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: 21 Feb 2007 12:21:56 -0800 Subject: eval('000052') = 42? In-Reply-To: <1172036245.213528.303000@v33g2000cwv.googlegroups.com> References: <1172036245.213528.303000@v33g2000cwv.googlegroups.com> Message-ID: <1172089316.336938.214160@v33g2000cwv.googlegroups.com> On Feb 20, 7:37 pm, "John Machin" wrote: > On Feb 21, 3:09 pm, Astan Chee wrote: > > > Hi, > > I just tried to do > > eval('00052') and it returned 42. > > Is this a known bug in the eval function? Or have I missed the way eval > > function works? > > Thanks > > Eight fives are forty. Forty plus two is forty two. I see no bug here, > only a language design strangeness which can be blamed on the then- > pervasive influence of all things from Bell Labs :-) So is this anachronism slated for removal in Python 3? From marco at waven.com Thu Feb 15 02:51:05 2007 From: marco at waven.com (Marco) Date: Thu, 15 Feb 2007 15:51:05 +0800 Subject: How to write a programe that include both pipe(low speed system call) and signal Message-ID: <5c62a320702142351h47a20e4dg1d9cac30d69dc21e@mail.gmail.com> Hi, I have know that signal will interrupt some kind low speed system call like pipe. But how to design a program that both support signal and pipe? I have a mplayer.py to play movie via os.popen2() and mplayer slave mode. And there is a mplayer_ctl.py send signal to mplayer.py to trigger function from mplayer.py. Sometimes os.popen2() is reading or writing when user run mplayer_ctl.py the bad things raise... Is there some better way to design the programe? Thank you -- LinuX Power From alan.franzoni_invalid at geemail.invalid Wed Feb 28 11:12:12 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 28 Feb 2007 17:12:12 +0100 Subject: Python Source Code Beautifier References: Message-ID: <1gvfzpau4gxx3$.1r9poiuldqrtm$.dlg@40tude.net> Il Wed, 28 Feb 2007 07:53:47 +1100, Delaney, Timothy (Tim) ha scritto: > Alan Franzoni wrote: >> the += operator is syntactic sugar just to save time... if one >> doesn't use it I don't think it's a matter of beauty. > > This change can have semantic differences, and so should not be done for > anything except basic, immutable objects (such as integers). As such, it > can't be done automatically. Yeah, that's right, it could have semantic differences, but that shouldn't be the case anyway. I mean, if I don't define an __iadd__ method, writing a += n or a = a + n is just the same, right? So, if I bother to define an __iadd__ method, I should make sure it works just the same, or I would introduce a very strange and hard-to-understand behaviour. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From jonc at icicled.net Sun Feb 4 00:48:53 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sat, 3 Feb 2007 23:48:53 -0600 Subject: "President Bush ... you are under arrest" - 911 truth video by Dr Morgan Reynolds, Former Chief Economist under Bush In-Reply-To: <1170564986.884781.277460@v33g2000cwv.googlegroups.com> References: <1170564986.884781.277460@v33g2000cwv.googlegroups.com> Message-ID: <200702032348.53086.jonc@icicled.net> dude, please go spam elsewhere. don't post unrelated material here. From deets at nospam.web.de Thu Feb 22 09:36:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 15:36:42 +0100 Subject: plugin development best practices References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> <1172154115.054296.214120@t69g2000cwt.googlegroups.com> Message-ID: <545o3qF1v23j6U1@mid.uni-berlin.de> > Simple plugin system proposal: > > have a package (directory with __init__.py) called plugins where the > actual plugins are modules in this directory. > > When the main script imports the plugins package, all plugin modules > would be available as plugins.pluginA, plugins.pluginB , etc. > > A registry of available plugins would be available as a simple > dir(plugins). > > code in the main script than wished to use a given plugin, would only > have to look in the registry before calling any code from a given > plugin. > > What is wrong/missing with this simple framework? Nothing wrong. It's just one way of doing it. But it requires you to have all plugins being part of one module, in one location. Depending on what you want to do, this won't suffice. For example if your app is installed in a system path you aren't supposed to write to - how do you install your individual plugin? easy_install allows you to install to a folder that is contained in the PYTHONPATH, and then you can discover entrypoints. But please, do as we suggested: read the past discussions. Depending on what _you_ actually want to accomplish, you're proposal is enough. But don't expect it to become the "one plugin system to rule them all"-solution. diez From sjmachin at lexicon.net Fri Feb 9 20:04:43 2007 From: sjmachin at lexicon.net (John Machin) Date: 9 Feb 2007 17:04:43 -0800 Subject: Matching Strings In-Reply-To: References: Message-ID: <1171069483.338976.165320@p10g2000cwp.googlegroups.com> On Feb 10, 11:03 am, rshep... at nospam.appl-ecosys.com wrote: > I'm not sure how to change a string so that it matches another one. > > My application (using wxPython and SQLite3 via pysqlite2) needs to compare > a string selected from the database into a list of tuples with another > string selected in a display widget. Tuple? Doesn't that give you a clue? > > An extract of the relevant code is: > > selName = self.polTree.GetItemText(selID) > ... > for item in self.appData.polNat: > print 'Item: ', item, '\n', 'selName: ', selName, '\n' > if item == selName: > print '***** ', self.appData.polNat[1] > > The last comparison and print statement never work because the strings are > presented this way: What you mean is: The way you have presented the strings is confusing you, and consequently you have written a comparison that will not work :-) > > Item: (u'ground water',) Hmmmm. That comma in there is interesting. I wonder where the parentheses came from. What did the man mutter about a list of tuples? > selName: ground water > > What do I need to do to 'Item' to strip the parentheses, unicode symbol, > single quotes, and comma? Nothing. They're not there. It's all in your mind. > Do I want 'raw' output? What is "raw output"? > If so, how do I specify > that in the line 'if item == selName:'? That's a comparison, not output. Step 1: Find out what you've *really* got there: Instead of print 'Item: ', item, '\n', 'selName: ', selName, '\n' do this: print 'item', repr(item), type(item) print 'selName', repr(selName), type(selName) Step 2: Act accordingly. Uncle John's Crystal Balls (TM) predict that you probably need this: if item[0] == selName: HTH, John From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 26 17:31:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 26 Feb 2007 23:31:41 +0100 Subject: how can I create/set a 'file' reference in a attribute of a class References: <1172528624.153189.218200@8g2000cwh.googlegroups.com> Message-ID: <54h5edF20e1e4U1@mid.individual.net> ken wrote: > Hi, > i have a class: > > class LogHandler(ContentHandler): > # a reference to a file open by some other function/class > outputFile; What do you intend to achieve with this last line, and what's the ';' for? > First, I get an error saying 'NameError: global name 'outputFile' > is not defined' , how can I declare outputFile as a 'file > reference'? If I'm not mistaken it would be best to read the Python tutorial. > Second , how can I set this file reference after I create the > object 'LogHandler'? You shouldn't create an object that has the same name as its class. Anyway, you can open a file using var = file("/path/to/file") > How can I do that? > f = open('dummyFile.txt'); > curHandler = LogHandler() > curHandler.file = f Is it this you want to do? class LogHandler(ContentHandler): pass f = file("dummyfile.txt") curHandler = LogHandler() curHandler.file = f Seems quite pointless to me. I'm still confused about your intentions. Regards, Bj?rn -- BOFH excuse #111: The salesman drove over the CPU board. From emami at knmi.nl Mon Feb 26 10:46:59 2007 From: emami at knmi.nl (Nader Emami) Date: Mon, 26 Feb 2007 16:46:59 +0100 Subject: ez_setup.py In-Reply-To: References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> Message-ID: <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> Tim Golden wrote: > Nader Emami wrote: >> L.S., >> >> I have installed locally Python-2.4.4 without any problem. Then I >> would install the "ez_setup.py" to be able using of "easy_install" >> tool, but I get the next error: >> >> %python ez_setup.py >> Traceback (most recent call last): >> File "ez_setup.py", line 223, in ? >> main(sys.argv[1:]) >> File "ez_setup.py", line 155, in main >> egg = download_setuptools(version, delay=0) >> File "ez_setup.py", line 111, in download_setuptools >> import urllib2, shutil >> File "/usr/people/emami/lib/python2.4/urllib2.py", line 108, in ? >> import cookielib >> File "/usr/people/emami/lib/python2.4/cookielib.py", line 35, in ? >> from calendar import timegm >> File "/usr/people/emami/calendar.py", line 23, in ? >> import pygtk >> ImportError: No module named pygtk >> >> I don't understand what is the problem! Could somebody tell me what I >> have to do to solve it? > > > You have a module called "calendar" in your user directory > /usr/people/emami/calendar.py which is shadowing the stdlib > calendar module -- which doesn't get used much so you've > probably never noticed. Either rename your local one or take > your home folder off the Python path... at least for long enough > for ez_setup to do its stuff. > > TJG How can do the second solution, (take off the home from Python path)? From gagsl-py at yahoo.com.ar Sun Feb 18 23:52:10 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 01:52:10 -0300 Subject: Logging errors to a file References: <1171854035.318628.28730@p10g2000cwp.googlegroups.com> Message-ID: En Mon, 19 Feb 2007 00:00:35 -0300, Harlin Seritt escribi?: > Is there any way to automatically log errors that occur within an > executed script to a file? The logging module. You may want to enclose your main entry point in a try/except block, just to be sure you catch everything. (*Almost* everything; a multithreaded program may require additional catching of errors) -- Gabriel Genellina From gibo at gentlemail.com Wed Feb 21 19:41:01 2007 From: gibo at gentlemail.com (GiBo) Date: Thu, 22 Feb 2007 13:41:01 +1300 Subject: Which Crypto Library? Message-ID: <45DCE69D.40506@gentlemail.com> Hi I need some encryption done in my Python 2.5 application. I wonder what's the most recommended library? I've found M2crypto and some OpenSSL wrappers and Python Cryptography Toolkit and some others. No surprise I'm confused :-) What's the most often used library for crypto? For now I need a simple AES, no asymmetric crypto or GPG involved. Thanks! GiBo From grahamd at dscpl.com.au Mon Feb 5 18:40:47 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 5 Feb 2007 15:40:47 -0800 Subject: Python does not play well with others In-Reply-To: <7xzm7sryao.fsf@ruckus.brouhaha.com> References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> <7xzm7sryao.fsf@ruckus.brouhaha.com> Message-ID: <1170718846.989763.204120@s48g2000cws.googlegroups.com> On Feb 6, 10:15 am, Paul Rubin wrote: > "Graham Dumpleton" writes: > > There is also much more possibility for code, if it runs up extra > > threads, to interfere with the operation of the Apache parent process. > > Certainly launching any new threads should be postponed til after the > fork. Except that you can't outright prevent it from being done as a Python module could create the threads as a side effect of the module import itself. I guess though if you load a module which does that and it screws things up, then you have brought it on yourself as it would have been your choice to make mod_python load it in the first place if the feature was there. :-) From ms at cerenity.org Sat Feb 3 07:17:31 2007 From: ms at cerenity.org (Michael) Date: Sat, 03 Feb 2007 12:17:31 +0000 Subject: Where Does One Begin? References: <1170465286.881096.262380@v33g2000cwv.googlegroups.com> Message-ID: <45c47cc2$0$8736$ed2619ec@ptn-nntp-reader02.plus.net> George Sakkis wrote: > On Feb 2, 3:39 pm, Mister Newbie wrote: > >> I have no programming experience. I want to learn Python so I can make >> simple, 2D games. Where should I start? Can you recommend a good book? >> >> Thank you. > > http://www.amazon.com/Game-Programming-Python-Development/dp/1584502584 It's a nice book, but totally inappropriate in my opinion for someone who says they have no programming experience. Michael. From naima.mans at gmail.com Tue Feb 27 08:39:51 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 27 Feb 2007 05:39:51 -0800 Subject: spawnl and waitpid In-Reply-To: References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> Message-ID: <1172583591.509707.190240@p10g2000cwp.googlegroups.com> On 27 f?v, 12:27, Thinker wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > > > > naima.m... at gmail.com wrote: > > On 27 f?, 11:28, Thinker wrote: > > naima.m... at gmail.com wrote: > >>>> hello, I run a python cgi script under Apache... and while > >>>> the script is running i want to display a "please wait" > >>>> message until the script finish. I have tried to do this but > >>>> the "please wait" message appears at the script end (which is > >>>> useless at this time! ) > > You should flush sys.stdout after you print messages, or the > > message will keep in buffer untill buffer is full or process > > terminated. > > > Hello > > thanks for answering i have flush like this but same result .. the > > server wait until the end... > > pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ > > \python.exe","python","Main.py") sys.stdout.flush() ret = > > os.waitpid(pid,0) > > Your program will be blocked here until child process being terminated. > You should print your messages before this line. > > > if ( ret[1] != 0): print """ wait %i """ %ret[1] > > sys.stdout.flush() else: print """ end %i """ %ret[1] > > sys.stdout.flush() > > - -- > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF5BWS1LDUVnWfY8gRAkp8AKCAcTKi/MO6sfkGBBEcMjfpH42O1wCeN14I > 0AZ83oVacK0hKik4YC/jfCA= > =3h7d > -----END PGP SIGNATURE------ Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - thanks again i have tried as you said (cf bellow) and same result... is there any link which explain how a server Web read script and send the answer ? ------------------------------------------------------------------------- pid = os.spawnl(os.P_NOWAIT,"c:\\python25\ \python.exe","python","Main.py") ret = os.waitpid(pid,0) print """please wait ....""" sys.stdout.flush() # retourne le process id if ( ret[1] != 0): print """ wait %i """ %ret[1] sys.stdout.flush() else: print """ end %i """ %ret[1] sys.stdout.flush() --------------------------------------------------------------------------- thanks From martin.wiechert at gmx.de Thu Feb 8 13:11:02 2007 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Thu, 8 Feb 2007 19:11:02 +0100 Subject: Simple SVN/CVS-like library in Python? In-Reply-To: References: Message-ID: <200702081911.02384.martin.wiechert@gmx.de> On Wednesday 07 February 2007 21:29, Andrea Gavana wrote: > Hi All, > > in our office we work with quite complex input files for a > reservoir simulator. Those files have thousands of keywords, switches, > sub-keywords and whatever. Every time a modification is requested, we > modify the input file and re-run the simulator. Obviously, the > possible modifications are innumerable: so, after few months, we lose > the records of all the changes we made during time and we don't have > anymore a clear history of our work. This can be a problem, as > sometimes it happens that an old input file is requested by > collegues/sub-companies, and it is a pain to retrieve the correct file > and results. > So, I have written a GUI in wxPython that could help us in tracking > the history, but I was wondering if there exists a small and simple > SVN/CVS-like library in Python that may help us in a better way, > storing modifications/changes and showing which input file are the > "children" of (are derived from) another input file (older). > But I am open to all possible suggestions to improve/modify the > software, as this is an area in which my experience is about nothing > above zero. > > Thank you very much for every hint. http://www.selenic.com/mercurial/wiki/ http://www.selenic.com/mercurial/wiki/index.cgi/HgkExtension > > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.virgilio.it/infinity77/ From steven.bethard at gmail.com Thu Feb 1 16:12:15 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 01 Feb 2007 14:12:15 -0700 Subject: Sorting a list In-Reply-To: <45c254a2$0$674$426a34cc@news.free.fr> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> <45c254a2$0$674$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > If you want to prevent this from happening and don't mind creating a > copy of the list, you can use the sorted() function with the key and > reverse arguments and operator.itemgetter: > > >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), > ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')] > >>> from operator import itemgetter > >>> sorted(lines, key=itemgetter(0), reverse=True) > [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), > ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')] You don't need to use sorted() -- sort() also takes the key= and reverse= arguments:: >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), ... ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ... ('1996', 'aaa')] >>> from operator import itemgetter >>> lines.sort(key=itemgetter(0), reverse=True) >>> lines [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')] STeVe From george.sakkis at gmail.com Sun Feb 25 21:13:45 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 25 Feb 2007 18:13:45 -0800 Subject: modifying a list while iterating through In-Reply-To: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> References: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> Message-ID: <1172456025.496869.316560@8g2000cwh.googlegroups.com> On Feb 25, 8:12 pm, dustin.g... at gmail.com wrote: > consider the following working loop where Packet is a subclass of > list, with Packet.insert(index, iterable) inserting each item in > iterable into Packet at consecutive indexes starting at index. > > i=0 > while(i if packet[i:i+5]==Packet("01110"): > packet.insert(i, "01111") > i+=10 #skip the 5 bits inserted, and skip the 5 bits just > checked bc overlap should not trigger insertion > else: i+=1 > > is there a way to do this more elegantly? seems like a big kludge. Unless I missed something, this is a simple string replacement: ''.join(packet).replace('01110', '0111001111') George From steven.bethard at gmail.com Mon Feb 5 09:01:26 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 05 Feb 2007 07:01:26 -0700 Subject: Python 3.0 (Was: when will python 2.5 take in mainstream?) In-Reply-To: References: <4Rrxh.18423$pQ3.12414@newsread4.news.pas.earthlink.net> <1170631417.253200.136330@h3g2000cwc.googlegroups.com> Message-ID: Laurent Pointal wrote: > For Python 3.0, AFAIK its a big rewrite and developers know that it will > be uncompatible in large parts with existing code. Wrong on both counts. ;-) Python 3.0 is not a rewrite. It's based on the same code base as the 2.X line, but with a lot of the old deprecated things removed. And, while Python 3.0 is allowing itself to break backwards compatibility, at least that the Python level, it should be largely compatible with the 2.X line. There will be some breakages, but (1) they shouldn't be too extensive and (2) there will be utilities to help you update your code. In many cases, it will be possible to write code that works in both Python 2.X and 3.0. STeVe From deets at nospam.web.de Sun Feb 18 12:01:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Feb 2007 18:01:11 +0100 Subject: PyDev on Mac In-Reply-To: <1171812580.477975.37060@t69g2000cwt.googlegroups.com> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> <1171812580.477975.37060@t69g2000cwt.googlegroups.com> Message-ID: <53rf37F1ttqnuU1@mid.uni-berlin.de> Ahmer schrieb: > On Feb 18, 4:50 am, "Diez B. Roggisch" wrote: >> Ahmer schrieb: >> >>> I've been trying to set up PyDev on my new MacBook Pro, but i have not >>> had an success. >>> Could you please help! >> Just wait until my crystal ball comes back from the cleaners, and I will >> start looking at your problem. >> >> As you can lay back and do nothing while that happens, I suggest you >> take this highly entertaining read: >> >> http://www.catb.org/~esr/faqs/smart-questions.html >> >> Diez > > > The main problem seems to be locating Python. > > Even though I installed the official python for mac, it says the > interpreter is invalid. > So I tried jPython, no succes on that either. It always tells me I am > using an invlaid interpreter. crystal ball still not available. Who tells you what exactly when you do what? Is there a shell-script involved, what happens if you enter "python" at the commandline and press return? All this are uneccessary guessing games because you don't give enough context. Which is one of the many things mentioned on the site I suggested you to read. So I think you should read it again. Diez From bignose+hates-spam at benfinney.id.au Thu Feb 1 21:21:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 13:21:47 +1100 Subject: Calculating future dates References: <1170377490.664368.175860@a75g2000cwd.googlegroups.com> <1170377690.176241.96590@p10g2000cwp.googlegroups.com> <1170378285.708350.100830@s48g2000cws.googlegroups.com> Message-ID: <87k5z1uwn8.fsf@benfinney.id.au> "Toine" writes: > On Feb 1, 4:54 pm, "Dan Bishop" wrote: > > str(datetime.date.today() + datetime.timedelta(31)) > > Your example gave me a few errors but I was able to adapt it into > this: > > str(date.today() + timedelta(31)) That only works if you're importing 'date' and 'timedelta' into the current namespace. It's better to keep them in the 'datetime' namespace, so it's clear what comes from where. >>> import datetime >>> str(datetime.date.today() + datetime.timedelta(31)) -- \ "How many people here have telekenetic powers? Raise my hand." | `\ -- Emo Philips | _o__) | Ben Finney From martin.laloux at gmail.com Tue Feb 27 04:22:43 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 27 Feb 2007 01:22:43 -0800 Subject: ArcGIS and Python In-Reply-To: References: Message-ID: <1172568162.964867.25430@m58g2000cwm.googlegroups.com> Try Esri http://support.esri.com/index.cfm?fa=forums.gateway or http://geography.sdsu.edu/People/Pages/jankowski/public_html/web683/lectures683.htm From shanekwon at gmail.com Tue Feb 13 21:37:01 2007 From: shanekwon at gmail.com (agent-s) Date: 13 Feb 2007 18:37:01 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: <1171420621.676864.244230@v45g2000cwv.googlegroups.com> OK I just realized that a list of lists can be accessed in the same way a 2d array would be accessed. Thanks anyways guys. From mensanator at aol.com Sat Feb 10 23:38:30 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Feb 2007 20:38:30 -0800 Subject: pygame and python 2.5 In-Reply-To: <1171145277.777740.179060@h3g2000cwc.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> Message-ID: <1171168710.785138.265650@a34g2000cwb.googlegroups.com> On Feb 10, 4:07?pm, "Ben Sizer" wrote: > On Feb 10, 6:31 am, "mensana... at aol.com" wrote: > > > On Feb 9, 11:39?am, "Ben Sizer" wrote: > > > > Hopefully in the future, some of those convoluted steps will be fixed, > > > but that requires someone putting in the effort to do so. As is often > > > the case with Python, and indeed many open source projects, the people > > > who are knowledgeable enough to do such things usually don't need to > > > do them, as their setup already works just fine. > > > So you're saying the knowledgeable people's attitude > > is "fuck everyone else as lomg as it's not MY problem"? > > > And you people complain about Microsoft. > > Am I one of "those people"? You don't exactly make it clear. I'm talking about the people who complain about Microsoft making the VC6 compiler no longer legally available and yet are so irresponsible that they use it for the latest release. > > But yes, there is a lot of "well, it works for me" going around. If > you do that long enough, people stop complaining, so people wrongly > assume there's no longer a problem. This is partly why Python has > various warts on Windows and why the standard libraries are oddly > biased, why configuring Linux almost always ends up involving hand- > editing a .conf file, why the leading cross-platform multimedia > library SDL still doesn't do hardware graphics acceleration a decade > after such hardware became mainstream, and so on. > > However, the difference between the open-source people and Microsoft > is the the open-source people aren't being paid by you for the use of > their product, so they're not obligated in any way to help you. This argument has become tiresome. The Python community wants Python to be a big fish in the big pond. That's why they make Windows binaries available. > After all, they have already given freely and generously, and if they choose > not to give more on top of that, it's really up to them. Right. Get people to commit and then abandon them. Nice. > Yes, it's > occasionally very frustrating to the rest of us, but that's life. As the Kurds are well aware. > The best I feel I can do is raise these things on occasion, > on the off-chance that I manage to catch the attention of > someone who is > altruistic, knowledgeable, and who has some spare time on > their hands! Someone who, say, solved the memory leak in the GMPY divm() function even though he had no way of compiling the source code? Just think of what such an altruistic, knowedgeable person could do if he could use the current VC compiler or some other legally available compiler. > > -- > Ben Sizer From deets at nospam.web.de Tue Feb 6 05:36:30 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 Feb 2007 11:36:30 +0100 Subject: XMLRPC Server References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> Message-ID: <52r41eF1p17pqU1@mid.uni-berlin.de> viscanti at gmail.com wrote: > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > It's not too difficult to configure everything, but I would like to > tune it in order to receive up to 2000 calls per minute without any > problems. Do Pthon CGIs use threading? > I need to make it very efficient, but I haven't found much information > about Python CGI optimization. > The called function will update a table in a mysql db. I will use > triggers to export data from the table updated by the xmlrpc server to > other tables used by the backend application. You might consider using the twisted application server framework instead, and totally ditch the CGI, and even the apache. http://twistedmatrix.com/ http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py Diez From mfmdevine at gmail.com Fri Feb 23 04:29:37 2007 From: mfmdevine at gmail.com (amadain) Date: 23 Feb 2007 01:29:37 -0800 Subject: pexpect regex help In-Reply-To: <1172220818.916947.11650@v33g2000cwv.googlegroups.com> References: <1172099628.074816.61980@q2g2000cwa.googlegroups.com> <1172099731.535866.234380@s48g2000cws.googlegroups.com> <1172220418.035252.65410@8g2000cwh.googlegroups.com> <1172220818.916947.11650@v33g2000cwv.googlegroups.com> Message-ID: <1172222977.378427.225880@k78g2000cwa.googlegroups.com> On Feb 23, 8:53 am, "amadain" wrote: > On Feb 23, 8:46 am, "amadain" wrote: > > > > > On Feb 21, 11:15 pm, jonathan.s... at gmail.com wrote: > > > > On Feb 21, 6:13 pm, jonathan.s... at gmail.com wrote: > > > > > I have apexpectscript to walk through a cisco terminal server and I > > > > was hoping to get some help with this regex because I really suck at > > > > it. > > > > > This is the code: > > > > > index = s.expect(['login: ',pexpect.EOF,pexpect.TIMEOUT]) > > > > if index == 0: > > > > m = re.search('((#.+\r\n){20,25})(\s.*)', > > > > s.before) #<---------- MY PROBLEM > > > > print m.group(3), > > > > print ' %s %s' % (ip[0], port) > > > > s.send(chr(30)) > > > > s.sendline('x') > > > > s.sendline('disco') > > > > s.sendline('\n') > > > > elif index == 1: > > > > print s.before > > > > elif index == 2: > > > > print > > > > print '%s %s FAILED' % (ip[0], port) > > > > print 'This host may be down or locked on the TS' > > > > s.send(chr(30)) > > > > s.sendline('x') > > > > s.sendline('disco') > > > > s.sendline('\n') > > > > > This is attempting to match the hostname of the connected host using > > > > the output of a motd file which unfortunately is not the same > > > > everywhere... It looks like this: > > > > > ######################################################################### > > > > # This system is the property > > > > of: # > > > > # > > > > # > > > > # DefNet > > > > # > > > > # > > > > # > > > > # Use of this system is for authorized users > > > > only. # > > > > # Individuals using this computer system without authority, or > > > > in # > > > > # excess of their authority, are subject to having all of > > > > their # > > > > # activities on this system monitored and recorded by > > > > system # > > > > # > > > > personnel. # > > > > # > > > > # > > > > # In the course of monitoring individuals improperly using > > > > this # > > > > # system, or in the course of system maintenance, the > > > > activities # > > > > # of authorized users may also be > > > > monitored. # > > > > # > > > > # > > > > # Anyone using this system expressly consents to such > > > > monitoring # > > > > # and is advised that if such monitoring reveals > > > > possible # > > > > # evidence of criminal activity, system personnel may provide > > > > the # > > > > # evidence of such monitoring to law enforcement > > > > officials. # > > > > ######################################################################### > > > > > pa-chi1 console login: > > > > > And sometimes it looks like this: > > > > > ######################################################################### > > > > # This system is the property > > > > of: # > > > > # > > > > # > > > > # DefNet > > > > # > > > > # > > > > # > > > > # Use of this system is for authorized users > > > > only. # > > > > # Individuals using this computer system without authority, or > > > > in # > > > > # excess of their authority, are subject to having all of > > > > their # > > > > # activities on this system monitored and recorded by > > > > system # > > > > # > > > > personnel. # > > > > # > > > > # > > > > # In the course of monitoring individuals improperly using > > > > this # > > > > # system, or in the course of system maintenance, the > > > > activities # > > > > # of authorized users may also be > > > > monitored. # > > > > # > > > > # > > > > # Anyone using this system expressly consents to such > > > > monitoring # > > > > # and is advised that if such monitoring reveals > > > > possible # > > > > # evidence of criminal activity, system personnel may provide > > > > the # > > > > # evidence of such monitoring to law enforcement > > > > officials. # > > > > ######################################################################### > > > > pa11-chi1 login: > > > > > The second one works and it will print out pa11-chi1 but when there > > > > is a space or console is in the output it wont print anything or it > > > > wont match anything... I want to be able to match just the hostname > > > > and print it out. > > > > > Any ideas? > > > > > Thanks, > > > > > Jonathan > > > > It is also posted here more clearly and formatted as it would appear > > > on the terminal: http://www.pastebin.ca/366822 > > > what about using s.before.split("\r\n")[-1]? > > > A > > result=[x for x in s.before.split("\r\n") if x != ""] > print result[-1] > > should cover the blank line problem > > A sorry I just read that you are not matching sometimes. Try expecting for "ogin:" (without the first letter and trailing space). There could be no space after login: or there could be \t (tab). A From wolf_tracks at invalid.com Sat Feb 10 19:20:43 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 11 Feb 2007 00:20:43 GMT Subject: Python 2.4 pdf Tutorial--Available In-Reply-To: References: <1hpzh.5885$4H1.5133@newssvr17.news.prodigy.net> Message-ID: Gabriel Genellina wrote: > En Sat, 10 Feb 2007 16:45:08 -0300, W. Watson > escribi?: > >> I was able to download the 2.5 tutorial, but think I may need the 2.4 >> tutorial (Guido van Rossum) if it exists. Anyone know where to find it? > > Go to http://docs.python.org/ and follow the link "Locate previous > versions" > > --Gabriel Genellina > Thanks. Found the 2.4 Python Tutorial web page by Guido van Rossum, but would like the pdf. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Humans aren't the first species to alter the atmosphere; that distinction belongs to early bacteria, which some two billion years ago, invented photosynthesis. -- Field Notes from a Catastrophe, Kolbert -- Web Page: From steve at holdenweb.com Sat Feb 10 03:47:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 08:47:44 +0000 Subject: python linux distro In-Reply-To: <1171057671.866940.269130@v33g2000cwv.googlegroups.com> References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> <1170955617.478249.82460@m58g2000cwm.googlegroups.com> <1171057671.866940.269130@v33g2000cwv.googlegroups.com> Message-ID: Szabolcs Nagy wrote: >> Now what would be interesting (and *really* crazy) would be Linux (or >> BSD or whatever) distro written almost entirely *in* Python, with the >> goal of eliminating as much bash/sh as possible. >> >> That would be fun. > > actually there was(is) an os whitch is written "almost entirely *in* > Python": > http://en.wikipedia.org/wiki/Unununium_(operating_system) > > (their main site http://unununium.org seems to be down) > ^was(is)^may one day be, but probably not,^ From the quoted page: """The project is in an early development phase and as of January 2007, no significant progress was being made due to lack of developer time.[5]""" regards Steve [5]: links to a dead server -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From Eric_Dexter at msn.com Thu Feb 8 19:27:15 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 8 Feb 2007 16:27:15 -0800 Subject: Newbie Question In-Reply-To: References: Message-ID: <1170980835.761703.163120@j27g2000cwj.googlegroups.com> You have a large number of basic languages that use opengl and wxwindows. I haven't tried them but when you are looking at 3d stuff all the opengl stuff is pretty fried. You can get around this with a whole host of other 3d options including directx. I have also used borlands c++ and it does some things very well when it comes to gui.. You may want several languages unless you are doing simple tasks. On Feb 8, 6:12 pm, "John" wrote: > Visual Basic is also good. > > "Reid" wrote in message > > news:LeNyh.4130$R71.62146 at ursa-nb00s0.nbnet.nb.ca... > > > > > Hello all > > > I am just starting to play with programing again as a hobby. I have heard > > good things about python. I have not really looked into the language much. > > My question is, will python make programs with a gui under windows xp. If > it > > will do this I will explore the language more, if not I will try some > other > > language. > > > Reid- Hide quoted text - > > - Show quoted text - From bjourne at gmail.com Tue Feb 20 15:47:57 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 20 Feb 2007 21:47:57 +0100 Subject: Python 3.0 unfit for serious work? In-Reply-To: <1171990150.797668.19770@p10g2000cwp.googlegroups.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> Message-ID: <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> What a load of bull crap. Python is one of the simplest packages to have multiple version of installed. When Python 3.0 is released, all Linux distros will acquire a symlink at /usr/bin/python2 pointing to the latest Python 2.x version installed. Or something equivalent. Rest assured that Linux distributors will not drop Python 2.x support in the nearest decade. They are not stupid. On 20 Feb 2007 08:49:10 -0800, Jay Tee wrote: > Yo, > > On Feb 16, 6:07 am, Steven Bethard wrote: > > Python 3.0 is determined not to be hampered by backwards incompatibility > > concerns. It's not even clear yet that your average 2.6 code will work > > Then Python is pretty much determined to remove itself from > consideration > from various kinds of international projects like the one I work on. > We're already catching flack from people due to a few things that were > valid > in 2.2 that are not valid in 2.3 (I don't have the details but could > scare them > up). The project we work on contains code from many different people > and has to > run on thousands of computers all over the world. The installed base > at the > moment is a mix of RHEL 3, RHEL 4, and Debian, with a few other > machines thrown in. > The relevant Python versions at this moment IIRC are 2.2.3 and 2.3.4, > because these > are the native versions on those platforms. > > We are estimating, due to the speed at which our applications follow > OS releases, that > we can drop RHEL 3 (and hence Python 2.2) support a year from now. Go > figure when you > think we might be ready to require that all programs run on python > 3.0. If it's not > backwards compatible, meaning if 2.4 code doesn't run on 3.0, it's > rather likely that > strong pressure will be applied to port *away* from Python into > something less capricious. > > Bottom line: practicality and beauty is always a tradeoff. Oberon is > the most beautiful > language I ever saw, but there is almost nobody using it any more. > Too many beauty contests over who had the best proposal for a standard > library. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- mvh Bj?rn From deets at nospam.web.de Wed Feb 14 09:25:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Feb 2007 15:25:24 +0100 Subject: replacing substrings within strings References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> <53gcsbF1sbe8oU1@mid.uni-berlin.de> <1171456059.848396.42270@m58g2000cwm.googlegroups.com> <53ghdgF1slkirU1@mid.uni-berlin.de> <1171461100.321811.96180@h3g2000cwc.googlegroups.com> Message-ID: <53gkekF1qqvslU1@mid.uni-berlin.de> bearophileHUGS at lycos.com wrote: > Diez B. Roggisch: >> That's the price to pay for immutable strings. > > Right, but CPython has array.array("c") too. Using Diez Roggisch's > code: Ahhh, ze arrayz. I alwayz forget about the arrayz. Diez From cheekymontrosity at yahoo.com Mon Feb 12 18:46:23 2007 From: cheekymontrosity at yahoo.com (Sam Wortzberg) Date: Mon, 12 Feb 2007 23:46:23 GMT Subject: Make 1million in 6 weeks or less Message-ID: Legal Consultants http://legal-rx.blogspot.com/index.html will show you how to make 1 million in less than 6 weeks! From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 15:31:13 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 21:31:13 +0100 Subject: what is wrong with my python code? In-Reply-To: References: Message-ID: <45ca2feb$0$1620$426a74cc@news.free.fr> Dongsheng Ruan a ?crit : > I got feed back saying" list object is not callable". But I can't figure out > what is wrong with my code. > > A=[3,5,4,9,6,7] > l=len(A)-1 > > for i in range(l): > print A(i) > The error message is quite clear when you remember that () is the call operator. For the subscribe operator, you want []. And FWIW, Python for loops are smarter than that: A = [3,5,4,9,6,7] for i in A: print i From steveo at syslang.net Fri Feb 23 23:17:32 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 23 Feb 2007 23:17:32 -0500 (EST) Subject: Solved: Question about idiomatic use of _ and private stuff. In-Reply-To: References: Message-ID: On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr: =>I understand that two leading underscores in a class attribute make the =>attribute private. But I often see things that are coded up with one =>underscore. Unless I'm missing something, there's a idiom going on here. => =>Why do people sometimes use one leading underscore? I found the answer. It turns out that if you say: import foo then you get access to all of the attributes that are not mangled. A single leading underscore does not cause mangling. If you say from foo import _fooa, _foob, then the import will fail because the _ is used only by the import to decide that you shouldn't see _fooa or _foob. -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From arkanes at gmail.com Fri Feb 23 12:12:21 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 23 Feb 2007 11:12:21 -0600 Subject: c_string missing from ctypes? In-Reply-To: <1172250201.092615.52940@s48g2000cws.googlegroups.com> References: <1172250201.092615.52940@s48g2000cws.googlegroups.com> Message-ID: <4866bea60702230912o60da3b74m3be75cb20d1ae3fc@mail.gmail.com> On 23 Feb 2007 09:03:21 -0800, Jacob Rael wrote: > Hello, > > I was following along with this site: > > http://www.brunningonline.net/simon/blog/archives/000659.html > > and I got a error. It boils down to: > > ==================== > > In [9]: import ctypes > In [10]: dir(ctypes.c_string) > --------------------------------------------------------------------------- > Traceback (most recent call > last) > > P:\ in () > > : 'module' object has no attribute > 'c_string' > > ==================== The tutorial is out of date, ctypes.c_string was removed somewhere around version 0.6 (theres a comment to this effect in the comments under the tutorial). You want ctypes.c_buffer instead. > > > I google ctypes.c_string and many people use it. > > I am using python 2.5 with ctypes version: 1.0.1 on a windows > machine. > > I have to admit I don't know where ctypes came from. I tried to re- > install it but the window binaries only support 2.4. > As of Python 2.5 ctypes is part of the standard library. > Also: > > http://starship.python.net/crew/theller/ctypes/tutorial.html > > seems dead. > > An info is greatly appreciated. > > jr > > -- > http://mail.python.org/mailman/listinfo/python-list > From karoly.kiripolszky at gmail.com Mon Feb 5 07:45:59 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 5 Feb 2007 04:45:59 -0800 Subject: C parsing fun In-Reply-To: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> Message-ID: <1170679559.272656.145660@v33g2000cwv.googlegroups.com> and the great thing is that the algorithm can be used with any language that structures the code with brackets, like PHP and many others. From franz.steinhaeusler at gmx.at Mon Feb 5 02:17:11 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Mon, 05 Feb 2007 08:17:11 +0100 Subject: Python compiled on Windows Message-ID: Hello, I'm only curious. Why is Python and most extension (also wxPython) not built using an open source compiler like gcc or g++ on Windows? I'm always wondering, why Microsoft is still supported in that way, using VC++ 7.1, if I'm not wrong. Ok, maybe the compiled assembler code could be better, but this cannot be the reason, or? It would be wonderful (from the principle) if this could be possible. >From the standpoint of open source. What are your opinions? From fccoelho at gmail.com Thu Feb 22 10:01:58 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 07:01:58 -0800 Subject: plugin development best practices In-Reply-To: <1172155861.892583.224240@v45g2000cwv.googlegroups.com> References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> <1172154115.054296.214120@t69g2000cwt.googlegroups.com> <545o3qF1v23j6U1@mid.uni-berlin.de> <1172155861.892583.224240@v45g2000cwv.googlegroups.com> Message-ID: <1172156518.293831.253460@m58g2000cwm.googlegroups.com> On Feb 22, 12:51 pm, "Flavio" wrote: > On Feb 22, 12:36 pm, "Diez B. Roggisch" wrote: > > > > > > Simple plugin system proposal: > > > > have a package (directory with __init__.py) called plugins where the > > > actual plugins are modules in this directory. > > > > When the main script imports the plugins package, all plugin modules > > > would be available as plugins.pluginA, plugins.pluginB , etc. > > > > A registry of available plugins would be available as a simple > > > dir(plugins). > > > > code in the main script than wished to use a given plugin, would only > > > have to look in the registry before calling any code from a given > > > plugin. > > > > What is wrong/missing with this simple framework? > > > Nothing wrong. It's just one way of doing it. But it requires you to have > > all plugins being part of one module, in one location. Depending on what > > you want to do, this won't suffice. For example if your app is installed in > > a system path you aren't supposed to write to - how do you install your > > individual plugin? easy_install allows you to install to a folder that is > > contained in the PYTHONPATH, and then you can discover entrypoints. > > > But please, do as we suggested: read the past discussions. > > > Depending on what _you_ actually want to accomplish, you're proposal is > > enough. But don't expect it to become the "one plugin system to rule them > > all"-solution. > > > diez > > Oh, I have read all the links that have been suggested, but I am > looking for the simplest possible solution. > > I have no intention to create the "next Plugin system" I am just > trying to solve my own problem and in the process leave a record of a > fruitfull discussion about plugin systems. > > BTW I have yet to check TRAC's plugin system. I have look at Trac's component based pluging system and I liked it very much. If external dependencies is not an issue I believe this is the best solution. http://trac.edgewall.org/wiki/TracPlugins From skip at pobox.com Sat Feb 3 16:41:09 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 3 Feb 2007 15:41:09 -0600 Subject: Python does not play well with others In-Reply-To: <7xbqkb2pmt.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <7xbqkb2pmt.fsf@ruckus.brouhaha.com> Message-ID: <17861.373.512805.810008@montanaro.dyndns.org> Paul> Yeah well, the Wxpython, PyQt, PyGTK etc. people may feel slighted Paul> that Tkinter got included and their stuff didn't, and the Eric, Paul> Eclipse, Komodo etc. people may feel slighted that IDLE got Paul> included, but that doesn't stop Tkinter and IDLE from being useful Paul> and worth shipping in Python. They were both pretty much the only games in town when they were included with Python. If they were developed in today's environment I doubt they would be included. Paul> Basic competitive analysis. People ask here all the time "I'm Paul> trying to write application XYZ, should I use language L or should Paul> I use Python" (L is usually Java or PHP but can be other things). So every time some lame ass PHP refugee gripes about something they think Python is missing which PHP includes we should scan the horizon for all the candidates and toss them in the next release? Skip From deets at nospam.web.de Fri Feb 23 09:02:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Feb 2007 15:02:54 +0100 Subject: Local class variables? (mod_python problem) References: <545lchF1vd5s1U2@mid.uni-berlin.de> <20070222103151.GA12437@campbell-lange.net> <20070222154239.GA12709@campbell-lange.net> Message-ID: <548ageF1u22afU1@mid.uni-berlin.de> > It is not desirable for the class variable to keep incrementing outside > of invocations of '__main__', as is the case when it is loaded under > mod_python under apache2 on linux. > I'm still not clear on what you want to accomplish. In the end it boils down to who is supposed to share that information in the variables, or in other words: which scope has it. Is it per request? Then using some thread-local storage would be in order, or "abusing" a possible request-object. Is it per user, over several requests? Then you need a session-mechanism. Is it per application, for several users, over several requests? Then your approach is ok, but needs guarding against concurrrent access using threading.Lock for example. However, I presume that is not the desired usecase, from what I can extract from your posts I presume it's case two. Diez From redawgts at gmail.com Wed Feb 14 14:41:29 2007 From: redawgts at gmail.com (redawgts) Date: 14 Feb 2007 11:41:29 -0800 Subject: try...except...finally problem in Python 2.5 Message-ID: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> I keep getting this error "local variable 'f' referenced before assignment" in the finally block when I run the following code. try: f = file(self.filename, 'rb') f.seek(DATA_OFFSET) self.__data = f.read(DATA_SIZE) self.isDataLoaded = True except: self.isDataLoaded = False finally: f.close() Can someone tell me what's wrong with the code? Am I doing something wrong? I'm somewhat new to python but this makes sense to me. From johnjsal at NOSPAMgmail.com Mon Feb 5 15:04:44 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 05 Feb 2007 15:04:44 -0500 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> <52pc34F1oqe5fU1@mid.individual.net> Message-ID: <45c78ddf$0$10609$c3e8da3@news.astraweb.com> Alexander Schmolck wrote: > Would you use a calculator that would require Java-style > boilerplate to add two numbers? This isn't a Java newsgroup, so your metaphor is irrelevant. People use Python because it *isn't* Java and does not succumb to the problem you seem to be accusing it of. From yacinechaouche at gmail.com Tue Feb 6 03:52:04 2007 From: yacinechaouche at gmail.com (ychaouche) Date: 6 Feb 2007 00:52:04 -0800 Subject: HTMLParser's start_tag method never called ? In-Reply-To: <526j57F1mn0bdU1@mid.uni-berlin.de> References: <1170084691.837503.10520@j27g2000cwj.googlegroups.com> <526j57F1mn0bdU1@mid.uni-berlin.de> Message-ID: <1170751924.397456.191360@k78g2000cwa.googlegroups.com> On 29 jan, 16:45, "Diez B. Roggisch" wrote: > ychaouche wrote: > > Hi, python experts. > > > > > chaouche at CAY:~/TEST$ python nettoyageHTML.py > > chaouche at CAY:~/TEST$ > > > > > This is the nettoyageHTML.py python script > > > > > fromHTMLParserimportHTMLParser > > > class ParseurHTML(HTMLParser): > > def __init__(self): > > HTMLParser.__init__(self) > > > def start_body(self,attrs): > > print "this is my body" > > > p = ParseurHTML() > > p.feed(open("/home/chaouche/TEST/AJAX/testXMLRPC.html","r").read()) > > > > > this is the testXMLRPC.html html file : > > > > > > > > > > > > > > > > > NON > > > > > > > The script should output "this is my body", but nothing is printed. > > Anyone ? > > You need a p.close() after the feed I guess. > > Diez I tried p.close() and nothing happens. Y.Chaouche From sjmachin at lexicon.net Fri Feb 23 10:31:35 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Feb 2007 07:31:35 -0800 Subject: CSV(???) In-Reply-To: References: Message-ID: <1172244695.585282.111350@s48g2000cws.googlegroups.com> On Feb 23, 10:11 pm, David C. Ullrich wrote: > Is there a csvlib out there somewhere? I can make available the following which should be capable of running on 1.5.2 -- unless they've suffered bitrot :-) (a) a csv.py which does simple line-at-a-time hard-coded-delimiter-etc pack and unpack i.e. very similar to your functionality *except* that it doesn't handle newline embedded in a field. You may in any case be interested to see a different way of writing this sort of thing: my unpack does extensive error checking; it uses a finite state machine so unexpected input in any state is automatically an error. (b) an extension module (i.e. written in C) with the same API. The python version (a) imports and uses (b) if it exists. (c) an extension module which parameterises everything including the ability to handle embedded newlines. The two extension modules have never been compiled & tested on other than Windows but they both should IIRC be compilable with both gcc (MinGW) and the free Borland 5.5 compiler -- in other words vanilla C which should compile OK on Linux etc. If you are interested in any of the above, just e-mail me. > > And/or does anyone see any problems with > the code below? > > What csvline does is straightforward: fields > is a list of strings. csvline(fields) returns > the strings concatenated into one string > separated by commas. Except that if a field > contains a comma or a double quote then the > double quote is escaped to a pair of double > quotes and the field is enclosed in double > quotes. > > The part that seems somewhat hideous is > parsecsvline. The intention is that > parsecsvline(csvline(fields)) should be > the same as fields. Haven't attempted > to deal with parsecsvline(data) where > data is in an invalid format - in the > intended application data will always > be something that was returned by > csvline. "Always"? Famous last words :-) > It seems right after some > testing... also seems blechitudinous. I agree that it's bletchworthy, but only mildly so. If it'll make you feel better, I can send you as a yardstick csv pack and unpack written in awk -- that's definitely *not* a thing of beauty and a joy forever :-) I presume that you don't write csvline() output to a file, using newline as a record terminator and then try to read them back and pull them apart with parsecsvline() -- such a tactic would of course blow up on the first embedded newline. So as a matter of curiosity, where/ how are you storing multiple csvline() outputs? > > (Um: Believe it or not I'm _still_ using > python 1.5.7. So comments about iterators, > list comprehensions, string methods, etc > are irrelevent. Comments about errors in > the algorithm would be great. Thanks.) 1.5.7 ? [big snip] Cheers, John From google at mrabarnett.plus.com Wed Feb 7 14:47:51 2007 From: google at mrabarnett.plus.com (MRAB) Date: 7 Feb 2007 11:47:51 -0800 Subject: mplayer bug or python bug? In-Reply-To: References: Message-ID: <1170877671.829207.306470@j27g2000cwj.googlegroups.com> On Feb 7, 11:40 am, Marco wrote: > The following code is my test program for control mplayer. > in movies/ there are about 20 movies, the code plays them in circle, > but mplayer will crash silently after a circle, the "sliently" means I > can handle popen2 without except, but no movie. > > I have no idea about it... > Can you help me? > > class SimplePlayer( myobject ): > def __init__(self): > self.debug('simple player init ready') > self.is_open = False > self.wfd = None > self.rfd = None > > def play(self, file): > if self.is_open: > self.wfd.write('loadfile %s\n' %(file)) > self.wfd.flush() > else: > self.wfd, self.rfd = os.popen2('mplayer -loop 0 -slave > -quiet -ao null %s 2> /dev/null' %(file)) > self.is_open = True > > ################## > if __name__ == '__main__': > player = SimplePlayer() > all = os.listdir('movies/') > print all > while True: > for current in all: > print current > player.play('movies/' + current) > time.sleep(3) > Just a thought, but is mplayer writing anything to its standard output or error streams? It may be trying to report an error! While you're debugging, try redirecting them to logfiles. From zefirek at Speacock.Pau.Apoznan.Mpl Sat Feb 10 11:23:56 2007 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Sat, 10 Feb 2007 17:23:56 +0100 Subject: Hacking in python In-Reply-To: References: Message-ID: enes naci wrote: > > i would like to know about hacking in python too whether its illegal or > not is not the point and anyway it doesn't mean i'm gong to use it. > If you mean hacking as modyfying the code of interpreter of libraries - it is perfectly legal, as Python is Open Source. If you mean hacking as cracking into computer systems, then what's the difference if it's with Python or anything else. If you mean hacking as gaining excellency in programming - then why should it be? Greets zefciu From edreamleo at charter.net Fri Feb 16 10:00:46 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 09:00:46 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> <1171636975.653884.122850@p10g2000cwp.googlegroups.com> Message-ID: > So you only have one codebase to maintain and you can still use print... Not if the theorum is correct. > It may be true that you won't be able to write code that runs > untranslated on 2 and 3. That's my definition of a common code base. That is the content of the theorum. > That doesn't stop you writing code for Python > 2.X, then translating a version for Python 3. (Uhm... indeed that's the > point of 2to3.) That is not what I would call a common code base. The developer would have to run the translater every time the code changed. And if the Python 3.0 code were considered the 'master' code, the developer would need a 3to2 translater. Either disprove the theorum or give up the notion of having a common code base that uses print. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From roman.yakovenko at gmail.com Fri Feb 16 10:35:45 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Fri, 16 Feb 2007 17:35:45 +0200 Subject: Reg Google Web Toolkit and Python In-Reply-To: <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> References: <53lranF1th0pcU1@mid.uni-berlin.de> <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> Message-ID: <7465b6170702160735v5a224b48i283dfba7fa77fccb@mail.gmail.com> On 2/16/07, Shadab Sayani wrote: > Hi , > We have a project where I need to read files store > them in database in the backend.We have done this in > python.Now we decided to use Ajax technique for user > interface.For that we found that GWT is one of the > best toolkits.Now I got a doubt can I interface GWT > with python. http://pyjamas.pyworks.org/ is the way to go. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From gert.cuykens at gmail.com Thu Feb 8 16:49:26 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Thu, 8 Feb 2007 22:49:26 +0100 Subject: def obj() Message-ID: def obj(): return {'data':'hello', 'add':add(v)} def add(v): data=data+v if __name__ == '__main__': test=obj() test.add('world') print test.data I don't know why but i have one of does none class c programing style moods again. I was wondering if the following was possible without using a class ? From laurent.pointal at limsi.fr Mon Feb 5 04:19:26 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 05 Feb 2007 10:19:26 +0100 Subject: when will python 2.5 take in mainstream? In-Reply-To: <1170631417.253200.136330@h3g2000cwc.googlegroups.com> References: <4Rrxh.18423$pQ3.12414@newsread4.news.pas.earthlink.net> <1170631417.253200.136330@h3g2000cwc.googlegroups.com> Message-ID: tleeuwenburg at gmail.com a ?crit : > When they have to ... > > One of the big things about Python is that its penetration slows it > down. There's more legacy code and interdependant systems around now > that Python is more successful and more mature. > > Here's a thought -- perhaps it would be worth having some good ways to > interact with Python from Python. Suppose you have some 2.4 code > someplace, interacting with your mysqldb or whatever, and you don't > want to rewrite it. So long as you have some kind of object broker, > you could (plausibly) leave your 2.4 apps running with the old > interpreter, but wrap them for Python 2.5 and use that in your new > development. KISS please. > Ditto 3.0. > > Rather than having to re-write every interacting component, maybe it > could be straightforward to all Python2.4 from Python2.5 to execute > particular library calls. I'm not an expert, I don't know how you'd > build such a system, but I do know that re-writing stuff is a real > pain. Most of Python 2.4 source code is compatible with Python 2.5. Problems come with native compiled modules, you must have those for you 2.X Python version - some times just a compilation is enough. For Python 3.0, AFAIK its a big rewrite and developers know that it will be uncompatible in large parts with existing code. > Perhaps APIs for 2.5 and 3.0 could have a special version flag, and if > not present or not compatible, a 2.4 interpreter could be called > instead... Making Python interpreter bigger and more complex. Some code already has "hacks", trying to import a newer module and installing a fallback if its not available. If really your old Python 2.4 software cant run under Python 2.5, then you can have both Python 2.4 and 2.5 installed and running some code. Setup Pyro [1] on both, and go throught remote object invocation. And if you dont need new Python 2.5 stuff in your code evolution, just stay with 2.4, it works well. A+ Laurent. [1] http://pyro.sourceforge.net/ From greg at cosc.canterbury.ac.nz Fri Feb 23 19:51:46 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 24 Feb 2007 13:51:46 +1300 Subject: Regex Speed In-Reply-To: <1172272548.867795.289560@m58g2000cwm.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172079285.197453.131490@h3g2000cwc.googlegroups.com> <1172272548.867795.289560@m58g2000cwm.googlegroups.com> Message-ID: <549glaF1vhdlcU1@mid.individual.net> garrickp at gmail.com wrote: > the author of this citation states that > any regex can be expressed as a DFA machine. However ... > I appear to have found one example of a regex > which breaks this assumption. > > "ab+c|abd" > > Am I correct? No. Any NFA can be converted to an equivalent DFA. This is how scanner generators like Lex work -- they first construct an NFA from the regex, and then convert it to a DFA. Going directly from the regex to a DFA, like you're trying to do, would be a lot harder, and I'd be surprised if anyone ever does it that way. There's a description of the NFA-to-DFA algorithm here: http://www.gamedev.net/reference/articles/article2170.asp -- Greg From paddy3118 at netscape.net Sun Feb 4 06:17:44 2007 From: paddy3118 at netscape.net (Paddy) Date: 4 Feb 2007 03:17:44 -0800 Subject: Definitions of editor and IDE? In-Reply-To: References: <20070203224824.0CC7C1E400A@bag.python.org> Message-ID: <1170587864.512288.217940@h3g2000cwc.googlegroups.com> On Feb 4, 9:01 am, Necmettin Begiter wrote: > 04 ?ub 2007 Paz 00:48 tarihinde, Dick Moores ?unlar? yazm??t?:> Are there generally accepted definitions of "editor" and "IDE". Is there a > > clear-cut distinction between them? I've been looking at the lists of each > > at python.org, and < > >http://wiki.python.org/moin/IntegratedDevelopmentEnvironments>. Many > > programs are on both lists: Komodo, Eclipse, jedit, SPE, Wing IDE, UliPad, > > etc. > > > Dick Moores > > Can't give definitions, but here is the difference: if you use an editor, you > will have to run your script or program from outside the editor; if you use > an IDE, you will press a key or key combination in the IDE (say F9 or F5) and > your program/script will run... Hmm, is vim an editor or an IDE? By the above definition it would be an IDE because under the tools menu you can run make or compilers/interpreters. It has probably got to the stage that its a continuum from something like Eclipse or SPE that are definitely IDE's through to ed and notepad which are editors. - Pad. From jstroud at mbi.ucla.edu Thu Feb 1 18:18:35 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 01 Feb 2007 15:18:35 -0800 Subject: Python, readline and OS X In-Reply-To: References: Message-ID: Ron Garret wrote: > I have installed Python 2.5 on my new Intel Mac but I can't for the life > of me get readline to work. I have libreadline installed, I've tried > copying readline.so from my Python 2.3 installation into 2.5, I've > searched the web, and no joy. Could someone please give me a clue? > > rg Where have you installed libreadline? Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib? Did you install libreadline with fink? If so, try setenv LD_LIBRARY_PATH /sw/lib before compiling (csh). Bash (OSX default) and similar shells use this silly 2 part syntax: LD_LIBRARY_PATH=/sw/lib export LD_LIBRARY_PATH Do a "locate libreadline.dylib" and set the LD_LIBRARY_PATH to the containing directory and then make clean ./configure make make install or similar. From skip at pobox.com Sat Feb 3 09:08:57 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 3 Feb 2007 08:08:57 -0600 Subject: strange test for None In-Reply-To: <1170510459.804204.311760@v33g2000cwv.googlegroups.com> References: <1170510459.804204.311760@v33g2000cwv.googlegroups.com> Message-ID: <17860.38777.57951.725474@montanaro.dyndns.org> >>>>> "karoly" == karoly kiripolszky writes: karoly> in my server i use the following piece of code: karoly> ims = self.headers["if-modified-since"] karoly> if ims != None: karoly> t = int(ims) karoly> and i'm always getting the following error: karoly> t = int(ims) karoly> ValueError: invalid literal for int(): None Try printing repr(ims), type(ims) and id(ims) then compare that with repr(None), type(None) and id(None). My guess is you have a string whose value is "None": % python2.4 Python 2.4.1 (#3, Jul 28 2005, 22:08:40) [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> int("None") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): None The output in 2.5 makes it more clear what you've got: % python2.5 Python 2.5c1 (release25-maint:51339, Aug 17 2006, 22:15:14) [GCC 4.0.0 (Apple Computer, Inc. build 5026)] on darwin Type "help", "copyright", "credits" or "license" for more information. in>>> int("None") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'None' Skip From jorge.vargas at gmail.com Wed Feb 21 17:38:03 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 21 Feb 2007 18:38:03 -0400 Subject: BDFL in wikipedia In-Reply-To: <8e9ua4-voh.ln1@ophelia.g5n.co.uk> References: <8e9ua4-voh.ln1@ophelia.g5n.co.uk> Message-ID: <32822fe60702211438k3a3c3b0bh249cdd0327d0f304@mail.gmail.com> On 2/21/07, Toby A Inkster wrote: > Jorge Vargas wrote: > > > shouldn't it mention Linus, Larry Wall, others?[3] > > Despite the link you posted, I don't think Linus, Larry Wall, Rasmus > Lerdorf, etc describe themselves as BDFLs, even if they fulfil similar > roles within their respective development communities. > yea I just got that as an example, from around the web, I really haven't follow the internals of any of those communities to be able to know if they do or don't. > -- > Toby A Inkster BSc (Hons) ARCS > Contact Me ~ http://tobyinkster.co.uk/contact > Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux > Now Playing ~ ./vol/music/snug/from_solar_to_polar/04_naked_+_smiling.ogg > > * = I'm getting there! > -- > http://mail.python.org/mailman/listinfo/python-list > From bblais at bryant.edu Tue Feb 20 08:30:24 2007 From: bblais at bryant.edu (Brian Blais) Date: Tue, 20 Feb 2007 08:30:24 -0500 Subject: CherryPy/Turbogears on server not controlled by me Message-ID: <45DAF7F0.1080503@bryant.edu> Hello, I was wondering if there is a way to run CherryPy/Turbogears on a server that I don't have root access to. If I just choose a random port, I think the security guys on the server would get annoyed at me. What are my options? I can talk to the admin, but they are very slow/reluctant to make changes...it took me a couple months to get them to upgrade to 2.4 from 2.3 last year, even when 2.5 was out. thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From rds1226 at sh163.net Sat Feb 3 14:15:28 2007 From: rds1226 at sh163.net (Ruan) Date: Sat, 3 Feb 2007 14:15:28 -0500 Subject: confused about resizing array in Python Message-ID: My confusion comes from the following piece of code: memo = {1:1, 2:1} def fib_memo(n): global memo if not n in memo: memo[n] = fib_memo(n-1) + fib_memo(n-2) return memo[n] I used to think that the time complexity for this code is O(n) due to its use of memoization. However, I was told recently that in Python, dictionary is a special kind of array and to append new element to it or to resize it, it is in fact internally inplemented by creating another array and copying the old one to it and append a new one. Therefore, for "memo[n] = fib_memo(n-1) + fib_memo(n-2)", the time it taks is not at all constant. The larger the n grows, the more time this statement takes. Can anybody here familiar with the internal mechanism of python confirm this? From petercable at gmail.com Mon Feb 12 04:23:04 2007 From: petercable at gmail.com (petercable at gmail.com) Date: 12 Feb 2007 01:23:04 -0800 Subject: randomly generate n of each of two types In-Reply-To: <3YOzh.1133$yg7.205@trnddc08> References: <3YOzh.1133$yg7.205@trnddc08> Message-ID: <1171272184.544941.277510@s48g2000cws.googlegroups.com> > > This again has the "costs" I referred to: > creating a potentially large sequence, > and shuffling it. I thought I would see if I could do better, so I wrote this: import random def index_types(n, typelist=[True, False]): numtypes = len(typelist) total = float(n*numtypes) counts = [0] * numtypes while total > 0: index = int(random.random() * numtypes) if counts[index] < n: counts[index] += 1 total -= 1 yield typelist[index] def shuffle_types(n,typelist=[True,False]): types = typelist*n random.shuffle(types) for next_type in types: yield next_type def random_types(n,typelist=[True,False]): type0, type1 = typelist ct0, ct1 = 0,0 while ct0+ct1<2*n: if random.random() < ((n-ct0)/(2*n-ct0-ct1)): next_type = type0 ct0 += 1 else: next_type = type1 ct1 += 1 yield next_type def test_index(n): for x in index_types(n): pass def test_shuffle(n): for x in shuffle_types(n): pass def test_random(n): for x in shuffle_types(n): pass if __name__ == '__main__': from time import sleep sleep(10) from timeit import Timer for function in ['test_index', 'test_shuffle', 'test_random']: for nvalue in [1000,10000,100000,1000000]: t = Timer("%s(%d)" % (function, nvalue), "from __main__ import %s" % function) print function, 'n =', nvalue, ':', t.timeit(number=100) Which yielded the following results: pete at pete-desktop:~$ python test.py test_index n = 1000 : 0.599834918976 test_index n = 10000 : 5.78634595871 test_index n = 100000 : 56.1441719532 test_index n = 1000000 : 562.577429056 test_shuffle n = 1000 : 0.420483827591 test_shuffle n = 10000 : 4.62663197517 test_shuffle n = 100000 : 46.3557109833 test_shuffle n = 1000000 : 498.563408852 test_random n = 1000 : 0.440869092941 test_random n = 10000 : 4.77765703201 test_random n = 100000 : 47.6845810413 test_random n = 1000000 : 485.233494043 Which shows my function is the slowest (doh!) and your second function is the fastest. However, shuffle isn't taking much longer to create and randomize a fairly large list (4.99 secs vs 4.85 secs for your second function.) In my defense, I wanted to see if I could write the function to take an arbitrarily long list, rather than limiting it to 2 items. I also noticed your second function is not working as intended: >>> r = [x for x in test.random_types(10)] >>> r [False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True] I think it needs a cast to a float: if random.random() < (float(n-ct0)/(2*n-ct0-ct1)): I was too impatient to wait for the n=1000000 results, so here it is without them: pete at pete-desktop:~$ python test.py test_index n = 1000 : 0.583498001099 test_index n = 10000 : 5.80185317993 test_index n = 100000 : 58.8963599205 test_shuffle n = 1000 : 0.431984901428 test_shuffle n = 10000 : 4.75261592865 test_shuffle n = 100000 : 48.1326880455 test_random n = 1000 : 0.697184085846 test_random n = 10000 : 4.41986989975 test_random n = 100000 : 45.7090520859 Once again, the difference is negligible. My question is, does this function reduce the "randomness" of the data? Doesn't it move the data towards an alternating pattern of True, False? It seems to me that calling shuffle, or perhaps chained PRNG as suggested by Steven > If you really care about shuffling large lists, you can chain PRNGs. For > instance, you might use shuffle() to generate a random batch of items, > then use a completely different PRNG to shuffle the list again. would produce the most "random" data... Pete From jeba_ride at yahoo.com Sun Feb 25 12:53:34 2007 From: jeba_ride at yahoo.com (Clement) Date: 25 Feb 2007 09:53:34 -0800 Subject: Help on Dict Message-ID: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> Can any body tell how Dict is implemented in python... plz tell what datastructure that uses................ From savvas83 at gmail.com Mon Feb 26 15:06:24 2007 From: savvas83 at gmail.com (iceman) Date: 26 Feb 2007 12:06:24 -0800 Subject: Add images together Message-ID: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> Hi, I am trying to add together a number of images: im = image1 + image2 + ... How can i do this? I have tried to add two image instances together but i get the following error: TypeError: unsupported operand type(s) for +: 'instance' and 'instance' From no at spam.com Tue Feb 27 19:17:06 2007 From: no at spam.com (Farshid Lashkari) Date: Tue, 27 Feb 2007 16:17:06 -0800 Subject: how to convert an integer to a float? In-Reply-To: References: <1172621139.954362.196170@k78g2000cwa.googlegroups.com> Message-ID: Farshid Lashkari wrote: > When two integers are involved in a division, the result will also be a > division. My bad, I meant the result will also be an *integer* -Farshid From larry.bates at websafe.com Thu Feb 1 16:39:26 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Feb 2007 15:39:26 -0600 Subject: Recursive zipping of Directories in Windows In-Reply-To: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> References: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> Message-ID: Jandre wrote: > Hi > > I am a python novice and I am trying to write a python script (most of > the code is borrowed) to Zip a directory containing some other > directories and files. The script zips all the files fine but when it > tries to zip one of the directories it fails with the following > error: > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > The script I am using is: > > import zipfile, os > > def toZip( directory, zipFile ): > """Sample for storing directory to a ZipFile""" > z = zipfile.ZipFile( > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > ) > def walker( zip, directory, files, root=directory ): > for file in files: > file = os.path.join( directory, file ) > # yes, the +1 is hacky... > archiveName = file[len(os.path.commonprefix( (root, > file) ))+1:] > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > print file > os.path.walk( directory, walker, z ) > z.close() > return zipFile > > > if __name__ == "__main__": > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > I have tried to set the permissions on the folder, but when I check > the directory permissions it is set back to "Read Only" > > Any suggestions? > > Thanks > Johan Balt > Couple of quick suggestions that may help: 1) don't use 'file' as a variable name. It will mask the builtin file function. If it hasn't bitten you before it will if you keep doing that. 2) If you put the target .zip file in the directory you are backing what do you expect the program to do when it comes to the file you are creating as you walk the directory? You haven't done anything to 'skip' it. 3) Your commonprefix and +1 appears to result in same information that the easier to use os.path.basename() would give you. Double check me on that. I don't see anything that references C:\\aaa\temp in your code. Does it exist on your hard drive? If so does it maybe contain temp files that are open? zipfile module can't handle open files. You must use try/except to catch these errors. Hope info helps. -Larry From gagsl-py at yahoo.com.ar Sun Feb 11 15:29:50 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Feb 2007 17:29:50 -0300 Subject: Problem with reimporting modules References: <1171209111.551190.146590@a34g2000cwb.googlegroups.com> Message-ID: En Sun, 11 Feb 2007 15:56:16 -0300, Christoph Zwerschke escribi?: > Yes I know about reload(), but TurboGears (TurboKid) does not use it and > the docs say that removing modules from sys.module is possible to force > reloading of modules. I don't want to rewrite everything since it's a > pretty complex thing with modules which are compiled from templates > which can depend from other templates etc... If you remove the module from sys.modules, when you import it again you end up with a *new*, fresh, module object, unrelated to the original one. Quoting your original message again: > I tracked it down to the following behavior of Python. Assume you have a > module hello.py like that: > ---- hello. py ---- > greeting = 'Hello!' > def print_hello(): > print greeting > ------------------- > Now run the following code: > from hello import print_hello > print_hello() > import sys > del sys.modules['hello'] # delete module > import hello # recreate module > print_hello() > The second print_hello() prints "None" instead of "Hello!". Why is that? Notice that you are mixing references here. You first import print_hello from hello, and after deleting the module, you import hello (not print_hello). And you expect that your old reference to print_hello now refers to the new function. The whole point of reloading/reimporting a module is to get the *new* contents, but that only works if you refer to things using the module.function notation, not if you hold a reference to the function (which will always be the original function). In short, your code should be: import hello hello.print_hello() import sys del sys.modules['hello'] import hello hello.print_hello() or, using reload: import hello hello.print_hello() reload(hello) hello.print_hello() If you think that always typing module.function is too much - well, don't try to reload modules then :) Somewhere I read that at Google the policy is to always import modules, never functions, and this may be a good reason for it. If you want to know the details: print_hello doesn't hold a reference to the containing module, only to its namespace, in the func_globals attribute. When you delete the last reference to the module, it gets destroyed. At that time, all values in the module namespace are set to None (for breaking possible cycles, I presume). print_hello now has a func_globals with all names set to None. (Perhaps the names could have been deleted instead, so print_hello() would raise a NameError, but I'm just describing the current CPython implementation) -- Gabriel Genellina From DustanGroups at gmail.com Thu Feb 1 04:44:41 2007 From: DustanGroups at gmail.com (Dustan) Date: 1 Feb 2007 01:44:41 -0800 Subject: Can I import a file without file extension .py? In-Reply-To: <1170312698.028776.111320@l53g2000cwa.googlegroups.com> References: <1170305999.001998.251390@m58g2000cwm.googlegroups.com> <1170312698.028776.111320@l53g2000cwa.googlegroups.com> Message-ID: <1170323081.350021.63120@k78g2000cwa.googlegroups.com> On Feb 1, 12:51 am, "Jia Lu" wrote: > > def make_module_from_file(module_name, file_name): > > """ Make a new module object from the code in specified file """ > > > from types import ModuleType > > module = ModuleType(module_name) > > > module_file = open(file_name, 'r') > > exec module_file in module.__dict__ > > Thank you very much. > And can you tell me what does " exec module_file in module.__dict__ " > mean? > > Thanx http://docs.python.org/ref/exec.html It executes whatever code is in module_file and dumps all variables defined in the process into module.__dict__. From chris at kateandchris.net Thu Feb 8 10:50:17 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Thu, 8 Feb 2007 10:50:17 -0500 Subject: Getting a class name from within main In-Reply-To: <1170838959.441543.19720@s48g2000cws.googlegroups.com> References: <1170838959.441543.19720@s48g2000cws.googlegroups.com> Message-ID: <20070208155017.GA10444@kateandchris.net> On Wed, Feb 07, 2007 at 01:02:39AM -0800, bg_ie at yahoo.com wrote: > Hi, > > Lets say I have the following class - > > class MyClass: > def __init__(self): > print (__name__.split("."))[-1] I would spell this: print self.__class__.__name__ > > if __name__ == '__main__': > MyClassName = "MyClass" > > I can print the name of the class from within the class scope as seen > above in the init, but is there any way of printing it from within the > main without creating an object of the MyClass type. I need to assign > the name of the class within my script, to a variable in main. > > Thanks, > > Barry. > > -- > http://mail.python.org/mailman/listinfo/python-list From michele.simionato at gmail.com Thu Feb 1 01:02:36 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 31 Jan 2007 22:02:36 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: References: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> <1170271023.955808.314010@q2g2000cwa.googlegroups.com> Message-ID: <1170309756.501758.303800@a34g2000cwb.googlegroups.com> On Jan 31, 8:31 pm, "Carl J. Van Arsdall" wrote: > > Well, since it will be io based, why not use threads? They are easy to > use and it would do the job just fine. Then leverage some other > technology on top of that. > > You could go as far as using wget via os.system() in a thread, if the > app is simple enough. Calling os.system in a thread look really perverse to me, you would loose CTRL-C without any benefit. Why not to use subprocess.Popen instead? I am unhappy with the current situation in Python. Whereas for most things Python is such that the simplest things look simple, this is not the case for threads. Unfortunately we have a threading module in the standard library, but not a "Twisted for pedestrian" module, so people overlook the simplest solution in favor of the complex one. Another thing I miss is a facility to run an iterator in the Tkinter mainloop: since Tkinter is not thread-safe, writing a multiple-download progress bar in Tkinter using threads is definitely less obvious than running an iterator in the main loop, as I discovered the hard way. Writing a facility to run iterators in Twisted is a three-liner, but it is not already there, nor standard :-( Michele Simionato From franz.steinhaeusler at gmx.at Wed Feb 7 05:11:33 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 07 Feb 2007 11:11:33 +0100 Subject: Python compiled on Windows References: Message-ID: <7b9js256ol2et1so9lrrckrm7lgjorh97l@4ax.com> On 7 Feb 2007 09:44:32 GMT, Duncan Booth wrote: >Franz Steinhaeusler wrote: > >>>Yes, people have compiled Python with gcc on windows. I believe it is >>>slightly slower than the standard release, but I would guess that may >>>depend on the exact versions of gcc/msc you choose to compare, and the >>>exact compiler options you choose (or I may even be imagining it >>>entirely). >> >> I cannot imagine, that there is a decisive difference, especially as >> in gcc, you have also a couple of options. >> >I did a quick comparison running pystone and taking the best of several >runs: > >On one system which had the Windows Python 2.4 distribution and also >Python 2.4 installed under cygwin: > > Windows Python 2.4: 46k > Cygwin Python 2.4: 41k > >On another system which has a dual boot setup: > > Windows Python 2.5: 43.7k > Ubuntu Python 2.5: 42.0k > >So in the first case there was about a 12% improvement and in the second >case about 5% improvement using the Windows distribution. > >I don't know whether the gap is closing from improvements in gcc or >whether there is an OS related difference as well. Unfortunately cygwin >doesn't appear to offer Python 2.5 yet. Hello Duncan, interesting test, so this little gap don't care at all (for me). If the difference would be say 30% or more, than that would make a perceptible difference, I think. From exhuma at gmail.com Thu Feb 15 05:06:17 2007 From: exhuma at gmail.com (exhuma.twn) Date: 15 Feb 2007 02:06:17 -0800 Subject: ZSI + mod_python Message-ID: <1171533977.607906.181580@p10g2000cwp.googlegroups.com> Hi, I tried for the last 2 hours now to somehow grasp how to use ZSI over mod_python. It's nice that they have a code-example in the ZSI docs, but it's incomplete and you are left guessing. The ZSI docs I used as reference can be found on http:// pywebsvcs.sourceforge.net/zsi.html#SECTION003130000000000000000 Here is where I am at so far: First I created the two files as described in the ZSI docs. Namely "MyHandler.py" and "ws.py". The first name is obvious to someone who has coded at least a little bit of python, but it could be explicitly stated in the docs, so the beginners don't get stumped by a silly filename to start with ;) The second filename is my own concoction. I suppose it does not matter how it's named as you specify it in the apache conf anyhow. So. Now to the apache conf. I put the scripts into the document-root of my server. In this case: "/var/www/localhost". So this is what I get (ommitting the unnecessary cruft -- marked it with "[...]"): ---- /etc/apache2/sites-enables/000-default.conf ----------------------------------- [...] DocumentRoot /var/www/localhost AddHandler mod_python .py [...] [...] PythonHandler ws PythonDebug On [...] -------------------------------------------------------------------------------------------------------- This is as far as I got. Now how do I call a service from this setting? What's the URI I need to specify in the client? I was trying "http://server/foo.py" in the browser, and it was obviously doing *something* with the "ws.py" file. But I have no clue what. Here's the output: ---- Browser output for http://server/foo.py --------------------------------------------- Mod_python error: "PythonHandler ws" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/var/www/localhost/ws.py", line 9, in handler dispatch.AsHandler(modules=(MyHandler,), request=req) File "/usr/lib/python2.4/site-packages/ZSI-2.0_rc3-py2.4.egg/ZSI/ dispatch.py", line 263, in AsHandler File "/usr/lib/python2.4/site-packages/ZSI-2.0_rc3-py2.4.egg/ZSI/ parse.py", line 61, in __init__ File "/usr/lib/python2.4/site-packages/PyXML-0.8.4-py2.4-linux- i686.egg/_xmlplus/dom/ext/reader/PyExpat.py", line 65, in fromStream success = self.parser.ParseFile(stream) ExpatError: no element found: line 1, column 0 -------------------------------------------------------------------------------------------------------- No matter what I append to the URI, it does not make a difference in the output. And *why* am I forced to add a "abracadabra.py" to the URI? Could I not set Apache up in a way that it would use the ZSI handler for everything that calls -- let's say -- http:// webservices.server.tld/ instead of http://webservices.server.tld/ booh.py ? I'm off to a little bit more of testing. But any hints/input would be kindly appreciated ;) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 28 18:20:32 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 00:20:32 +0100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> Message-ID: <54mh20F21ho3eU1@mid.individual.net> Luis M. Gonz?lez wrote: > I've come across a code snippet in www.rubyclr.com where they show > how easy it is to declare a class compared to equivalent code in > c#. I wonder if there is any way to emulate this in Python. > > The code is as follows: > > Person = struct.new( :name, :birthday, :children) What's easy about this? Also, this is a definition and not just a declaration. > But this above is not what I want. > I guess I should find a way to include the constructor code inside > this function, but I don't know if this is possible. Could you please describe what exactly you want in an abstract way? > Also, I wonder if there is a way to use the variable name in order > to create a class with the same name (as in "Person"above). Two classes with the same name? In Python, classes have no name. They are anonymous objects which can be bound to names. Regards, Bj?rn -- BOFH excuse #367: Webmasters kidnapped by evil cult. From horpner at yahoo.com Tue Feb 13 09:10:50 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 13 Feb 2007 15:10:50 +0100 Subject: float print formatting References: Message-ID: On 2007-02-13, hg wrote: > Hi, > > Considering the float 0.0, I would like to print 00.00. > > I tried '%02.02f' % 0.0 ... but I get 0.00 > > Any clue ? Yes. How wide (total) is "0.00", compared to "00.00"? -- Neil Cerutti From rune.strand at gmail.com Wed Feb 14 07:56:05 2007 From: rune.strand at gmail.com (Rune Strand) Date: 14 Feb 2007 04:56:05 -0800 Subject: replacing substrings within strings In-Reply-To: <1171456035.101434.232440@q2g2000cwa.googlegroups.com> References: <1171454918.840972.189990@k78g2000cwa.googlegroups.com> <1171456035.101434.232440@q2g2000cwa.googlegroups.com> Message-ID: <1171457764.799237.177830@v45g2000cwv.googlegroups.com> Or, slighly slower, but more general: def swap(s, order=(3,4,2,0,1)): # assert len(s) >= len(order) return ''.join([s[o] for o in order]) + s[6:] From ishpeck at gmail.com Tue Feb 27 17:55:40 2007 From: ishpeck at gmail.com (Ishpeck) Date: 27 Feb 2007 14:55:40 -0800 Subject: Running Python scripts from BASH Message-ID: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> I'm using Python to automate testing software for my company. I wanted the computers in my testing lab to automatically fetch the latest version of the python scripts from a CVS repository and then ask a local database server which of the scripts to run. I built the following: #!/bin/bash # Batcher will run the specified scripts. cvs update while true do # This part makes sure that # every hour or so, we get the latest # snapshot of the suite from CVS. if [ $(date +%M) = 0 ]; then cvs update sleep 360 fi # Then we grab the name of # a randomly-selected script i=$(python randomRun.py) # If the return-value of randomRun.py #is empty, we don't run it. if ["$i"=""]; then echo Not running anything sleep 3600 # If randomRun doesn't return # empty, we run the script that it prints. else python "$i"; sleep 2 fi done --------- END BASH FILE -------- For debugging purposes, you can just build "randomRun.py" to do the following: print "randomRun.py" It's silly but works. Whenever I run this script, Python decides that it doesn't like the way BASH feeds it the name of the script. I get the following message: ': [Errno 22] Invalid argumentopen file 'foo.py I dunno. Maybe this is a better question for a BASH-related group. How do I get around this? From bearophileHUGS at lycos.com Fri Feb 9 08:52:55 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Feb 2007 05:52:55 -0800 Subject: unique elements from list of lists In-Reply-To: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> References: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> Message-ID: <1171029175.000076.276030@l53g2000cwa.googlegroups.com> Tekkaman: If the sublists contain hashable elements you can use this: def uniter(lists): merge = set() for sub in lists: merge = merge.union(sub) for el in merge: yield el data = [['a', 'b', 'd'], ['b', 'c'], ['a', 'c', 'd']] print list(uniter(data)) But often this too may be enough: def uniter(lists): merge = set() for sub in lists: merge = merge.union(sub) return merge Bye to the gentle Pegas too, bearophile From garrickp at gmail.com Fri Feb 23 18:15:48 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 23 Feb 2007 15:15:48 -0800 Subject: Regex Speed In-Reply-To: <1172079285.197453.131490@h3g2000cwc.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172079285.197453.131490@h3g2000cwc.googlegroups.com> Message-ID: <1172272548.867795.289560@m58g2000cwm.googlegroups.com> On Feb 21, 10:34 am, garri... at gmail.com wrote: > On Feb 20, 6:14 pm, Pop User wrote: > >http://swtch.com/~rsc/regexp/regexp1.html Going back a bit on a tangent, the author of this citation states that any regex can be expressed as a DFA machine. However, while investigating this more I appear to have found one example of a regex which breaks this assumption. "ab+c|abd" Am I correct? Can you think of a deterministic method of computing this expression? It would be easier with a NFA machine, but given that the Python method of computing RE's involves pre-compiling a re object, optimizing the matching engine would make the most sense to me. Here's what I have so far: class State(object): def __init__(self): self.nextState = {} self.nextStateKeys = [] self.prevState = None self.isMatchState = True def setNextState(self, chars, iNextState): self.nextState[chars] = iNextState self.nextStateKeys = self.nextState.keys() self.isMatchState = False def setPrevState(self, iPrevState): self.prevState = iPrevState def moveToNextState(self, testChar): if testChar in self.nextStateKeys: return self.nextState[testChar] else: return None class CompiledRegex(object): def __init__(self, startState): self.startState = startState def match(self, matchStr): match_set = [] currentStates = [self.startState] nextStates = [self.startState] for character in matchStr: for state in currentStates: nextState = state.moveToNextState(character) if nextState is not None: nextStates.append(nextState) if nextState.isMatchState: print "Match!" return currentStates = nextStates nextStates = [self.startState] print "No Match!" def compile(regexStr): startState = State() currentState = startState backRefState = None lastChar = "" for character in regexStr: if character == "+": currentState.setNextState(lastChar, currentState) elif character == "|": currentState = startState elif character == "?": backRefState = currentState.prevState elif character == "(": # Implement "(" pass elif character == ")": # Implement ")" pass elif character == "*": currentState = currentState.prevState currentState.setNextState(lastChar, currentState) else: testRepeatState = currentState.moveToNextState(character) if testRepeatState is None: newState = State() newState.setPrevState(currentState) currentState.setNextState(character, newState) if backRefState is not None: backRefState.setNextState(character, newState) backRefState = None currentState = newState else: currentState = testRepeatState lastChar = character return CompiledRegex(startState) >>> a = compile("ab+c") >>> a.match("abc") Match! >>> a.match("abbc") Match! >>> a.match("ac") No Match! >>> a = compile("ab+c|abd") >>> a.match("abc") Match! >>> a.match("abbc") Match! >>> a.match("ac") No Match! >>> a.match("abd") Match! >>> a.match("abbd") Match! >>> From ptmcg at austin.rr.com Thu Feb 8 17:45:37 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 8 Feb 2007 14:45:37 -0800 Subject: Parsing HTML In-Reply-To: <1170972940.852050.53830@h3g2000cwc.googlegroups.com> References: <1170963493.960986.247170@v45g2000cwv.googlegroups.com> <1170963788.882845.124810@k78g2000cwa.googlegroups.com> <1170972940.852050.53830@h3g2000cwc.googlegroups.com> Message-ID: <1170974736.944022.118620@h3g2000cwc.googlegroups.com> On Feb 8, 4:15 pm, "mtuller" wrote: > I was asking how to escape the quotation marks. I have everything > working in pyparser except for that. I don't want to drop everything > and go to a different parser. > > Can someone else help? > > Mike - pyparsing includes a helper for constructing HTML tags called makeHTMLTags. This method does more than just wrap the given tag text within <>'s, but also comprehends attributes, upper/lower case, and various styles of quoted strings. To use it, replace your Literal definitions for spanStart and spanEnd with: spanStart, spanEnd = makeHTMLTags('span') If you don't want to match just *any* tag, but say, you only want those with the class = "hpPageText", then add this parse action to spanStart: def onlyAcceptWithTagAttr(attrname,attrval): def action(tagAttrs): if not(attrname in tagAttrs and tagAttrs[attrname]==attrval): raise ParseException("",0,"") return action spanStart.setParseAction(onlyAcceptWithTagAttr("class","hpPageText")) -- Paul From kbk at shore.net Sun Feb 4 22:32:32 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 4 Feb 2007 22:32:32 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200702050332.l153WW59011394@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 423 open ( +2) / 3553 closed ( +4) / 3976 total ( +6) Bugs : 963 open (+20) / 6479 closed ( +8) / 7442 total (+28) RFE : 260 open ( +0) / 250 closed ( +0) / 510 total ( +0) New / Reopened Patches ______________________ ConfigParser getboolean() consistency (2007-01-28) http://python.org/sf/1646432 opened by Tal Einat gzip.GzipFile has no name attribute (2007-01-29) http://python.org/sf/1647484 opened by Lars Gust?bel proxy_bypass in urllib handling of macro (2007-01-30) http://python.org/sf/1648102 opened by Anthony Tuininga pty.fork() python implementation leaks the slave fd (2007-01-31) CLOSED http://python.org/sf/1648435 opened by John Levon Adding support for _Bool to ctypes as c_bool (2007-01-31) http://python.org/sf/1649190 opened by David Remahl configHandler support for raw data (2007-02-01) http://python.org/sf/1650174 opened by Tal Einat Patches Closed ______________ file -> open in stdlib (2007-01-25) http://python.org/sf/1644218 closed by gbrandl compiler.pycodegen causes crashes when compiling 'with' (2007-01-18) http://python.org/sf/1638243 closed by gbrandl Add aliases for latin7/9/10 charsets (2007-01-13) http://python.org/sf/1634778 closed by gbrandl pty.fork() python implementation leaks the slave fd (2007-01-31) http://python.org/sf/1648435 closed by gbrandl New / Reopened Bugs ___________________ os.access now returns bool but docstring is not updated (2007-01-27) CLOSED http://python.org/sf/1645944 opened by Seo Sanghyeon Dict lookups fail if sizeof(Py_ssize_t) < sizeof(long) (2007-01-27) http://python.org/sf/1646068 opened by ked-tao ctypes.string_at(buf, 0) is seen as zero-terminated-string (2007-01-28) http://python.org/sf/1646630 opened by Johannes H?lzl datetime.fromtimestamp fails with negative fractional times (2007-01-29) http://python.org/sf/1646728 opened by James Henstridge os.path, %HOME% set: realpath contradicts expanduser on '~' (2007-01-29) http://python.org/sf/1646838 opened by wrstl prmpft cookielib.CookieJar does not handle cookies when port in url (2007-01-29) CLOSED http://python.org/sf/1647037 opened by STS zero-length match confuses re.finditer() (2007-01-29) http://python.org/sf/1647489 opened by Jacques Frechet SystemError with re.match(array) (2007-01-30) http://python.org/sf/1647541 opened by Armin Rigo No obvious and correct way to get the time zone offset (2007-01-30) http://python.org/sf/1647654 opened by James Henstridge set update problem with class derived from dict (2007-01-30) CLOSED http://python.org/sf/1648179 opened by duncan Grammatical error (2007-01-30) CLOSED http://python.org/sf/1648191 opened by Chris Beelby Parameter list mismatches (portation problem) (2007-01-30) http://python.org/sf/1648268 opened by ked-tao HP-UX: ld -Wl,+b... (2007-01-31) http://python.org/sf/1648890 opened by Johannes Abt HP-UX: -lcurses missing for readline.so (2007-01-31) http://python.org/sf/1648923 opened by Johannes Abt HP-UX: _ctypes/libffi/src/ia64/ffi/__attribute__/native cc (2007-01-31) http://python.org/sf/1648957 opened by Johannes Abt HP-UX11.23: module zlib missing (2007-01-31) http://python.org/sf/1648960 opened by Johannes Abt HP-UX: compiler warnings: alignment (2007-01-31) http://python.org/sf/1649011 opened by Johannes Abt non-standard: array[0] (2007-01-31) http://python.org/sf/1649098 opened by Johannes Abt Arithmetics behaving strange (2007-01-31) CLOSED http://python.org/sf/1649100 opened by Sascha Peilicke potential class with C++ in ceval.h (2007-01-31) http://python.org/sf/1649238 opened by thechao gettext.py incompatible with eggs (2007-01-31) http://python.org/sf/1649329 opened by Shannon -jj Behrens decimals compare badly to floats (2007-02-01) http://python.org/sf/1650053 opened by Brian Sutherland doctest doesn't find nested functions (2007-02-01) http://python.org/sf/1650090 opened by Daniel Brown sys.excepthook does not work with -m command line switch (2007-02-02) CLOSED http://python.org/sf/1650899 opened by Miki Tebeka PyFloat_FromString deprecated form (2007-02-02) http://python.org/sf/1650903 opened by Jim Jewett ctypes.Structure formal parameter dies given tuple (2007-02-03) http://python.org/sf/1651235 opened by Gary Bishop readline needs termcap on my FC6 (2007-02-03) http://python.org/sf/1651427 opened by guichaz sgmllib _convert_ref UnicodeDecodeError exception, new in 2. (2007-02-04) http://python.org/sf/1651995 opened by John Nagle Bugs Closed ___________ os.access now returns bool but docstring is not updated (2007-01-27) http://python.org/sf/1645944 closed by gbrandl cookielib.CookieJar does not handle cookies when port in url (2007-01-29) http://python.org/sf/1647037 closed by tools-sts set update problem with class derived from dict (2007-01-30) http://python.org/sf/1648179 closed by rhettinger Grammatical error (2007-01-30) http://python.org/sf/1648191 closed by gbrandl GUI scripts always return to an interpreter (2006-09-29) http://python.org/sf/1568075 closed by jejackson Arithmetics behaving strange and magic underscore (2007-01-31) http://python.org/sf/1649100 closed by gbrandl pty.fork() leaves slave fd's open on Solaris (2004-04-12) http://python.org/sf/933670 closed by gbrandl Idle 1.2 - Calltips Hotkey does not work (2006-09-27) http://python.org/sf/1566611 closed by sf-robot sys.excepthook does not work with -m command line switch (2007-02-02) http://python.org/sf/1650899 closed by tebeka From matt.waite at gmail.com Thu Feb 1 17:31:00 2007 From: matt.waite at gmail.com (Matt Waite) Date: 1 Feb 2007 14:31:00 -0800 Subject: Newbie question: replacing nulls in CSV with preceding value In-Reply-To: References: <1170360800.751074.251980@q2g2000cwa.googlegroups.com> Message-ID: <1170369059.410305.213880@h3g2000cwc.googlegroups.com> Thanks everyone for your help. I got Skip's answer to work (mine is pasted below): import sys import csv last = {} reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb")) writer = csv.DictWriter(open("/home/mwaite/test/test3.csv", "wb"), ['ZONE','CITY','EVENT'], dialect='excel') for row in reader: for key in row: if not row[key]: row[key] = last.get(key, "") writer.writerow(row) last = row On Feb 1, 3:37 pm, s... at pobox.com wrote: > Matt> I have a CSV file, exported from Excel, that has blank records in > Matt> it, and I need to fill them in with the values from the record > Matt> just above it until it hits a non-blank value. > > Try something like: > > #!/usr/bin/env python > > import sys > import csv > > last = {} > reader = csv.DictReader(open("test1.csv", "rb")) > writer = csv.DictWriter(open("test2.csv", "wb"), > sys.stdout, fieldnames="Zone City Event".split()) > for row in reader: > for key in row: > if not row[key]: > row[key] = last.get(key, "") > writer.writerow(row) > last = row > > Skip From joshua at eeinternet.com Mon Feb 26 18:54:04 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 26 Feb 2007 14:54:04 -0900 Subject: Why does SocketServer default allow_reuse_address = false? Message-ID: <45e3668e$0$16385$88260bb3@free.teranews.com> Considering that UNIX Network Programming, Vol 1 (by W. Richard Stevens) recommends "_All_ TCP servers should specify [SO_REUSEADDR] to allow the server to be restarted [if there are clients connected]," and that self.allow_reuse_address = False makes restarting a server a pain if there were connected clients, why does SocketServer default allow_reuse_address to False? It's kind of bemusing to subclass ThreadingTCPServer just to change one variable that arguably should have been True in the first place. Is there some history to this of which I'm not aware? Is there a good reason for it to default to false? j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From exarkun at divmod.com Tue Feb 20 19:22:01 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 20 Feb 2007 19:22:01 -0500 Subject: converting u'11\xa022' to '11\xa022' In-Reply-To: Message-ID: <20070221002201.25807.117561763.divmod.quotient.28438@ohm> On Tue, 20 Feb 2007 18:12:42 -0600, alf wrote: >Hi, >is there a more elegant way to do that: > >''.join([chr(ord(i)) for i in u'11\xa022' ]) > u'11\xa022'.encode('charmap') Jean-Paul From paul at boddie.org.uk Tue Feb 6 06:41:54 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Feb 2007 03:41:54 -0800 Subject: XMLRPC Server In-Reply-To: <1170761422.916375.6490@v33g2000cwv.googlegroups.com> References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> <52r41eF1p17pqU1@mid.uni-berlin.de> <1170761422.916375.6490@v33g2000cwv.googlegroups.com> Message-ID: <1170762114.244431.264770@l53g2000cwa.googlegroups.com> On 6 Feb, 12:30, "Lorenzo" wrote: > Unfortunately I have to use Apache. The server implementation will we > very easy, so I'm also considering more efficient solutions than > python You could try mod_python if there isn't an absolute requirement for CGI: http://www.modpython.org/ Some people might recommend other frameworks which operate in separate long-running processes, but if you don't have the freedom to have such processes, you might wish to consider focusing on the start-up costs of your CGI programs. Once upon a time, CGI was deemed very expensive because process creation was itself expensive, and many database- related CGI programs had to open connections to database systems whose connection costs were very expensive (eg. Oracle). While not spawning new processes and not opening and closing database connections avoids such costs, it is worth reviewing just how expensive such things are on modern operating systems (on modern hardware) and with other database systems (such as MySQL, which you said you were using). Ultimately, some benchmarking/profiling will indicate whether your performance expectations are realistic. Paul From ben at benfinney.id.au Mon Feb 12 03:24:20 2007 From: ben at benfinney.id.au (Ben Finney) Date: Mon, 12 Feb 2007 19:24:20 +1100 Subject: Tkinter and Tile Message-ID: <871wkvaimj.fsf@benfinney.id.au> Howdy all, Python programmers looking for a built-in GUI toolkit are told two things: one, Python already comes with a GUI toolkit, and two, it looks equally ugly on all platforms. This is because the Tk widget library, that Tkinter uses, defaults to looking like Motif, which hasn't been the default widget set of *anything* for a long time. The Tk folks are apparently getting their act together. Tile is a "theming engine" for Tk with widgets that look and act native:: Tile is included with Tcl/Tk 8.5 and Tcl developers, at least, are encouraged to migrate to using it:: What effect will this have on Python's Tkinter? Is it possible we can soon expect that the long-time, but much-neglected, built-in GUI module for Python can take advantage of this and provide widgets that look and act like the native GUI on Unix, Windows and MacOS? -- \ "Compulsory unification of opinion achieves only the unanimity | `\ of the graveyard." -- Justice Roberts in 319 U.S. 624 (1943) | _o__) | Ben Finney From arnd.zapletal at googlemail.com Mon Feb 5 06:16:32 2007 From: arnd.zapletal at googlemail.com (Arnd) Date: 5 Feb 2007 03:16:32 -0800 Subject: Decimating Excel files In-Reply-To: <52od99F1p5s4vU1@mid.individual.net> References: <52kn9eF1odticU1@mid.individual.net> <1170585737.044166.155920@v45g2000cwv.googlegroups.com> <52od99F1p5s4vU1@mid.individual.net> Message-ID: <1170674192.281475.275720@s48g2000cws.googlegroups.com> On 5 Feb., 10:53, greg wrote: > Interesting. But does this mean that "duplicating" is > actually from the wrong root? by definition: roots are never wrong ;) But indeed, you're right, one has to look at the root (eg connected verb) to understand the Numeralia they used: The number 2 has Numeralia duo, secundus, bini and bis: duo + plicare (=to fold): Cardinalia (how much? ->n-fold) > And also we have "bifurcation", yes, or eg "bisection" (from "bis"): Multiplicativa (how many times?) To complete the story: "binary" (from "bini"): Distributiva (how much each time?, to build groups or distributions) "second" (from "secundus"): Ordinalia (which? -> the 2nd, the 3rd etc) Arnd (I hated Latin) From deets at nospam.web.de Tue Feb 27 10:03:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Feb 2007 16:03:07 +0100 Subject: installing "pysqlite" References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <1172579710.514139.103170@s48g2000cws.googlegroups.com> Message-ID: <54ivhbF214sh0U1@mid.uni-berlin.de> Nader wrote: > On Feb 27, 12:44 pm, "Paul Boddie" wrote: >> On 27 Feb, 10:31, Nader Emami wrote: >> >> > I have installed "TurboGears" and I would install 'pysqlite' also. I am >> > a user on a Linux machine. If I try to install the 'pysqlite' with >> > 'easy_install' tool I get the next error message. The error message is >> > longer than what I send here. >> >> [...] >> >> > src/connection.h:33:21: sqlite3.h: No such file or directory >> >> [...] >> >> > Could somebody tell me what I have to do to install 'pysqlite'? >> >> Install SQLite, perhaps? If the pysqlite build process can't find >> sqlite3.h then you either don't have SQLite installed, or you don't >> have the headers for SQLite installed. I'd recommend that you check >> your installed packages for the SQLite libraries (eg. libsqlite3-0 on >> Ubuntu) and/or the user interface (eg. sqlite3) and for the >> development package (eg. libsqlite3-dev). >> >> If you can't install the packages, install SQLite from source >> (seehttp://www.sqlite.org/) and try and persuade pysqlite to use your own >> SQLite installation - there's a setup.cfg file in the pysqlite >> distribution which may need to be changed to achieve this, but I don't >> know how that interacts with setuptools. >> >> Paul > > Thank for your reaction. I don't know also how the interaction sith > 'easy_install' is. I think that I have to install 'pysqlite' from > source code also, because i can change ther the 'setup.cfg' file and I > can give there where the 'libsqlie3' is. I think you are ok with easyinstall here. But as Paul said - you need the sqlite3-headers. Usually, these are in a package called sqlite3-dev or something. However, if you happen to have a decent distribution (read: debian-based), you should be able to install pysqlite2 as a package itself - no need to easy_install it. Diez From skip at pobox.com Mon Feb 26 10:49:45 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 26 Feb 2007 09:49:45 -0600 Subject: The Python interactive interpreter has no command history In-Reply-To: <1172485899.900548.84710@v33g2000cwv.googlegroups.com> References: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> <45d494c1$0$5104$ba4acef3@news.orange.fr> <1172485899.900548.84710@v33g2000cwv.googlegroups.com> Message-ID: <17891.409.564696.631585@montanaro.dyndns.org> > I will try add readline library in my system. Thomas, Once you have it installed here's an example of how to use it for command history: http://www.webfast.com/~skip/python/completions.py Skip From steve at REMOVEME.cybersource.com.au Tue Feb 20 23:19:19 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Feb 2007 15:19:19 +1100 Subject: code-object References: Message-ID: On Tue, 20 Feb 2007 20:39:43 -0500, LG wrote: > Hi, All, > >>>>code = compile('print "hello everyone, how are you? "', '', > 'exec') >>>>exec code > hello everyone, how are you? >>>>print code > ", line 1> > > how to print the code object ? You just did. > like the one on .pyc What do you mean? What output do you want to see? Does this help? >>> import dis >>> code = compile("print 'hello world'", "string", "exec") >>> dis.dis(code) 1 0 LOAD_CONST 0 ('hello world') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 1 (None) 8 RETURN_VALUE -- Steven D'Aprano From lists at fabis-site.net Thu Feb 22 09:22:37 2007 From: lists at fabis-site.net (Fabian Steiner) Date: Thu, 22 Feb 2007 15:22:37 +0100 Subject: How to test whether a host is reachable? Message-ID: Hello! As the subject says I need to test whether a host computer in our network is reachable or not. At the moment I simply attempt to connect to a given port that is open when the machine is online: [...] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect(('192.168.0.100', 80)) except socket.error: print >>sys.stderr "Server offline" sock.close() [...] Now I am wondering if there isn't any better method which would be more general. In fact, I think of something like a python version of ping which only tries to send ICMP packets. However, I don't know what the code has to look like then. Any ideas or suggestions? Thanks, Fabian From deets at nospam.web.de Tue Feb 6 05:14:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 Feb 2007 11:14:11 +0100 Subject: How to prevent from race conditions to share data between many process and thread in python References: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> Message-ID: <52r2njF1of0tpU1@mid.uni-berlin.de> mars wrote: > I use TurboGears to do some web service. TurboGears use cherrypy. When > web browser access this site, the cherrypy will call my python > program. So my program looks like a lib. When web browser access the > site, the http server will fock a process or gerenate a thread. I need > share some data or operate some files. How can I prevent from race > conditions. Is there any way can I lock this. > Thank you in advance! There are the Lock and RLock objects available in the module threading. Diez From alain.walter at thalesgroup.com Wed Feb 28 03:19:36 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 28 Feb 2007 00:19:36 -0800 Subject: gtk.mainquit is deprecated In-Reply-To: <3w6o7cbnr45v$.1hvyvdm2i2ffj$.dlg@40tude.net> References: <1172570193.721466.286700@8g2000cwh.googlegroups.com> <3w6o7cbnr45v$.1hvyvdm2i2ffj$.dlg@40tude.net> Message-ID: <1172650775.999879.130630@h3g2000cwc.googlegroups.com> Thank you You're right. a connection was made between "destroy" and gtk.main_quit (a bad cut and paste from an old application). On 27 f?v, 17:25, Alan Franzoni wrote: > Il 27 Feb 2007 01:56:33 -0800, awalter1 ha scritto: > > > But I don't want to quit the application, I need only to close the > > window. > > My application includes others places where "self.window.destroy()" > > instruction is used and the execution is done without warning. > > Very strange. > > But does then the application end, as if gtk.main_quit() were called? If > it's the case, it's very likely you connected the 'destroy' signal on that > very window and you set gtk.mainquit() as the callback. > > -- > Alan Franzoni > - > Togli .xyz dalla mia email per contattarmi. > Remove .xyz from my address in order to contact me. > - > GPG Key Fingerprint (Key ID = FE068F3E): > 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From lbates at websafe.com Mon Feb 26 10:20:47 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 26 Feb 2007 09:20:47 -0600 Subject: convert python scripts to exe file In-Reply-To: References: Message-ID: <45E2FACF.4090503@websafe.com> Eric CHAO wrote: > I know py2exe can make an exe file. But python runtime dll is still > there. How can I combine the dll file into the exe, just make one > file? > > Thanks. You can use the bundle= parameter to get "less" files, but you can't get to only 1 because you need mscvr71.dll and w9xpopen.exe at a minimum as external files. If you want to have only 1 .EXE to distribute, use Inno Installer. Your users will thank you for having a proper installer, uninstaller. -Larry Bates From kwatch at gmail.com Sun Feb 4 15:29:35 2007 From: kwatch at gmail.com (kwatch at gmail.com) Date: 4 Feb 2007 12:29:35 -0800 Subject: result of os.times() is different with 'time' command In-Reply-To: References: <1170441001.097986.294510@h3g2000cwc.googlegroups.com> <1170446796.156141.201960@v33g2000cwv.googlegroups.com> Message-ID: <1170620974.977293.185640@k78g2000cwa.googlegroups.com> Thank you, aspineux and Douglas. Douglas's analysis is especially great. I changed HZ to CLK_TCK in Python-2.5/Modules/posixmodule.c and got the proper result! ==================== $ time /usr/local/python2.5/bin/python ostimetest.rb n=35, v=14930352 utime=12.42, stime=0.04 real 0m13.621s user 0m12.438s sys 0m0.063s ==================== Great job, Douglas. -- regards, kwatch s... at signature.invalid (Douglas Wells) wrote: > [various posting problems corrected and response interspersed in > previous post for purposes of coherent response] > > In article <1170446796.156141.201... at v33g2000cwv.googlegroups.com>, > > > > "aspineux" writes: > > On 2 Feb, 19:30, kwa... at gmail.com wrote: > > > Hi, > > > > I have a question about os.times(). > > > os.times() returns a tuple containing user time and system time, > > > but it is not matched to the result of 'time' command. > > > For example, os.times() reports that user time is 39.85 sec, > > > but 'time' command reports that user time is 28.55sec. > > > (machine: Python2.5, MacOS X 10.4 Tiger, MacBook 1.83GHz intel core > > > duo) > > > > [ source elided ] > > > I dont see anything wrong ! > > Did you try to measure time with your watch ? > > Did you try a simple python test.py without the time command ? > > Maybe python is 'disturbed' by the intel core > > > can you try this ? > > > # strace python test.py 2>&1 | grep time > > times({tms_utime=1, tms_stime=1, tms_cutime=0, tms_cstime=0}) = > > 430217777 > > times({tms_utime=2238, tms_stime=2, tms_cutime=0, tms_cstime=0}) = 430220049 > > write(1, "n=35, v=14930352\nutime=22.37, st"..., 41n=35, v=14930 52 > > utime=22.37, stime=0.01 > > Note that this likely won't work. First, strace is not native to > OS X; ktrace is the analogous native command. Second, OS X almost > certainly implements the times system call in terms of getrusage. > > > > > > Result: > > > ==================== > > > $ python -V > > > Python 2.5 > > > $ time python ostimetest.py > > > n=35, v=14930352 > > > utime=39.85, stime=0.216666666667 > > > real 0m28.554suser 0m23.938ssys 0m0.177s > > > ==================== > > > > This shows that os.times() reports that user time is 39.85sec, > > > but time command shows that user time is 23.938sec. > > > Why os.times() reports wrong result? Do I have any mistake? > > > > -- > > > kwatch > > Yes, I can reproduce this on my FreeBSD system. No, I do not believe > that you have made a mistake. Yes, I believe that you have uncovered > a bug in the Python os/posix modules. > > Here's my analysis (although I should note that I've not looked > at the source of Python previously). I'm looking at Python 2.4.3, > but this looks like a long existing bug: > > The following code exists in the source code module > Modules/posixmodule.c @ posix_times: > struct tms t; > clock_t c; > [ ... ] > c = times(&t); > [ ... ] > return Py_BuildValue("ddddd", > (double)t.tms_utime / HZ, > (double)t.tms_stime / HZ, > (double)t.tms_cutime / HZ, > (double)t.tms_cstime / HZ, > (double)c / HZ); > This is incorrect. It should not be dividing by HZ, but by the > result of the dynamic value 'sysconf (_SC_CLK_TCK)'. Even if > it were to use a compile time value, the proper value would be > CLK_TCK, not HZ. > > So here's what's happening. Neither my FreeBSD nor the OP's Mac > defines HZ as a compile time variable, but the same source module > also contains the following code: > #ifndef HZ > #define HZ 60 /* Universal constant :-) */ > #endif /* HZ */ > So, the Python posix module is using 60 instead of the proper > value, which happens to be 128 on my FreeBSD, and 100 on the OP's > OS X(*). (BTW, this sort of historic code is exactly why POSIX > no longer defines HZ.) > > In support of this, I note that the following ratios exist: > user time from os.times / user time from time command > 39.85 / 23.938 => 1.665 > CLK_TCK / HZ > 100 / 60 => 1.667 > which are in reasonably close agreement! > > - dmw > > [*] I've actually only looked at OS X for the PPC platform, not > for the User's Intel platform, but I'm fairly certain that the > CLK_TCK value is the same on both. > > -- > . Douglas Wells . Connection Technologies . > . Internet: -sp9804- -at - contek.com- . From nike.is.nospam at home.se Sun Feb 25 10:01:08 2007 From: nike.is.nospam at home.se (Niclas) Date: Sun, 25 Feb 2007 16:01:08 +0100 Subject: convert strings to utf-8 Message-ID: Hi I'm having trouble to work with the special charcters in swedish (? ? ? ? ? ?). The script is parsing and extracting information from a webpage. This works fine and I get all the data correctly. The information is then added to a rss file (using xml.dom.minidom.Document() to create the file), this is where it goes wrong. Letters like ? ? ? get messed up and the rss file does not validate. How can I convert the data to UTF-8 without loosing the special letters? Thanks in advance From Greg Tue Feb 27 16:01:24 2007 From: Greg (Greg) Date: Tue, 27 Feb 2007 13:01:24 -0800 Subject: import parent Message-ID: <45e49c54$0$6620$9a6e19ea@unlimited.newshosting.com> How does one get access to the class that imported a module. For example: foo imports bar -- how does bar access foo? Thanks. From tiedon_jano at hotmail.com Fri Feb 2 10:14:14 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Fri, 02 Feb 2007 15:14:14 GMT Subject: compound statement from C "?:" In-Reply-To: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> Message-ID: Holger kirjoitti: > > I would like to do the equivalent if python of the C line: > printf("I saw %d car%s\n", n, n != 1 ? "s" : "") > > Please help > > /Holger > In this particular case you don't need the ternary operator: print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) Cheers, Jussi From cvanarsdall at mvista.com Wed Feb 7 19:18:20 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 07 Feb 2007 16:18:20 -0800 Subject: multithreading concept In-Reply-To: <004d01c74b12$81c16c20$e9936540@cisco.com> References: <1170865166.423764.87050@s48g2000cws.googlegroups.com><1170872694.018720.301410@m58g2000cwm.googlegroups.com> <004d01c74b12$81c16c20$e9936540@cisco.com> Message-ID: <45CA6C4C.30606@mvista.com> S.Mohideen wrote: > I would like to add my problem in this thread. > I have a network application in Python which sends and recv using a single > socket. > There is a dictionary on which I store/read data values. I want to seperate > the send and recv functionality on two different processes so that the > parallel execution becomes fast. Is there any way to do so, so that the > Dict's consitency is not lost(able to read & write) and also the performance > improves. I am looking upon the MPI4Py module to see if it does the job for > me. Any ideas would be appreciated. > Well, from your description so far I think that MPI is going to be a bit of overkill. I think you should consider threads or processors with shared memory/objects (POSH). Then take a look at a producer/consumer program to see how it works, that should get you to where you need to go. HTH -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From Finger.Octopus at gmail.com Fri Feb 9 14:03:53 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 9 Feb 2007 11:03:53 -0800 Subject: Database Programming with Python In-Reply-To: <1171040420.760665.326290@m58g2000cwm.googlegroups.com> References: <1171034880.089616.113380@p10g2000cwp.googlegroups.com> <1171040420.760665.326290@m58g2000cwm.googlegroups.com> Message-ID: <1171047833.095277.62350@a75g2000cwd.googlegroups.com> > You could use Dejavu 1.5, which has its own wrapper [1] for ADO (both > MS Access and SQL Server/MSDE). No ODBC necessary or desired. > > If you want an ADO wrapper without the full Dejavu ORM, it's possible > (but not heavily documented) to use dejavu's geniusql layer on its > own. That would give you connection mgmt (and pooling), along with the > ability to execute arbitrary SQL. > > Robert Brewer > System Architect > Amor Ministries > fuman... at amor.org > > [1]http://projects.amor.org/dejavu/browser/trunk/storage/storeado.py There are no examples of Dejavu that I found yet. I have installed it but don't know how to use or call its functions. From http Mon Feb 5 17:15:45 2007 From: http (Paul Rubin) Date: 05 Feb 2007 14:15:45 -0800 Subject: Python does not play well with others References: <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170711562.894756.120270@h3g2000cwc.googlegroups.com> Message-ID: <7x3b5k8d4e.fsf@ruckus.brouhaha.com> "Graham Dumpleton" writes: > Yes, these per VirtualHost interpreter instances will only be created > on demand in the child process when a request arrives which > necessitates it be created and so there is some first time setup for > that specific interpreter instance at that point, but the main Python > initialisation has already occurred so this is minor. Well ok, but what if each of those interpreters wants to load, say, the cookie module? Do you have separate copies of the cookie module in each interpreter? Does each one take the overhead of loading the cookie module? It would be neat if there was a way of including frequently used modules in the shared text segment of the interpreters, as created during the initial build process. GNU Emacs used to do something like that with a contraption called "unexec" (it could dump out parts of its data segment into a pure (shared) executable that you could then run without the overhead of loading all those modules) but the capability went away as computers got faster and it became less common to have a lot of Emacs instances weighing down timesharing systems. Maybe it's time for a revival of those techniques. From sickcodemonkey at gmail.com Tue Feb 27 20:23:58 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 27 Feb 2007 20:23:58 -0500 Subject: Special Characters Message-ID: <2adc542f0702271723m4e813d0ckf907227f76992a93@mail.gmail.com> I have a quick question about handling values with special characters. Lets say I have a file which contains: ================================== blah#blah ================================== Here is what I have for my code: f6 = open(fileAttached) msInfo = f6.readlines(); f6.close() varName = msInfo[0] .... smtp.login(uname,varName) ... ================================== I am trying to connect to a mailserver, and it keeps failing. My guess is that the "#" sign messing up. Is there anyway to encode that character? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregturn at mindspring.com Fri Feb 2 16:59:58 2007 From: gregturn at mindspring.com (gregturn at mindspring.com) Date: 2 Feb 2007 13:59:58 -0800 Subject: Spring Python 0.2.0 is released In-Reply-To: <1170393447.301368.124140@l53g2000cwa.googlegroups.com> References: <1170393447.301368.124140@l53g2000cwa.googlegroups.com> Message-ID: <1170453598.752876.75280@m58g2000cwm.googlegroups.com> I have managed to update the site documentation on ApplicationSecurity (the newer module in this release). Took me awhile, and one time I accidentally browsed to another site and lost what I had started. Well, it is in there now at http://springpython.python-hosting.com/wiki/ApplicationSecurity From B.Ogryczak at gmail.com Tue Feb 6 05:57:43 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 6 Feb 2007 02:57:43 -0800 Subject: Repr or Str ? In-Reply-To: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> References: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> Message-ID: <1170759462.977048.255330@v33g2000cwv.googlegroups.com> On Feb 6, 11:47 am, "Johny" wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences > Thanks RTFM. http://docs.python.org/ref/customization.html __repr__( self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. __str__( self) Called by the str() built-in function and by the print statement to compute the ``informal'' string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object. From jcrocholl at googlemail.com Mon Feb 5 17:13:04 2007 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 5 Feb 2007 14:13:04 -0800 Subject: Taint (like in Perl) as a Python module: taint.py Message-ID: <1170713584.199237.22210@v33g2000cwv.googlegroups.com> The following is my first attempt at adding a taint feature to Python to prevent os.system() from being called with untrusted input. What do you think of it? # taint.py - Emulate Perl's taint feature in Python # Copyright (C) 2007 Johann C. Rocholl # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Emulate Perl's taint feature in Python This module replaces all functions in the os module (except stat) with wrappers that will raise an Exception called TaintError if any of the parameters is a tainted string. All strings are tainted by default, and you have to call untaint on a string to create a safe string from it. Stripping, zero-filling, and changes to lowercase or uppercase don't taint a safe string. If you combine strings with + or join or replace, the result will be a tainted string unless all its parts are safe. It is probably a good idea to run some checks on user input before you call untaint() on it. The safest way is to design a regex that matches legal input only. A regex that tries to match illegal input is very hard to prove complete. You can run the following examples with the command python taint.py -v to test if this module works as designed. >>> unsafe = 'test' >>> tainted(unsafe) True >>> os.system(unsafe) Traceback (most recent call last): TaintError >>> safe = untaint(unsafe) >>> tainted(safe) False >>> os.system(safe) 256 >>> safe + unsafe u'testtest' >>> safe.join([safe, unsafe]) u'testtesttest' >>> tainted(safe + unsafe) True >>> tainted(safe + safe) False >>> tainted(unsafe.join([safe, safe])) True >>> tainted(safe.join([safe, unsafe])) True >>> tainted(safe.join([safe, safe])) False >>> tainted(safe.replace(safe, unsafe)) True >>> tainted(safe.replace(safe, safe)) False >>> tainted(safe.capitalize()) or tainted(safe.title()) False >>> tainted(safe.lower()) or tainted(safe.upper()) False >>> tainted(safe.strip()) or tainted(safe.rstrip()) or tainted(safe.lstrip()) False >>> tainted(safe.zfill(8)) False >>> tainted(safe.expandtabs()) True """ import os import types class TaintError(Exception): """ This exception is raised when you try to call a function in the os module with a string parameter that isn't a SafeString. """ pass class SafeString(unicode): """ A string class that you must use for parameters to functions in the os module. """ def __add__(self, other): """Create a safe string if the other string is also safe.""" if tainted(other): return unicode.__add__(self, other) return untaint(unicode.__add__(self, other)) def join(self, sequence): """Create a safe string if all components are safe.""" for element in sequence: if tainted(element): return unicode.join(self, sequence) return untaint(unicode.join(self, sequence)) def replace(self, old, new, *args): """Create a safe string if the replacement text is also safe.""" if tainted(new): return unicode.replace(self, old, new, *args) return untaint(unicode.replace(self, old, new, *args)) def strip(self, *args): return untaint(unicode.strip(self, *args)) def lstrip(self, *args): return untaint(unicode.lstrip(self, *args)) def rstrip(self, *args): return untaint(unicode.rstrip(self, *args)) def zfill(self, *args): return untaint(unicode.zfill(self, *args)) def capitalize(self): return untaint(unicode.capitalize(self)) def title(self): return untaint(unicode.title(self)) def lower(self): return untaint(unicode.lower(self)) def upper(self): return untaint(unicode.upper(self)) # Alias to the constructor of SafeString, # so that untaint('abc') gives you a safe string. untaint = SafeString def tainted(param): """ Check if a string is tainted. If param is a sequence or dict, all elements will be checked. """ if isinstance(param, (tuple, list)): for element in param: if tainted(element): return True elif isinstance(param, dict): return tainted(param.values()) elif isinstance(param, (str, unicode)): return not isinstance(param, SafeString) else: return False def wrapper(function): """Create a new function that checks its parameters first.""" def check_first(*args, **kwargs): """Check all parameters for unsafe strings, then call.""" if tainted(args) or tainted(kwargs): raise TaintError return function(*args, **kwargs) return check_first def install_wrappers(module, innocent): """ Replace each function in the os module with a wrapper that checks the parameters first, except if the name of the function is in the innocent list. """ for name, function in module.__dict__.iteritems(): if name in innocent: continue if type(function) in [types.FunctionType, types.BuiltinFunctionType]: module.__dict__[name] = wrapper(function) install_wrappers(os, innocent = ['stat']) if __name__ == '__main__': import doctest doctest.testmod() From rhamph at gmail.com Thu Feb 15 04:45:52 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 15 Feb 2007 01:45:52 -0800 Subject: threading and multicores, pros and cons In-Reply-To: <1171495836.015329.231010@v45g2000cwv.googlegroups.com> References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> <1171495836.015329.231010@v45g2000cwv.googlegroups.com> Message-ID: <1171532752.326822.127780@h3g2000cwc.googlegroups.com> On Feb 14, 4:30 pm, "MRAB" wrote: > Hmm. I wonder whether it would be possible to have a pair of python > cores, one for single-threaded code (no locks necessary) and the other > for multi-threaded code. When the Python program went from single- > threaded to multi-threaded or multi-threaded to single-threaded there > would be a switch from one core to the other. I have explored this option (and some simpler variants). Essentially, you end up rewriting a massive amount of CPython's codebase to change the refcount API. Even all the C extension types assume the refcount can be statically initialized (which may not be true if you're trying to make it efficient on multiple CPUs.) Once you realize the barrier for entry is so high you start considering alternative implementations. Personally, I'm watching PyPy to see if they get reasonable performance using JIT. Then I can start hacking on it. -- Adam Olsen, aka Rhamphoryncus From __peter__ at web.de Mon Feb 19 04:25:22 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 10:25:22 +0100 Subject: Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"? References: <1171825087.879824.14210@v45g2000cwv.googlegroups.com> <1171871775.848808.102080@q2g2000cwa.googlegroups.com> Message-ID: openopt at ukr.net wrote: > Ok, thx > But can I somehow determing how many outputs does caller func require? > for example: > MATLAB: > function [objFunVal firstDerive secondDerive] = simpleObjFun(x) > objFunVal = x^3; > if nargout>1 > firstDerive = 3*x^2; > end > if nargout>2 > secondDerive = 6*x; > end > > So if caller wants only > [objFunVal firstDerive] = simpleObjFun(15) > than 2nd derivatives don't must to be calculated with wasting cputime. > Is something like that in Python? For a sequence whose items are to be calulated on demand you would typically use a generator in Python. You still have to provide the number of items somehow (see the head() helper function). from itertools import islice def derive(f, x0, eps=1e-5): while 1: yield f(x0) def f(x, f=f): return (f(x+eps) - f(x)) / eps def head(items, n): return tuple(islice(items, n)) if __name__ == "__main__": def f(x): return x**6 print head(derive(f, 1), 4) Peter From http Wed Feb 14 15:09:34 2007 From: http (Paul Rubin) Date: 14 Feb 2007 12:09:34 -0800 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> Message-ID: <7x3b58jybl.fsf@ruckus.brouhaha.com> "redawgts" writes: > try: > f = file(self.filename, 'rb') ... > Can someone tell me what's wrong with the code? Various people have explained the error: if the file open attempt fails, f is never assigned. Doing it the right way (i.e. handling the potential exceptions separately) with try/except statements is messy, so it's worth mentioning that 2.5 adds the new "with" statement to clean this up. I'm not using 2.5 myself yet so maybe someone will have to correct me, but I think you'd write: from __future__ import with_statement self.isDataLoaded = False with open(self.filename, 'rb') as f: f.seek(DATA_OFFSET) self.__data = f.read(DATA_SIZE) self.isDataLoaded = True and that should handle everything, closing the file automatically. From skip at pobox.com Sat Feb 10 08:28:44 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 10 Feb 2007 07:28:44 -0600 Subject: pycallgraph 0.2.0 In-Reply-To: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> References: <1171091596.649381.121380@j27g2000cwj.googlegroups.com> Message-ID: <17869.51340.789272.907313@montanaro.dyndns.org> Gerald> I just released a new version of pycallgraph. It has many Gerald> improvements over 0.1.0. Looks nice. Before you get too far... Is there any chance that you can support ASCII output mode (obviously not laid out in two dimensions, just using indentation) so the GraphViz requirement can become optional? GraphViz has so many dependencies of its own (and many of them are GTK-related) that the chance of me satisfying them is very small. (I'm on Solaris and Mac, not Linux, so I don't have the benefit of a Linux distro to solve those particular headaches for me.) Thanks, Skip From simone.leo at gmail.com Fri Feb 9 05:33:52 2007 From: simone.leo at gmail.com (Tekkaman) Date: 9 Feb 2007 02:33:52 -0800 Subject: unique elements from list of lists Message-ID: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> I have a list of lists and I want to define an iterator (let's call that uniter) over all unique elements, in any order. For example, calling: sorted(uniter([['a', 'b', 'd'], ['b', 'c'], ['a', 'c', 'd']])) must return ['a', 'b', 'c', 'd']. I tried the following implementations: from itertools import chain def uniter1(listOfLists): for item in set(chain(*listOfLists)): yield item def uniter2(listOfLists): for item in reduce( lambda x,y: x|y, [set(list_) for list_ in listOfLists] ): yield item speed test with timeit says the first one is slightly faster. What bothers me is that it builds a set from an iterator and then another iterator from the set. Is there a way to implement this using only iterators? I also tried a "full python" implementation (by that I mean one that does not use the built-in set and keeps track of previously yielded items in a list) but the one I pulled out is about 180 times slower. Here it is: def uniter3(listOfLists): done = [] for list_ in listOfLists: for item in list_: if not item in done: done.append(item) yield item Thanks in advance for any contribution. -- Simone From paul at boddie.org.uk Sat Feb 3 18:40:32 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Feb 2007 15:40:32 -0800 Subject: Python does not play well with others In-Reply-To: References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <1170546032.316062.133050@m58g2000cwm.googlegroups.com> Chris Mellon wrote: > On 02 Feb 2007 11:10:04 -0800, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: > > "Paul Boddie" writes: > > > If the hosting provider doesn't want to install MySQLdb then it may > > > not be a technical issue - perhaps they just can't be bothered to > > > install it, possibly because there's no demand or benefit to the > > > bottom line in doing so. > > > > Why should the hosting provider need to devote attention to something > > like that? I agree with the remark about paying them for the service. The only reason why a provider would have Python available, an allocation of MySQL database instances per user, but not MySQLdb installed, would be that they want to stick with a conservative set of packages which requires zero admin (and thus zero outlay on administration), and that they don't understand obvious requirements for using MySQL with Python. I don't think they'd get my business. [...] > There are a number of languages which are primarily used for "web > development". PHP is the *only* one that ships with MySQL client > access. > > Ruby doesn't (only primarily web development because of rails) > ASP, either .NET or classic, doesn't. > Java (in any form I'm aware of) doesn't. You need to get the MySQL Connector/J driver, or whatever it's called this month. > Cold Fusion doesn't. > Perl doesn't. > > Who wants to host at a company that can't install packages anyway? Quite. I imagine that most GNU/Linux distributions (and various BSDs) provide at least some version of MySQLdb as a package. If a company can't manage to provide Python plus MySQL, and then let their users combine the two by installing a stock package (a single command or some mouse clicks in the package manager), without offering up "concerns" about how "secure" such a package might be (which I imagine some providers might do if they want to discourage people from using it), then I'd be a bit more concerned about how well they're keeping up with security updates and how good they are at performing other elementary administration tasks. Paul From chris at kateandchris.net Fri Feb 2 14:28:57 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 2 Feb 2007 14:28:57 -0500 Subject: OSS and ALSA In-Reply-To: References: Message-ID: <20070202192857.GA25119@kateandchris.net> On Fri, Feb 02, 2007 at 12:08:22AM -0200, Silver Rock wrote: > Hi all, > > I've seen that python comes by default with a module for communication > with OSS. > > I've looked for a ALSA module too (pyalsa) but it seems to handle only > limited operations. how about http://sourceforge.net/projects/pyalsaaudio ? > > Can anyone confirm or point wrong the impression that a newbie should use > the ossaudiodev module? Alsa has OSS emulation. You can also try the sound parts of PyGame which are cross platform: http://www.pygame.org/ > > thanks, > cl > -- > http://mail.python.org/mailman/listinfo/python-list From rhc28 at cornell.edu Tue Feb 20 15:01:17 2007 From: rhc28 at cornell.edu (Rob Clewley) Date: Tue, 20 Feb 2007 15:01:17 -0500 Subject: ANN: PyDSTool now compatible with numpy 1.0.1, scipy 0.5.2 and 64-bit CPUs. Message-ID: We are pleased to announce version 0.84 of PyDSTool, an open-source dynamical systems simulation, modeling, and analysis package. This long-overdue release is primarily intended to bring existing PyDSTool functionality up to date with the latest numpy and scipy releases (previous versions required scipy 0.3.2, numarray, numeric, etc). Also, PyDSTool is now compatible with 64-bit CPUs. While we have added a few new features and made several fixes, major improvements to functionality are in the pipeline for version 0.90. Please see http://pydstool.sourceforge.net for release notes and documentation, and http://sourceforge.net/projects/pydstool for downloading. As ever, please send us feedback if you have any problems with this new release or ideas and code contributions for future releases. Regards, Rob, Erik, and Drew. Center for Applied Mathematics, Cornell University. ****************** PyDSTool is an integrated simulation, modeling and analysis package for dynamical systems, written in Python (and partly in C). It is being developed at Cornell University, and the source code is available under the terms of the BSD license. PyDSTool runs on Linux, Windows, and Macs, and aims to have a minimal number of package dependencies. From __peter__ at web.de Tue Feb 27 04:09:45 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Feb 2007 10:09:45 +0100 Subject: Is type object an instance or class? References: <1172541599.948530.210120@z35g2000cwz.googlegroups.com> Message-ID: JH wrote: > I found that a type/class are both a subclass and a instance of base > type "object". > > It conflicts to my understanding that: > > 1.) a type/class object is created from class statement > 2.) a instance is created by "calling" a class object. > > A object should not be both a class and an instance at the same time. A class should be an instance. Now what? > Further I found out there is a special type call "type" that is a > subclass of base type "object". All other types are instances of this > type. Even base type "object" is an instance of this special type. > > What is role of this type "type" in object creation? Could someone > there straighten this concept a little? The type of a class is called metaclass. The creation of a class is the same as an instantiation of its metaclass. You can therefore write class A(object): answer = 42 as A = type("A", (object,), dict(answer=42)) So now we know how to make a class from a metaclass, how can we make a metaclass? The tailbiting answer is that a metaclass is a class, too. Can you figure out the result of isinstance(type, type)? Peter From jandre_balt at yahoo.co.uk Sun Feb 4 14:42:23 2007 From: jandre_balt at yahoo.co.uk (Jandre) Date: 4 Feb 2007 11:42:23 -0800 Subject: Recursive zipping of Directories in Windows In-Reply-To: References: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> Message-ID: <1170618143.449135.37580@v33g2000cwv.googlegroups.com> On Feb 1, 9:39 pm, Larry Bates wrote: > Jandre wrote: > > Hi > > > I am a python novice and I am trying to write a python script (most of > > the code is borrowed) to Zip a directory containing some other > > directories and files. The script zips all the files fine but when it > > tries to zip one of the directories it fails with the following > > error: > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > > The script I am using is: > > > import zipfile, os > > > def toZip( directory, zipFile ): > > """Sample for storing directory to a ZipFile""" > > z = zipfile.ZipFile( > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > ) > > def walker( zip, directory, files, root=directory ): > > for file in files: > > file = os.path.join( directory, file ) > > # yes, the +1 is hacky... > > archiveName = file[len(os.path.commonprefix( (root, > > file) ))+1:] > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > > print file > > os.path.walk( directory, walker, z ) > > z.close() > > return zipFile > > > if __name__ == "__main__": > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > > I have tried to set the permissions on the folder, but when I check > > the directory permissions it is set back to "Read Only" > > > Any suggestions? > > > Thanks > > Johan Balt > > Couple of quick suggestions that may help: > > 1) don't use 'file' as a variable name. It will mask > the builtin file function. If it hasn't bitten you before > it will if you keep doing that. > > 2) If you put the target .zip file in the directory you are > backing what do you expect the program to do when it comes > to the file you are creating as you walk the directory? You > haven't done anything to 'skip' it. > > 3) Your commonprefix and +1 appears to result in same > information that the easier to use os.path.basename() > would give you. Double check me on that. > > I don't see anything that references C:\\aaa\temp in your > code. Does it exist on your hard drive? If so does it > maybe contain temp files that are open? zipfile module > can't handle open files. You must use try/except to > catch these errors. > > Hope info helps. > > -Larry Thank you Larry. I've changed the code as epr your advice. The code is now: import zipfile, os def toZip( directory, zipFile ): """Sample for storing directory to a ZipFile""" z = zipfile.ZipFile( zipFile, 'w', compression=zipfile.ZIP_DEFLATED ) def walker( zip, directory, files, root=directory ): for f in files: f = os.path.join( directory, f ) archiveName = os.path.basename(f) zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) print f os.path.walk( directory, walker, z ) z.close() return zipFile if __name__ == "__main__": toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) I still get the same error: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Python24\Scripts\dirZip.py", line 20, in ? toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) File "C:\Python24\Scripts\dirZip.py", line 14, in toZip os.path.walk( directory, walker, z ) File "C:\Python24\lib\ntpath.py", line 329, in walk func(arg, top, names) File "C:\Python24\Scripts\dirZip.py", line 12, in walker zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) File "C:\Python24\lib\zipfile.py", line 405, in write fp = open(filename, "rb") IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp' c:\\aaa\\temp is a directory in the directory I an trying to zip. I want to use this script to back up my work once a day and would like to keep the directory structure as is. I can zip the files in c:\aaa\tem fine so I guess that there aren't any open files in the directory. Any more ideas? From duncan.booth at invalid.invalid Thu Feb 8 02:58:33 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Feb 2007 07:58:33 GMT Subject: 'IF' Syntax For Alternative Conditions References: Message-ID: "Gabriel Genellina" wrote: > Note that most (if not all) Python keywords are lowercase. > All keywords are lower case. and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 'None' is not entirely lowercase, and you cannot assign to it, but technically it isn't a keyword. From http Mon Feb 5 20:16:43 2007 From: http (Paul Rubin) Date: 05 Feb 2007 17:16:43 -0800 Subject: Python does not play well with others References: <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> <1170712668.870316.247580@q2g2000cwa.googlegroups.com> <1170715521.475189.18330@k78g2000cwa.googlegroups.com> <7xzm7sryao.fsf@ruckus.brouhaha.com> <1170718846.989763.204120@s48g2000cws.googlegroups.com> Message-ID: <7xsldk13wk.fsf@ruckus.brouhaha.com> "Graham Dumpleton" writes: > > Certainly launching any new threads should be postponed til after the > > fork. > > Except that you can't outright prevent it from being done as a Python > module could create the threads as a side effect of the module import > itself. Yeah, the preload would have to be part of the server configuration, requiring appropriate care in choosing the preloaded modules (they'd normally be stdlib modules which rarely do uncivilized things like launch new threads on import). It wouldn't do to let random user scripts into the preload. One could imagine languages in which this could be enforced by a static type system. Hmm. From gagsl-py at yahoo.com.ar Fri Feb 9 20:00:06 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Feb 2007 22:00:06 -0300 Subject: Matching Strings References: Message-ID: En Fri, 09 Feb 2007 21:03:32 -0300, escribi?: > I'm not sure how to change a string so that it matches another one. > > My application (using wxPython and SQLite3 via pysqlite2) needs to > compare > a string selected from the database into a list of tuples with another > string selected in a display widget. > > An extract of the relevant code is: > > selName = self.polTree.GetItemText(selID) > ... > for item in self.appData.polNat: > print 'Item: ', item, '\n', 'selName: ', selName, '\n' > if item == selName: > print '***** ', self.appData.polNat[1] > > The last comparison and print statement never work because the strings > are > presented this way: > > Item: (u'ground water',) > selName: ground water Forget about re and slicing and blind guessing... item appears to be a tuple; in these cases repr is your friend. See what happens with: print repr(item), type(item) If it is in fact a tuple, you should ask *why* is it a tuple (maybe could have many items?). And if it's just an artifact and actually it always will be a single: assert len(item)==1 item = item[0] if item... -- Gabriel Genellina From sseebbaa123 at yahoo.com Fri Feb 9 00:08:45 2007 From: sseebbaa123 at yahoo.com (jiddu) Date: Fri, 09 Feb 2007 00:08:45 -0500 Subject: Is Python for me? Message-ID: Hi, I'm planning to create a poker calculator, I learned some basic in highschool years ago and I was told for beginners Python is a good language to start. What I wanted to do is to first write a program which will be able to run through all the possible combinations of cards dealt out and use some counters to calculate different probabilities at different stages. Since that is a lot of data I think I have to store it in some kind of database or spreadsheet type thing? Then I wanted to write a simple user interface so I could use my mouse to make selections of cards that I am dealt and that come on the flop and how many opponents and have the program find the calculated information and display it on the screen. I am wondering if I learn to use Python will I be able to write something like this? My friend studied some C in college so I thought I'd learn C++, turns out it is a very complicated language so I thought maybe I should try something else before I commit more time to the language. Thank you very much in advance From tleeuwenburg at gmail.com Wed Feb 7 19:59:14 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 7 Feb 2007 16:59:14 -0800 Subject: Running long script in the background In-Reply-To: <1170891733.083400.187620@s48g2000cws.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170891733.083400.187620@s48g2000cws.googlegroups.com> Message-ID: <1170896354.024323.183770@v33g2000cwv.googlegroups.com> On Feb 8, 10:42 am, "Karthik Gurusamy" wrote: > On Feb 6, 5:26 am, "watter... at gmail.com" wrote: > > > Hello, > > > I am trying to write a python cgi that calls a script over ssh, the > > problem is the script takes a very long time to execute so Apache > > makes the CGI time out and I never see any output. The script is set > > to print a progress report to stdout every 3 seconds but I never see > > any output until the child process is killed. > > > Here's what I have in my python script: > > > command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % > > (host, domuname) > > output = os.popen(command) > > Apart from other buffering issues, it could be very well that ssh > returns all the output in one single big chunk. Try running the ssh > command (with the trailing 'command') from your shell and see if it > generates output immediately. > > There may be some option to make ssh not buffer the data it reads from > the remove command execution. If there is no such option, most likely > you are out of luck. In this case, even if you making your remote > script unbufferred, ssh may be buffering it. > > If both the machines have any shared filesystem, you can do a trick. > Make your script write it's output unbuffered to a file. Since the > file is mounted and available on both the machines.. start reading the > file from this main python script (note that you may need a thread to > do it, as your script will anyway be stuck waiting for the ssh to > complete). > > Karthik > > > for line in output: > > print line.strip() > > > Here's a copy of the bash script. > > >http://watters.ws/script.txt > > > I also tried using os.spawnv to run ssh in the background and nothing > > happens. > > > Does anybody know a way to make output show in real time? You could also try flushing the buffer after each status message From skyofdreams at gmail.com Fri Feb 2 07:07:30 2007 From: skyofdreams at gmail.com (skyofdreams) Date: Fri, 2 Feb 2007 20:07:30 +0800 Subject: Interpreter window References: <1170417263.849798.151010@k78g2000cwa.googlegroups.com> Message-ID: "Nils Overas Bergen" 1170417263.849798.151010 at k78g2000cwa.googlegroups.com... >I have created a Python application in Windows XP which uses > WxWidgets. When I start the application from the Python interpreter I > get one empty interpreter window in addition to the application > window. Is there a way to close the interpreter window without closing > the application? Or, can I start the interpreter and the application > script without starting the interpreter window? > do you mean console window? you can try pythonw.exe instead of python.exe -sods From CRhode at LacusVeris.com Thu Feb 15 17:51:48 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Thu, 15 Feb 2007 16:51:48 -0600 Subject: Automated resizing of JPEG image + making slices? References: Message-ID: Michiel Sikma wrote this on Thu, 15 Feb 2007 22:21:34 +0100. My reply is below. -snip- > I initially hired someone to do it in PHP (don't bite, please :-) > but it seems that I forgot about one thing: the people updating the > site would have been able to upload a huge 30 MB JPEG image, which > PHP would then resize to various sizes and cut them into 200x200 > pieces, which would be fed to the Google Maps API. However, this > costs a lot of memory, and PHP by default only has 8 MB. -snip- > I know some Python (but not much since I've never actually written > that many things in it), and with some effort I could probably make > a simple image manipulator frontend in it, but only if I can find a > good library for doing the actual manipulation. Do any of you know > such libraries? I can't make head or tail of your project's constraints, so the following advice probably isn't worth much. IMHO, slicing and dicing is best done by stand-alone, special-purpose, image-manipulation routines that do their own I/O. Here is a library of such routines: o http://netpbm.sourceforge.net/doc/directory.html These can be chained together (piped) in shell script (or in *python* if you prefer) if they're installed on your server. There is an API (and maybe even a *python* interface), but I've never needed it. For security, the parameters passed to these routines from the wild (such as file names) need to be scrubbed clean of any delimiters that would look like executable shell script code, variable substitutions, or even spurious path names. -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 18? ? Wind WNW 13 mph From mccredie at gmail.com Wed Feb 14 19:05:37 2007 From: mccredie at gmail.com (Matimus) Date: 14 Feb 2007 16:05:37 -0800 Subject: output to console and to multiple files In-Reply-To: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> Message-ID: <1171497937.318085.43070@h3g2000cwc.googlegroups.com> I took a look around and I couldn't find anything either. I will be keeping an eye on this thread to see if someone posts a more standard solution. In the mean time though, I will offer up a potential solution. Duck typing is your friend. If you are only using the write method of your files, it can be pretty simple to implement a fake file object to do what you want. [code] import sys class TeeFile(object): def __init__(self,*files): self.files = files def write(self,txt): for fp in self.files: fp.write(txt) if __name__ == "__main__": outf = file("log.out","w") errf = file("log.err","w") allf = file("log.txt","w") sys.stdout = TeeFile(sys.__stdout__,outf,allf) sys.stderr = TeeFile(sys.__stderr__,errf,allf) print "hello world this is stdout" print >> sys.stderr , "hello world this is stderr" [/code] From mail at microcorp.co.za Sat Feb 17 03:47:16 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 17 Feb 2007 10:47:16 +0200 Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <026801c7527c$bdd7b040$03000080@hendrik> "exhuma.twn" wrote: > Hi all, > > Supposing you have two separate processes running on the same box, > what approach would you suggest to communicate between those two > processes. 8< ------ sockets,webservices,CORBA,shared memory --------------- > Supposing both processes are written in Python, is there any other way > to achieve this? To me, shared memory sound the most suited approach. > But as said, I am still fuzzy in this area. Where can I find more > information on this subject? Using named pipes works for me Also look at Pyro, albeit not aimed at being in the same box. - Hendrik From tiedon_jano at hotmail.com Tue Feb 20 10:24:44 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 20 Feb 2007 15:24:44 GMT Subject: Sorting directory contents In-Reply-To: References: Message-ID: <0pECh.227$ll5.6@read3.inet.fi> Wolfgang Draxinger kirjoitti: > Jussi Salmela wrote: > >> I'm not claiming the following to be more elegant, but I would >> do it like this (not tested!): >> >> src_file_paths = dict() >> prefix = sourcedir + os.sep >> for fname in os.listdir(sourcedir): >> if match_fname_pattern(fname): >> fpath = prefix + fname >> src_file_paths[os.stat(fpath).st_mtime] = fpath >> for ftime in src_file_paths.keys().sort(): >> read_and_concatenate(src_file_paths[ftime]) > > Well, both versions, mine and yours won't work as it was written > down, as they neglegt the fact, that different files can have > the same st_mtime and that .sort() doesn't return a > sorted list. > > However this code works (tested) and behaves just like listdir, > only that it sorts files chronologically, then alphabetically. > > def listdir_chrono(dirpath): > import os > files_dict = dict() > for fname in os.listdir(dirpath): > mtime = os.stat(dirpath+os.sep+fname).st_mtime > if not mtime in files_dict: > files_dict[mtime] = list() > files_dict[mtime].append(fname) > > mtimes = files_dict.keys() > mtimes.sort() > filenames = list() > for mtime in mtimes: > fnames = files_dict[mtime] > fnames.sort() > for fname in fnames: > filenames.append(fname) > return filenames > > Wolfgang Draxinger More elegant or not ... I did it MY WAYYYY!!! (and tested this time really carefully;)): #------------------------------- def listdir_chrono_2(dirpath): import os files_dict = {} prefix = dirpath + os.sep for fname in os.listdir(dirpath): mtime = os.stat(prefix + fname).st_mtime files_dict.setdefault(mtime, []).append(fname) mtimes = sorted(files_dict.keys()) filenames = [] for mtime in mtimes: filenames += sorted(files_dict[mtime]) return filenames firstLst = listdir_chrono('.') secondLst = listdir_chrono_2('.') if firstLst == secondLst: print 'OK' else: print 'ERROR!!!' #------------------------------- I keep taking the "dirpath + os.sep" part out of the loop because it is a loop invariant and doesn't have to be inside the loop. Cheer From exarkun at divmod.com Thu Feb 22 10:06:14 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 22 Feb 2007 10:06:14 -0500 Subject: plugin development best practices In-Reply-To: <545o3qF1v23j6U1@mid.uni-berlin.de> Message-ID: <20070222150614.25807.1407070410.divmod.quotient.29649@ohm> On Thu, 22 Feb 2007 15:36:42 +0100, "Diez B. Roggisch" wrote: >> Simple plugin system proposal: >> >> have a package (directory with __init__.py) called plugins where the >> actual plugins are modules in this directory. >> >> When the main script imports the plugins package, all plugin modules >> would be available as plugins.pluginA, plugins.pluginB , etc. >> >> A registry of available plugins would be available as a simple >> dir(plugins). >> >> code in the main script than wished to use a given plugin, would only >> have to look in the registry before calling any code from a given >> plugin. >> >> What is wrong/missing with this simple framework? > >Nothing wrong. Are you sure? exarkun at charm:~$ mkdir someplugins exarkun at charm:~$ touch someplugins/__init__.py exarkun at charm:~$ touch someplugins/a.py exarkun at charm:~$ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import someplugins >>> dir(someplugins) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> Hey, where's my plugin? This most trivial test would have demonstrated the problem with the proposed plugin system. But I suppose it was easier for Flavio to make someone else find the defect in his new system than to either test it himself or to look carefully at any of the existing systems. Jean-Paul From vishal at veriwave.com Sun Feb 11 01:47:01 2007 From: vishal at veriwave.com (Vishal Bhargava) Date: Sat, 10 Feb 2007 22:47:01 -0800 Subject: can't find a way to display and print pdf through python. In-Reply-To: Message-ID: <200702110647.l1B6l22s027328@nsa.veriwave.com> Use Report Lab... Cheers, Vishal -----Original Message----- From: python-list-bounces+vishal=veriwave.com at python.org [mailto:python-list-bounces+vishal=veriwave.com at python.org] On Behalf Of krishnakant Mane Sent: Saturday, February 10, 2007 10:46 PM To: python-list at python.org Subject: can't find a way to display and print pdf through python. hello all, I am stuck with a strange requirement. I need a library that can help me display a pdf file as a report and also want a way to print the same pdf file in a platform independent way. if that's not possible then I at least need the code for useing some library for connecting to acrobat reader and giving the print command on windows and some thing similar on ubuntu linux. the problem is that I want to display reports in my application. the user should be able to view the formatted report on screen and at his choice click the print button on the screen to send it to the printer. I have reportlab installed and that is sufficient to generate pdf reports. but I still can't fine the way to display it directly and print it directly. Please help me. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list From grante at visi.com Tue Feb 20 11:44:55 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 20 Feb 2007 16:44:55 -0000 Subject: Weird result returned from adding floats depending on order I add them References: <12tm3hpom0tkqc7@corp.supernews.com> <1171984944.698061.248220@j27g2000cwj.googlegroups.com> Message-ID: <12tm9c78p2mea0f@corp.supernews.com> On 2007-02-20, John Machin wrote: > On Feb 21, 2:05 am, Grant Edwards wrote: >> On 2007-02-20, joanne matthews (RRes-Roth) wrote: >> >> > I'm getting different results when I add up a list of floats depending >> > on the order that I list the floats. > >> >> Don't use floating point if you expect exact results. > > It's not the floating point that's the problem, it's the radix, in > this case 2, not being able to express n/10 exactly. As the tutorial > points out, radix-10 has problems representing n/3 (and n/7 and ...) > exactly. No matter what radix you choose, you're going to be able to exactly represent 0% of the rational numbers within the range of the representation. Since you have no control over the FP representation (and hence radix), and little control over input values, the only sane thing to do is to write your code under the assumption that FP can't represent any values exactly. > Another take: Don't expect exact results. Which is what I said. :) > If the input is exact to 1 or two decimal places, don't expect > the sum to be exact to 15 or more decimal places. In this case the input values have about 14 significant digits. So does the output. Unfortunately, the algorithm as written requires an infinite number of significant digits. -- Grant Edwards grante Yow! WHOA!! Ken and at Barbie are having TOO visi.com MUCH FUN!! It must be the NEGATIVE IONS!! From garrickp at gmail.com Tue Feb 20 16:29:41 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 20 Feb 2007 13:29:41 -0800 Subject: Regex Speed Message-ID: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> While creating a log parser for fairly large logs, we have run into an issue where the time to process was relatively unacceptable (upwards of 5 minutes for 1-2 million lines of logs). In contrast, using the Linux tool grep would complete the same search in a matter of seconds. The search we used was a regex of 6 elements "or"ed together, with an exclusionary set of ~3 elements. Due to the size of the files, we decided to run these line by line, and due to the need of regex expressions, we could not use more traditional string find methods. We did pre-compile the regular expressions, and attempted tricks such as map to remove as much overhead as possible. With the known limitations of not being able to slurp the entire log file into memory, and the need to use regular expressions, do you have an ideas on how we might speed this up without resorting to system calls (our current "solution")? From gagsl-py at yahoo.com.ar Thu Feb 15 14:14:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 16:14:42 -0300 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded References: <1171305876.030471.59470@s48g2000cws.googlegroups.com> <1171564971.279097.151370@p10g2000cwp.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 15:42:51 -0300, escribi?: > This is what I get: > > 'import site' failed; use -v for traceback > ['c:\\temp\\pytest\\Debug\\python25_d.zip', 'C:\\Python25\\Lib', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', '', 'c:\\temp\\pytest\ > \Debug'] > > In fact, the 'import site' failed; use -v for traceback happens when I > call the Py_Initialize(). > > As can be seen from the output, the import sys; and print sys.path > works. I also added Py_SetProgramName(argv[0]) before calling > PyInitialize() but there was no change. "works" in the sense that it prints something; but sys.path is incomplete, it lacks site-packages and others (they are added by site.py). It appears that you have installed Python on C:\Python25 and you build your application executable into c:\temp\pytest\Debug - is that true? Hmmm, you will need a debug build of Python too, python25_d.lib/.dll. Perhaps at this stage it's easier to use the Release build, because you already have python25.lib/dll. You have to fix the "import site" error. Use the following command on a console window before launching your executable: set PYTHONVERBOSE=1 You'll see a lot of lines showing the initial imports; you should be able to detect what's the problem at "import site"; usually it's trying to load a missing DLL. -- Gabriel Genellina From mbm at mediamonger.ch Mon Feb 26 11:44:05 2007 From: mbm at mediamonger.ch (=?UTF-8?B?TWHDq2wgQmVuamFtaW4gTWV0dGxlcg==?=) Date: Mon, 26 Feb 2007 17:44:05 +0100 Subject: How to delete PyGTK ComboBox entries? In-Reply-To: <1172504000.3601.13.camel@localhost> References: <1172504000.3601.13.camel@localhost> Message-ID: <45E30E55.1080508@mediamonger.ch> Hej! > > > > model = combo_box.get_model() > > combo_box.set_model(None) > > model.clear() > > for entry in desired_entries: > > model.append([entry]) > > combo_box.set_model(model) > > > > model.append is essentially the same as combo_box.append_text. Setting > > the model to None before making changes to it speeds things at least in > > the case of tree views. I'm not sure if it does much with combo boxes. > > If you experince speed issues with combo boxes you're either doing > > something very wrong or you have so many entries that you ought to be > > using a tree view instead. > > Works like a charm. Thanks a lot! From franz.steinhaeusler at gmx.at Tue Feb 6 04:06:38 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 06 Feb 2007 10:06:38 +0100 Subject: Python compiled on Windows References: Message-ID: On 6 Feb 2007 08:35:08 GMT, Duncan Booth wrote: >Franz Steinhaeusler wrote: > >> @Duncan: Yes, you are not wrong! :) >> But this is not really open source in my opinion. >> Ok there is the VC++ toolkit for download. > >Which I agree totally is a real pain finding the right versions to >download. > >> >> I'm just curious, if there ever had compiled on windows using >> that toolkit or even with gcc, and with gcc, whether there are >> problems or/and differences in speed and run time behaviour. >> > >Yes, people have compiled Python with gcc on windows. I believe it is >slightly slower than the standard release, but I would guess that may >depend on the exact versions of gcc/msc you choose to compare, and the >exact compiler options you choose (or I may even be imagining it >entirely). I cannot imagine, that there is a decisive difference, especially as in gcc, you have also a couple of options. > >As I understand it, you can use Mingw to compile extension modules which >are compatible with the standard release of Python, and of course there >is always cygwin. > >But I still don't understand what difference it makes to anyone between: > >an application (could be open or closed source) running on an open >source language (Python) compiled with a closed source compiler on a >closed source OS. > >versus > >an application (could be open or closed source) running on an open >source language (Python) compiled with an open source compiler on a >closed source OS. For me it's more a issue of "principle". :) Ok, the OS is as it is, but the "layer" is more open. If there would be no toolkit, you have to buy (and many have bought Visual Studio) for open source projects, and that is the point, where I cannot make friend with me. > >at the end of the day you still have a mix of open and closed source >components. If it makes you feel better to be using an open source >compiler that's fine, but it doesn't really do anything for me. Ok, I let your opinion, it is also fine with me! :) From __peter__ at web.de Fri Feb 16 17:21:36 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Feb 2007 23:21:36 +0100 Subject: help with looping, re.search, multiple indexing References: Message-ID: Lance Hoffmeyer wrote: > How do I add another index inside a re.search? > > I want to add > for j in [96,97,98,99] > BASE = re.search ... > sh.Cells97... > for i .... > > so that the Table 96 within the re.search(s) becomes Table 96, Table 97, > Table 98, Table 99 but don't know how to add a second index within the > re.search since I already have %char in match = re.search ... " %char, > neuro ... You can make format strings with an arbitrary number of values by providing a tuple r"Table %d.*?%s.*?\n.*?\d(.*?)\n.*?" % (j, char) or a dict r"Table %(table)d.*?%(char)s.*?\n.*?\d(.*?)\n.*?" % dict(table=j, char=char) on the right side of the % operator. http://docs.python.org/lib/typesseq-strings.html Peter From JoostMoesker at gmail.com Sun Feb 4 07:53:22 2007 From: JoostMoesker at gmail.com (Joost) Date: 4 Feb 2007 04:53:22 -0800 Subject: stlib name clash when using python as ASP language In-Reply-To: References: <1170323389.184681.250640@v45g2000cwv.googlegroups.com> Message-ID: <1170593602.308391.225180@a34g2000cwb.googlegroups.com> > You *assume* that [0] is the IIS path, but perhaps some other imported > module changed sys.path too, and now it's not the first one anymore. > If you know exactly the path, try sys.path.remove(iis_path). > > -- > Gabriel Genellina It's was a hack and definitely not meant to go in to production ;) Since gzip.py lives in python24\lib I thought setting sys.path[0] to python24\lib would load this load this module, no matter what. However, in some magically way the sys.path gets modified during the request by IIS. Maybe IIS resets the global sys.path per new request, causing sporadic problems when request are handled concurrently? I just don't know. The iis/inetsrv path is included in sys.path for a reason and I don't want to fiddle around with sys.path to create problems in other parts of the code. I was wandering if there is some way to prevent a name clashes by using a custom importer or something like that. From sjmachin at lexicon.net Sat Feb 3 17:36:28 2007 From: sjmachin at lexicon.net (John Machin) Date: 3 Feb 2007 14:36:28 -0800 Subject: confused about resizing array in Python In-Reply-To: References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: <1170542188.773890.295280@a75g2000cwd.googlegroups.com> On Feb 4, 7:41 am, "Ruan" wrote: > Then how about Python's list? > > What is done exactly when list.append is executed? > > For list, is there another larger list initialized and the contents from the > old list is copied to it together with the new appended list? > Qi ren you tian :-) Llike with dictionaries, some spare space is left each time the list is expanded, so over-all the amortised cost is O(n). HTH, John From jstroud at mbi.ucla.edu Fri Feb 9 00:38:25 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 08 Feb 2007 21:38:25 -0800 Subject: Is Python for me? In-Reply-To: References: Message-ID: jiddu wrote: > Hi, > > I'm planning to create a poker calculator, I learned some basic in > highschool years ago and I was told for beginners Python is a good > language to start. > > What I wanted to do is to first write a program which will be able to run > through all the possible combinations of cards dealt out and use some > counters to calculate different probabilities at different stages. Since > that is a lot of data I think I have to store it in some kind of database > or spreadsheet type thing? > > Then I wanted to write a simple user interface so I could use my mouse to > make selections of cards that I am dealt and that come on the flop and how > many opponents and have the program find the calculated information and > display it on the screen. > > I am wondering if I learn to use Python will I be able to write something > like this? My friend studied some C in college so I thought I'd learn C++, > turns out it is a very complicated language so I thought maybe I should try > something else before I commit more time to the language. > > Thank you very much in advance > Yes, use python, you will get the most return on your learning effort, though some learning is required. Start at python.org -> docs -> tutorial. James From claudio.grondi at freenet.de Mon Feb 5 09:39:58 2007 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 05 Feb 2007 15:39:58 +0100 Subject: C parsing fun In-Reply-To: <1170683733.434435.171350@j27g2000cwj.googlegroups.com> References: <1170679394.034112.79790@m58g2000cwm.googlegroups.com> <1170679559.272656.145660@v33g2000cwv.googlegroups.com> <1170683733.434435.171350@j27g2000cwj.googlegroups.com> Message-ID: K?roly Kiripolszky wrote: > You're right, thank you for the comment! I will look after how to > avoid this. And after you have resolved this 'small' ;-) detail you will probably notice, that some full functional and in wide use being parser have still trouble with this ... Claudio > > Marc 'BlackJack' Rintsch ?rta: >> In <1170679559.272656.145660 at v33g2000cwv.googlegroups.com>, >> karoly.kiripolszky wrote: >> >>> and the great thing is that the algorithm can be used with any >>> language that structures the code with brackets, like PHP and many >>> others. >> But it fails if brackets appear in comments or literal strings. >> >> Ciao, >> Marc 'BlackJack' Rintsch > From jeff at jmcneil.net Thu Feb 22 22:59:31 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 22 Feb 2007 22:59:31 -0500 Subject: CherryPy/Turbogears on server not controlled by me In-Reply-To: <45DE57A7.7000607@bryant.edu> References: <45DAF7F0.1080503@bryant.edu> <32822fe60702211458u15b0e9a6r6217d8b55c0260f5@mail.gmail.com> <45DE57A7.7000607@bryant.edu> Message-ID: <9EC8ED90-B07A-4820-89F4-C94A6D726F88@jmcneil.net> Can you use mod_rewrite and include a proxy back to a different port? Assuming mod_proxy has been enabled, run your app server on port 8080 and then do something like this in a .htaccess file: RewriteEngine on RewriteRule ^/(.*)$ http://localhost:8080/$1 [P] This of course assumes you want to proxy *all* traffic back. I believe the [P] flag is fully supported in a per-directory configuration context. -Jeff On Feb 22, 2007, at 9:55 PM, Brian Blais wrote: > Jorge Vargas wrote: >> On 2/20/07, Brian Blais wrote: >>> I was wondering if there is a way to run CherryPy/Turbogears on a >>> server that I don't >>> have root access to. >> >> I have never run ANY webapp as root. you should follow that >> advice. in >> fact don't run any server as root. >> > > Oh, I didn't mean to imply that! But, at the same time, I can't > update the apache > server to include python_mod, or apache forwarding to the cherry py > server without > root access. Is there a standard port to use, when you have to > specify the port on > the url? > > > bb > > > -- > ----------------- > > bblais at bryant.edu > http://web.bryant.edu/~bblais > > -- > http://mail.python.org/mailman/listinfo/python-list From bignose+hates-spam at benfinney.id.au Mon Feb 12 19:56:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 13 Feb 2007 11:56:26 +1100 Subject: Vim scripting with python References: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Message-ID: <87slda98p1.fsf@benfinney.id.au> "J. Clifford Dyer" writes: > Which versions of vim is this valid for? I tried ":py print 'Hello'", > and got "E319: Sorry, the command is not available in this version" The ability of Vim to run Python commands is one of many optional features that can be enabled or disabled when the program is built. This allows a Vim program runtime of reasonable size (where "reasonable" is decided by the person building the program); many of the optional features are quite large, and building all of them into the program would be a poor choice. To find out what features are explicitly enabled or disabled in your Vim program, type ':version'. The feature 'python' will be listed as '+python' if enabled, '-python' if disabled. If it's disabled and you want it enabled, you'll need to rebuild Vim with that option enabled; or find someone who's done the same (preferably the same person you got your default Vim from) and install that program. -- \ "If you continue running Windows, your system may become | `\ unstable." -- Microsoft, Windows 95 BSOD message | _o__) | Ben Finney From gosinn at gmail.com Tue Feb 6 03:05:17 2007 From: gosinn at gmail.com (Gosi) Date: 6 Feb 2007 00:05:17 -0800 Subject: Calling J from Python In-Reply-To: <1170731096.976076.173270@h3g2000cwc.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> Message-ID: <1170749117.582426.151770@p10g2000cwp.googlegroups.com> On Feb 6, 3:04 am, "Eric_Dex... at msn.com" wrote: > On Feb 5, 8:48 am, "Gosi" wrote: > > > It is quite easy to call J from Python > > >http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... > > There are a couple of issue that should be adressed. Am I going to > jail if I write a program and then redistribute all the files required > to run the program I write?? J is free for anyone to download and use. If someone is interested in putting you in jail it will not because you distribute J or redistribute the J utilities. > The second is how do I use the j stuff > without learning all that much about j. Just like Python then how much time you spend is uo to you. If you want to be good at it you may have to spend some time. You may also be just a casual user and dip into it now and again. There are lots of Demos, Labs and Help files besides all the utilities. You can freely use the utilities and examples to create your own application. You can write code in conventional style and not spend any time on the advanced functionality. > I am just intrested in > stealing graphics libraries and using what I have already written in > python.. There are a number of graphics examples, utilities and demos you can use in J and combine it with Python. The new grid classes in J are amazingly useful too. I am just starting to learn Python and I find it interesting to combine it with J. I know a few people who are doing so successfully. There are always some nicetise in any language that can be beneficial. Combining them enhances both. http://groups.google.com/group/j-programming http://jsoftware.com/ From buffinator at mymail.com Fri Feb 23 17:16:59 2007 From: buffinator at mymail.com (buffinator) Date: Fri, 23 Feb 2007 23:16:59 +0100 Subject: Having multiple instances of a single application start a single instance of another one Message-ID: <45df6400$0$489$cc7c7865@news.luth.se> I have two applications that should work together, let's call them A and B. The first time A starts, it should open a B process and start communicating with it. All other times an A instance starts it should simply talk with the B that already is open. The problem here is, if I start say 40 A applications at once... how do I check if a B is open "fast enough" so that the other A's (not the first one) won't spawn new B's? Im programming this in windows and am currently using the horrible solution in A if not win32gui.FindWindow(None, "Name of B"): spawn_B_here() This only works well if there is a small time between the A's started first... What would the best solution for my problem be? /buffis From dubrovsky at physics.uq.edu.au Tue Feb 20 19:36:08 2007 From: dubrovsky at physics.uq.edu.au (Alejandro Dubrovsky) Date: Wed, 21 Feb 2007 10:36:08 +1000 Subject: Regex Speed References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> Message-ID: garrickp at gmail.com wrote: > While creating a log parser for fairly large logs, we have run into an > issue where the time to process was relatively unacceptable (upwards > of 5 minutes for 1-2 million lines of logs). In contrast, using the > Linux tool grep would complete the same search in a matter of seconds. > > The search we used was a regex of 6 elements "or"ed together, with an > exclusionary set of ~3 elements. Due to the size of the files, we > decided to run these line by line, and due to the need of regex > expressions, we could not use more traditional string find methods. Just guessing (since I haven't tested this), switching from doing it line by line to big chunks (whatever will fit in memory) at a time would help, but I don't think you can get close to the speed of grep (eg while True: chunk = thefile.read(100000000)) if not len(chunk): break for x in theRE.findall(chunk): ..... ) Function calls in python are expensive. From ah at hatzis.de Thu Feb 8 08:17:34 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Thu, 08 Feb 2007 14:17:34 +0100 Subject: distutils: different names in src and dist/build Message-ID: <45CB22EE.7090301@hatzis.de> Hi, is it possible to have different names between the original package name and that which will be installed? Example: setup.py src/ sdk/ __init__.py startme.py This usually creates a distribution file like sdk-0.6.2.tar.gz, which may create site-packages/ sdk/ But I would like to have a MySDK-0.6.2.tar.gz and in site-packages/ MySDK/ Of course with-out changing the original src package name "sdk" to "MySDK" (which likely would be the easiest way, hum). Any suggestion or link how I can achieve this? Many thanks, Anastasios From liuwensui at gmail.com Wed Feb 28 16:11:23 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Wed, 28 Feb 2007 16:11:23 -0500 Subject: convert many excel files to pdf in batch In-Reply-To: <1172696032.167875.154800@s48g2000cws.googlegroups.com> References: <1172696032.167875.154800@s48g2000cws.googlegroups.com> Message-ID: <1115a2b00702281311v3df41c05se565d1a6a91afb11@mail.gmail.com> Adam, If you could come up with a way without using Adobe writer, it should also work for me. thanks. On 28 Feb 2007 12:53:52 -0800, Adam wrote: > 1. Get PDFCreator > 2. Install > 3. Set as default printer > 4. Have all excel files in same folder > 5. Select all excel files > 6. Right click > 7. Select Print > 8. Save Each PDF to a location > 9. ??? > 10. Profit!!!! > > Never done it with Adobe Writer. I'm a cheapskate. > > Regards, > Adam > > -- > http://mail.python.org/mailman/listinfo/python-list > -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From naima.mans at gmail.com Wed Feb 28 05:23:28 2007 From: naima.mans at gmail.com (naima.mans at gmail.com) Date: 28 Feb 2007 02:23:28 -0800 Subject: spawnl and waitpid In-Reply-To: References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> <1172573530.625901.36420@k78g2000cwa.googlegroups.com> <1172583591.509707.190240@p10g2000cwp.googlegroups.com> <1172600050.794986.47140@m58g2000cwm.googlegroups.com> Message-ID: <1172658208.202787.195510@j27g2000cwj.googlegroups.com> On 27 f?v, 19:32, Thinker wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > naima.m... at gmail.com wrote: > > On 27 f?, 18:54, Thinker wrote: > > hello > > ha ok... > > i tried this one and the browser don't write the message at once... > > I have alos tried with thread and have the same result... :( > > Does child-process terminate it-self in a very short time ? > It can be a race condition, here. > You can try to sleep for a while in child-process to make sure parent > being executed. Parent process may not schedule to run immediately > after spawn. And, you can print some thing before os.spawnl() to make > sure that message can be delivered successfully. > > - -- > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF5Hkp1LDUVnWfY8gRAtDdAKCKy8/ap5VJvZV14nhSCWYfLZdyYACffJ+Y > 0sHMgyaQBmsOMwq/rxEvm1Q= > =qjTU > -----END PGP SIGNATURE----- hello oki, i have test a simple script that only wait... when i tun the script without the server it write on 2 time which is normal: ================================================ Content-Type: text/html wait The main program continues to run in foreground. [[[[(((then after 5 second ))]]]]]]] Fin background Main program waited until background was done. ================================================== BUT when i call it under the server web it write after 5 second all the message in 1 time : =================================================== wait The main program continues to run in foreground. Fin background Main program waited until background was done. =================================================== -----------------------THE SCRIPT --------------------------- import cgitb; cgitb.enable() import os,sys import threading, zipfile,time,Main print "Content-Type: text/html" print print "wait" sys.stdout.flush() class AsyncZip(threading.Thread): def __init__(self, infile): threading.Thread.__init__(self) self.infile = infile def run(self): time.sleep(5.0) print 'Fin background' background = AsyncZip('Main.py') background.start() print 'The main program continues to run in foreground.' sys.stdout.flush() background.join() # Wait for background task to finish print 'Main program waited until background was done.' sys.stdout.flush() --------------------------------------------------------------- From jstroud at mbi.ucla.edu Tue Feb 13 00:24:59 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 12 Feb 2007 21:24:59 -0800 Subject: how to compare... In-Reply-To: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> References: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> Message-ID: jairodsl wrote: > Hello everybody ! > > > I have two list, they are, S1=['A','B','C','D','E'], and > S2=['F','G','H','I','J'], but i have to compare both in this way: > > A vs J > A vs I, B vs J > A vs H, B vs I, C vs J > A vs G, B vs H, C vs I, D vs J > A vs F, B vs G, C vs H, D vs I, E vs J > B vs F, C vs G, D vs H, E vs I > C vs F, D vs G, E vs H > D vs F, E vs G > E vs F > > Perhaps, you should understand better in this way: > > A > J > > A B > I J > > A B C > H I J > > A B C D > G H I J > > A B C D E > F G H I J > > B C D E > F G H I > > C D E > F G H > > D E > F G > > E > F > > Could someone give me any idea how to compare(or print) both list in > this way ??? Thanks a lot !!! > > jDSL > for i in xrange(1, len(S1)+1): print S1[0:i] print S2[-i:] print Am I really the first person to respond to this? From skip at pobox.com Mon Feb 5 11:14:23 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 5 Feb 2007 10:14:23 -0600 Subject: in place-ness of list.append In-Reply-To: References: Message-ID: <17863.22495.86083.614982@montanaro.dyndns.org> as> I'm pretty confident append itself (and a+[n]) are linear in as> N=len(a) ... Yes, as I indicated in an earlier reply. The overall construction of his data structure would be O(N**2) or O(N*log N). The latter is for binary tree construction, but I didn't know what the OP was going to do with his lists at the time I originally replied. as> Or, if you don't need to mutate the tree ``left = (parent, as> 1)``. Tuples ought to have a little less memory overhead. Since at least 2.4, lists overallocate space for new entries proportional to the current size of the list, so yes, tuples will be a bit friendlier, certainly if your tree is very deep. Skip From edreamleo at charter.net Fri Feb 16 09:47:18 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 08:47:18 -0600 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: <%tjBh.6$iV1.2@newsfe06.lga> > It looks your main issue is that you're complaining that Python 3000 is going to break things in a non-backward compatible way. No. My complaint is *only* that changing the meaning of 'print' is needless pain. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From thebrasse at brasse.org Thu Feb 15 17:04:05 2007 From: thebrasse at brasse.org (=?iso-8859-1?B?TWF0dGlhcyBCcuRuZHN0cvZt?=) Date: 15 Feb 2007 14:04:05 -0800 Subject: filecmp.cmp() cache In-Reply-To: References: <1171554885.517477.316470@s48g2000cws.googlegroups.com> Message-ID: <1171577045.892167.46580@p10g2000cwp.googlegroups.com> On Feb 15, 5:56 pm, Peter Otten <__pete... at web.de> wrote: > You can clear the cache with > > filecmp._cache = {} > > as a glance into the filecmp module would have shown. You are right, a quick glance would have enlighten me. Next time I will RTFS first. :-) > If you don't want to use the cache at all (untested): > > class NoCache: > def __setitem__(self, key, value): > pass > def get(self, key): > return None > filecmp._cache = NoCache() > Just one small tought/question. How likely am I to run into trouble because of this? I mean, by setting _cache to another value I'm mucking about in filecmp's implementation details. Is this generally considered OK when dealing with Python's standard library? :.:: mattias From http Sun Feb 11 09:25:34 2007 From: http (Paul Rubin) Date: 11 Feb 2007 06:25:34 -0800 Subject: How to access an absolute address through Python? References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> <1171197574.776135.96980@k78g2000cwa.googlegroups.com> <1171198707.889681.177270@h3g2000cwc.googlegroups.com> Message-ID: <7xy7n4lqjl.fsf@ruckus.brouhaha.com> Steve Holden writes: > > My goal is to sync program with external equipment through a register > > defined as an absolute physical address. I know how to do it from C - > > was curious if it may be done from Python. Can it be done? > > > No. You'd have to use a compiled extension. Well, you don't necessarily have to deal with the C API or ctypes; it may be enough to invoke an external program that accesses the necessary memory address. From boris.smirnov at gmail.com Wed Feb 28 04:26:13 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 28 Feb 2007 01:26:13 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172650071.878083.106290@h3g2000cwc.googlegroups.com> <1172653246.535391.105780@a75g2000cwd.googlegroups.com> Message-ID: <1172654773.047745.83250@8g2000cwh.googlegroups.com> On Feb 28, 10:22 am, Phil Thompson wrote: > On Wednesday 28 February 2007 9:00 am, boris.smir... at gmail.com wrote: > > > > > > > On Feb 28, 9:07 am, boris.smir... at gmail.com wrote: > > > On Feb 28, 8:56 am, Phil Thompson > > > > wrote: > > > > On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > > > > > When your programs stops with the error, it should also be printing a > > > > > stack trace. This is a list of all the functions that have been > > > > > called when Python had the problem. > > > > > > You shouldn't have to do anything extra to get the stack trace. > > > > > The error is raised in Qt and aborts immediately. It never gets back to > > > > Python to generate a trace. > > > > > He needs to produce a short and complete test which demonstrates the > > > > problem, then we can point out where the QPaintDevice is being created. > > > > > Phil > > > > OK, but before I do a complete test, could anybody tell/explain me why > > > the same file is working on Windows? > > > Did anybody already meet with something similar Win vs. Linux? > > > > b. > > > Here is my simple script: > > > import sys > > from qt import * > > class Optimizer(QWidget): > > def __init__(self, parent = 0): > > QWidget.__init__(self) > > QGridLayout(self) > > if __name__ == '__main__': > > a = QApplication (sys.argv) > > mywidget = Optimizer() > > a.exec_loop() > > > This produces this: > > > python qt_script_bs_070228.py > > > QPaintDevice: Must construct a QApplication before a QPaintDevice > > > Any suggestions here? > > It works fine for me. > > > Thanks > > > BTW: One question: > > when I use "import qt" instead of "from qt import *" I get this error: > > Traceback (most recent call last): > > File "mscarideidtool_bs_070228.py", line 4, in ? > > class Optimizer(QWidget): > > NameError: name 'QWidget' is not defined > > > What is the difference between "import qt" and "from qt import *" ? I > > thought that these are the same. > > The first creates a new namespace called "qt" and imports the module's objects > into it. To reference those objects you have to include the namespace name. > > The second imports the module's objects into the current namespace. > > Phil- Hide quoted text - > > - Show quoted text - OK, I have to apologize because I didn't mention that I use python version 2.2.1, could it be the problem here? Bugs or something? I have to use this version since it was delivered with a software that we use here. From ah at hatzis.de Wed Feb 7 13:25:25 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Wed, 07 Feb 2007 19:25:25 +0100 Subject: distutils: renaming setup.py ok? Message-ID: <45CA1995.9060604@hatzis.de> I want to distribute Python site-packages. Is it okay to use other setup file names than setup.py, which is mentioned in any place I read in the doc? E.g., setupMySDK.py, setupMyLib.py It seems that it works with distutils at least - but probably doing so has side-effects with other tools which may expect exactly "setup.py" as file name. Many thanks, Anastasios From Bilgehan.Balban at gmail.com Thu Feb 1 04:12:23 2007 From: Bilgehan.Balban at gmail.com (Bilgehan.Balban at gmail.com) Date: 1 Feb 2007 01:12:23 -0800 Subject: how do I pipe two processes? Message-ID: <1170321143.287492.4300@k78g2000cwa.googlegroups.com> Hi, I want to pipe output of process A to B, and read output of B from python. On Unix if I do the following: child_out, child_in = popen2("program_a | program_b") line = child_out.readline() I get "IOError: bad file descriptor" from Python, and broken pipe error from program_b. How do I do this right? Thanks, Bahadir From researchbase at gmail.com Sun Feb 11 01:45:31 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 11 Feb 2007 12:15:31 +0530 Subject: can't find a way to display and print pdf through python. Message-ID: hello all, I am stuck with a strange requirement. I need a library that can help me display a pdf file as a report and also want a way to print the same pdf file in a platform independent way. if that's not possible then I at least need the code for useing some library for connecting to acrobat reader and giving the print command on windows and some thing similar on ubuntu linux. the problem is that I want to display reports in my application. the user should be able to view the formatted report on screen and at his choice click the print button on the screen to send it to the printer. I have reportlab installed and that is sufficient to generate pdf reports. but I still can't fine the way to display it directly and print it directly. Please help me. Krishnakant. From stj911 at rock.com Sat Feb 3 01:07:13 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 2 Feb 2007 22:07:13 -0800 Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. In-Reply-To: References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> Message-ID: <1170482833.643671.254640@s48g2000cws.googlegroups.com> > >>Can a jet fuel/hydrocarbon fire collapse a steel structure? An > >>experiment. > > > [snip] > > Run your "experiment" again but add some pure oxygen such as was > > escaping from the on-board breathing oxygen tanks on the > > airplanes that were crashed into the WTC. No need to do it. We have the pictures of live humans waving from the gaping holes in the towers where the planes crashed. We have the testimonies of the fire fighters that the fires were not that hot and minor. The fuel of the plane which is mainly in the wings were severed outside the netting and much of them burnt outside in the fireball that is visible in all the videos. Futhermore, the black soot that was visible to the naked eye is indicative of bloody cold flame. Also, the probability of the oxygen tanks oriented in such a way to inject oxygen onto the steel as in a oxygen cutting torch is extremely low. These cylinders have a 1000-3000psi of pressure which makes them into a rocket or an explosive under uncontrolled gas release. And they would not contaminate the molten metal with any sulfur. Either the atmosphere inside was oxidising or reducing. If it was oxidising, how did the sulfur in huge quantities contaminate the molten metal pools? The official lies to explain sulfur is from the plaster wall. But that requires a reducing atmosphere with finely divided and intimately mixed reactants in a calciner where they are continuously rotated and run for several hours. Yet the fires ran not even for an hour before the building collapsed. From gagsl-py at yahoo.com.ar Tue Feb 20 20:00:09 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 Feb 2007 22:00:09 -0300 Subject: question with inspect module References: <1171998273.748507.14070@h3g2000cwc.googlegroups.com> Message-ID: En Tue, 20 Feb 2007 16:04:33 -0300, Tool69 escribi?: > I would like to retrieve all the classes, methods and functions of a > module. > I've used the inspect module for this, but inside a given class > (subclass of some other one), I wanted to retrieve only the methods > I've written, not the inherited one. How can I do ? A more direct approach: [name for name,value in vars(your_class).items() if inspect.isroutine(value)] This gets you normal, static and class methods. inspect.isfunction would return only normal methods, and inspect.ismethoddescriptor static and class methods. -- Gabriel Genellina From maheh_saied at yahoo.com Sun Feb 18 01:44:47 2007 From: maheh_saied at yahoo.com (mahdieh saeed) Date: Sat, 17 Feb 2007 22:44:47 -0800 (PST) Subject: conver string to dictionary Message-ID: <849825.29475.qm@web53614.mail.yahoo.com> Hi I want to convert string to dictionary .what is the best solution for this ? for example string is like this: '{"SalutationID":["primarykey",8388607,0,None],"CompanyID":[0,8388607,0,"index"], "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]}' and I want to convert this string to this dictionary: {"SalutationID":["primarykey",8388607,0,None],"CompanyID":[0,8388607,0,"index"], "SalutationName":["",255,0,None],"isDefault":["tinyint",1,1,None]} please help me what is the best solution(faster solution) for this? thanks regards saeed --------------------------------- 8:00? 8:25? 8:40? Find a flick in no time with theYahoo! Search movie showtime shortcut. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmbkiwi at gmail.com Thu Feb 1 13:04:23 2007 From: dmbkiwi at gmail.com (dumbkiwi) Date: 1 Feb 2007 10:04:23 -0800 Subject: urllib2 hangs "forever" where there is no network interface In-Reply-To: References: <1170315718.860222.160810@k78g2000cwa.googlegroups.com> Message-ID: <1170353063.024553.10060@s48g2000cws.googlegroups.com> On Feb 2, 5:02 am, j... at pobox.com (John J. Lee) wrote: > "dumbkiwi" writes: > > I have written a script that uses the urllib2 module to download web > > pages for parsing. > > > If there is no network interface, urllib2 hangs for a very long time > > before it raises an exception. I have set the socket timeout with > > socket.setdefaulttimeout(), however, where there is no network > > interface, this seems to be ignored - presumably, because without a > > network interface, there is nothing for the socket module to interact > > with. > > > So, can someone point me in the right direction, so that I can catch > > an exception where there is no network interface? > > Are you on Windows or something Unixy? Linux > > Presumably Windows? (Unix systems almost always have at least a > loopback interface) > > John Sorry, I should have been more specific. The network interfaces are up - ie lo and eth1, it's where the wireless connection has dropped out. Is the best solution to test for a wireless connection through / proc before trying to download data? From phil_nospam_schmidt at yahoo.com Sat Feb 3 21:34:31 2007 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 3 Feb 2007 18:34:31 -0800 Subject: Decimating Excel files In-Reply-To: References: Message-ID: <1170556471.579611.37140@v33g2000cwv.googlegroups.com> gonzlobo wrote: > We have a data acquisition program that saves its output to Excel's > .xls format. Unfortunately, the programmer was too stupid to write > files the average user can read. > > I'd like some advice on how to go about: > 1. Reading a large Excel file and chop it into many Excel files (with > only 65535 lines per file) > or > 2. Decimate an Excel file & write... say every other line (user > selectable)... to a new file. Is the file format really native Excel, or is a CSV or TSV file? I've seen apps (one is a data acquisition program, as a matter of fact) that create "Excel" files that are just CSV or TSV files. Try opening the file with a text editor to see if it's plain ASCII text. In any case, if it's a CSV or TSV file, the Python CSV module is your friend. From bdesth.quelquechose at free.quelquepart.fr Fri Feb 16 17:21:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 16 Feb 2007 23:21:22 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> Message-ID: <45d626f5$0$19811$426a74cc@news.free.fr> Stef Mientki a ?crit : > ifti_crazy at yahoo.com wrote: > >> I am VB6 programmer and wants to start new programming language but i >> am unable to deciced. >> >> i have read about Python, Ruby and Visual C++. but i want to go >> through with GUI based programming language like VB.net >> >> so will you please guide me which GUI based language has worth with >> complete OOPS Characteristics > > Although the GUI of Python is not as good as VB, "the GUI of Python" ? What's that ? Python is a *programming language*, not a GUI toolkit. > (although others in this group will definitely have a different opinion), > the beautiful thing about Python is, > that you can easily embed /encapsulate it in VB, > giving you the best of both worlds. Why would one go thru the pain of "embedding" Python in VB (if that's even possible) when Python can directly access the Win32 API and all COM components and have bindings for GUI toolkits like wxWidgets ? From gagsl-py at yahoo.com.ar Thu Feb 15 20:01:44 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 22:01:44 -0300 Subject: Python's freeze.py utility References: <20070215161851.3d6bf2fc@opal.pathscale.com> Message-ID: En Thu, 15 Feb 2007 21:18:51 -0300, Mitko Haralanov escribi?: > OK, this might be a stupid question: for the life of me, I can't find > Python's freeze.py utility in the Python distribution that comes with > FC6. > > Has it been removed from the distribution? Has it been removed from > Python? > > I have FC6's python-2.4.4 rpms installed (python, python-devel, > python-tools, etc) and the script is neither > in /usr/lib/python-2.4/Tools or /usr/lib/python-2.4/Demos I can only say that it's on my Windows source tree, under Python-2.4.2\Tools\freeze (and it is not on the windows binary distribution). -- Gabriel Genellina From usenet1 at ingfamily.net Thu Feb 15 13:42:51 2007 From: usenet1 at ingfamily.net (usenet1 at ingfamily.net) Date: 15 Feb 2007 10:42:51 -0800 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded In-Reply-To: References: <1171305876.030471.59470@s48g2000cws.googlegroups.com> Message-ID: <1171564971.279097.151370@p10g2000cwp.googlegroups.com> On Feb 12, 2:25 pm, "Gabriel Genellina" wrote: > En Mon, 12 Feb 2007 15:44:36 -0300, escribi?: > > > I'm trying to write some "C" code that will run a python script that > > can in turn call some "C" functions. However I'm having a problem > > getting started because although I can run a script from the python > > ide that imports ctypes, when I execute that 'import ctypes' code from > > the "C" code I get the following error: > > > 'import site' failed; use -v for traceback > > You have to fix this first. Probably you can't import anything, not just > ctypes. > Quoting myself from a similar problem: > > Try this: > PyRun_SimpleString("import sys; print sys.path"); > to see where Python expects to find its library (or call the Py_GetPath > function). > You may need to call Py_SetProgramName (before Py_Initialize) so it can > find where the standard library resides. > At least for testing purposes, you can copy your executable into the same > directory where Python is installed. > > -- > Gabriel Genellina This is what I get: 'import site' failed; use -v for traceback ['c:\\temp\\pytest\\Debug\\python25_d.zip', 'C:\\Python25\\Lib', 'C:\ \Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', '', 'c:\\temp\\pytest\ \Debug'] In fact, the 'import site' failed; use -v for traceback happens when I call the Py_Initialize(). As can be seen from the output, the import sys; and print sys.path works. I also added Py_SetProgramName(argv[0]) before calling PyInitialize() but there was no change. Thanks, Steve From jm.suresh at gmail.com Wed Feb 7 00:53:21 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 6 Feb 2007 21:53:21 -0800 Subject: Steiner Tree In-Reply-To: <1170803507.353774.286190@v33g2000cwv.googlegroups.com> References: <1170663061.700803.231460@s48g2000cws.googlegroups.com> <1170803507.353774.286190@v33g2000cwv.googlegroups.com> Message-ID: <1170827601.713880.301020@j27g2000cwj.googlegroups.com> On Feb 7, 4:11 am, bearophileH... at lycos.com wrote: > Suresh: > > > I could find GeoSteiner (http://www.diku.dk/geosteiner/) which is > > implemented as a C program. Anybody know python wrapper for this? > > Anybody tried this program in a python program? > > Once compiled, you may just need to use it with files calling it > through the console with pipes from Python. If that isn't enough, you > can probably write a simple enough wrapper using Pyrex. > If you succed, I may be interested in the result. > > Bye, > bearophile bearophile, Thanks for the response. I could compile the program. I am now doing this with pipes only; but only thing is that, I had to parse the ps output myself, to generate the line segements, which looks ugly and fails in some cases. Did you find any other way to directly get the new line segments and steiner points. import popen2,re def steiner(points): process = popen2.Popen3('/path/rfst |\ /path/prunefst \ | /path/bb') for pt in points: process.tochild.write('%f %f\n' % (pt[0], pt[1])) process.tochild.close() process.wait() BeginPlot=False EndPlot=False lineSegments = [] for line in process.fromchild: if not EndPlot: if BeginPlot: if line == 'EndPlot\n': EndPlot = True else: if not (re.match('^\s.*%', line) \ or re.match('\s*Plot_Terminals', line) \ or re.match('^\s*\(', line)\ ): #print line a,b,c,d,j = line.split() if b == 'T': p1 = points[int(a)] else: p1 = (float(a),float(b)) if d == 'T': p2 = points[int(c)] else: p2 = (float(c), float(d)) if not(p1[0] == p2[0] and p1[1] == p2[1]): lineSegments.append((p1,p2)) else: if line == 'BeginPlot\n': BeginPlot=True return(lineSegments) I want to write the code with pyrex, but the c program looks complicated. Maybe with some help in understanding from you, we can write the wrapper with pyrex. - Suresh From larry.bates at websafe.com Wed Feb 14 14:55:12 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 14 Feb 2007 13:55:12 -0600 Subject: try...except...finally problem in Python 2.5 In-Reply-To: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> Message-ID: redawgts wrote: > I keep getting this error "local variable 'f' referenced before > assignment" in the finally block when I run the following code. > > try: > f = file(self.filename, 'rb') > f.seek(DATA_OFFSET) > self.__data = f.read(DATA_SIZE) > self.isDataLoaded = True > except: > self.isDataLoaded = False > finally: > f.close() > > Can someone tell me what's wrong with the code? Am I doing something > wrong? I'm somewhat new to python but this makes sense to me. > finally: block is executed even if there is an exception in which case f hasn't been defined. What you want is: try: f = file(self.filename, 'rb') f.seek(DATA_OFFSET) self.__data = f.read(DATA_SIZE) self.isDataLoaded = True except: isDataLoaded=False else: f.close() -Larry From gagsl-py at yahoo.com.ar Mon Feb 5 18:46:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:46:55 -0300 Subject: raise or not to raise [Newbie] References: Message-ID: En Sat, 03 Feb 2007 18:07:12 -0300, Jacol escribi?: > I understand that author generated exception and than extracted the name > of > function from the exeption. But is any sens in using exeptions service if > we have smthing simpler: just print for example? In my opinion no, it > doesn't make sens. Notice the posting date... 8 years ago, that was the only way. Now, things are different (thanks Guido and all the folks making Python better each day!) -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Wed Feb 28 16:48:35 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Mar 2007 08:48:35 +1100 Subject: Question about raise and exceptions. References: Message-ID: <871wkax8b0.fsf@benfinney.id.au> "Steven W. Orr" writes: > In my class I have I assume you mean "in my module", since you're showing us several classes. > class TransitionError(Error): > [...] > def __init__(self, previous, next, message): Here you define the arguments that must be passed when creating a TransitionError instance. > Also in my class I check to see if a transition is legal or not: I assume this code is in a different class elsewhere. > if newstate == self.error_state: > raise TransitionError, self.curr_state, newstate, \ > "Going to error state %d from state %d" % (self.curr_state, newstate) Here you specify the *class* TransitionError, instead of creating a new *instance* of TransitionError with the required arguments. This should be, as you specified in the definition of the TransitionError class: raise TransitionError(self.curr_state, newstate, "Badness: %d from %d" % (self.curr_state, newstate) ) The syntax of the 'raise' statement requires one, two, or three arguments, all of which instruct 'raise' what to do, and none of which refer to arguments given to the exception instance. The above statement will supply one argument, an instance to raise as the exception. The other forms of the 'raise' statement are all about what raise should do, so your example above, even if it were not incorrect syntax, is logically incorrect. -- \ "I believe in making the world safe for our children, but not | `\ our children's children, because I don't think children should | _o__) be having sex." -- Jack Handey | Ben Finney From dmbkiwi at gmail.com Thu Feb 1 02:41:59 2007 From: dmbkiwi at gmail.com (dumbkiwi) Date: 31 Jan 2007 23:41:59 -0800 Subject: urllib2 hangs "forever" where there is no network interface Message-ID: <1170315718.860222.160810@k78g2000cwa.googlegroups.com> I have written a script that uses the urllib2 module to download web pages for parsing. If there is no network interface, urllib2 hangs for a very long time before it raises an exception. I have set the socket timeout with socket.setdefaulttimeout(), however, where there is no network interface, this seems to be ignored - presumably, because without a network interface, there is nothing for the socket module to interact with. So, can someone point me in the right direction, so that I can catch an exception where there is no network interface? From silovana.vjeverica at com.gmail Thu Feb 8 14:29:48 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Thu, 8 Feb 2007 20:29:48 +0100 Subject: Functions, parameters References: <45cb6def$0$1014$426a74cc@news.free.fr> <7x4ppwsc5n.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Since split is applied to argname, it retrieves 'question' and 'startswith'. Exactly. :) And, 'questions' and 'startswith' are two string, and not references at Poll.question, or more precisely, instanceOfPoll.question. I suppose this is what I was looking for: __getattribute__(...) x.__getattribute__('name') <==> x.name Tnx guys. -- http://www.nacional.hr/articles/view/23894/23 From steve at holdenweb.com Fri Feb 16 11:32:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 11:32:16 -0500 Subject: Reg Google Web Toolkit and Python In-Reply-To: <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> References: <53lranF1th0pcU1@mid.uni-berlin.de> <20070216151846.30170.qmail@web38713.mail.mud.yahoo.com> Message-ID: <45D5DC90.8090907@holdenweb.com> Shadab Sayani wrote: > Hi , > We have a project where I need to read files store > them in database in the backend.We have done this in > python.Now we decided to use Ajax technique for user > interface.For that we found that GWT is one of the > best toolkits.Now I got a doubt can I interface GWT > with python. > Thanks , > Shadab. > > Send instant messages to your online friends http://uk.messenger.yahoo.com Please note that you should not create a new conversation on a newsgroup by editing a reply to an unrelated post - your comments are now threaded along wiht "Approaches of Interprocess Communication", making them unnecessarily hard to find and somewhat confusingly positioned. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From Bulkan at gmail.com Wed Feb 14 23:54:31 2007 From: Bulkan at gmail.com (placid) Date: 14 Feb 2007 20:54:31 -0800 Subject: Method overloading? Message-ID: <1171515271.811324.218020@s48g2000cws.googlegroups.com> Hi all, Is it possible to be able to do the following in Python? class Test: def __init__(self): pass def puts(self, str): print str def puts(self, str,str2): print str,str2 if __name__ == "__main__": t = Test() t.puts("hi") t.puts("hi","hello") Cheers From Bulkan at gmail.com Thu Feb 15 18:23:18 2007 From: Bulkan at gmail.com (placid) Date: 15 Feb 2007 15:23:18 -0800 Subject: Method overloading? In-Reply-To: References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <1171519115.463977.220700@j27g2000cwj.googlegroups.com> Message-ID: <1171581798.025412.153990@j27g2000cwj.googlegroups.com> On Feb 16, 3:37 am, Neil Cerutti wrote: > On 2007-02-15, Steven D'Aprano wrote: > > >> def multiAccept( argOfVariousTypes ): > >> if isinstance(argOfVariousTypes,int): > >> # treat like an int > >> elif isinstance(argOfVariousTypes,float): > >> # treat like a float > >> elif isinstance(argOfVariousTypes,(list,tuple)): > >> # treat like a container > > > Is that really called "overloading"? I've never (knowingly) > > come across the term being used in that context before. I've > > always known that as "multiple dispatch" or "polymorphism", > > depending on whether you or the compiler handles the > > dispatching. > > It's due to vague terminology that we're using. > > What the OP wanted to know about was static polymorphism of names > based on function signatures, often refered to informally in the > context of C++ as "function overloading", though it's really > "identifier overloading where identifier refers to a function or > member function". This what i was asking. > > What Python provides is dynamic polymorphism of names with > single-dispatch. > > I think. ;-) > > -- > Neil Cerutti Thank you all for the information. From chris.cavalaria at free.fr Wed Feb 14 11:09:53 2007 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 14 Feb 2007 17:09:53 +0100 Subject: How to ping and shutdown a remote computer? In-Reply-To: <1171469222.163242.157040@q2g2000cwa.googlegroups.com> References: <1171469222.163242.157040@q2g2000cwa.googlegroups.com> Message-ID: <45d33458$0$417$426a74cc@news.free.fr> joja15 at gmail.com a ?crit : > I am working on a Python script to perform as a remote computer > manager. So far I have a WOL function working and I would like to add > the ability to show if a machine is on or off (I figured I would do so > by pinging the machine and seeing if I get a response). I would also > like to add the ability to remotely shutdown a computer from the > python script. Does anyone have a code snippet for pinging an IP, a > code snippet for shutting down a remote Windows XP machine, and a code > snippet for sending a HTTP request? > > Here is my current setup: > > - PC running python script > - FreeNAS (media server running on FreeBSD. Can be shutdown from web > interface so I planned on just sending that same web button click from > the python script to shutdown the FreeNAS server) > - Windows XP machine with folder share (What packet is sent over the > network to remotely shutdown a Windows XP machine?) import os os.system("shutdown -s -f") Try other switches if you want. Requires Windows XP at the minimum. From mhellwig at xs4all.nl Wed Feb 7 18:27:47 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 08 Feb 2007 00:27:47 +0100 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: <1170883933.480967.53500@v33g2000cwv.googlegroups.com> References: <1170883933.480967.53500@v33g2000cwv.googlegroups.com> Message-ID: <45ca6033$0$328$e4fe514c@news.xs4all.nl> azrael wrote: > On Feb 7, 3:13 am, "fdu.xia... at gmail.com" > wrote: >> Hi all, >> >> I'm interested in Parallel Python and I learned from the website of >> Parallel Python >> that it can run on SMP and clusters. But can it run on a our muti-CPU >> server ? >> We are running an origin3800 server with 128 CPUs. >> >> Thanks. > > I see you got a problem. me to. how can i get such a little toy for my > own and how much do i have to spend on it. > i also want sometjing like thi. 128 cpu-s, 64 GB rainbowtables, oh my > god. i want this. i am very close to have an orgasm. > Rent it :-) Well you could do at Sara, just google for "sara teras" ;-) -- mph From usable.thought at gmail.com Fri Feb 16 12:15:08 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 09:15:08 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: <1171644713.924096.173940@h3g2000cwc.googlegroups.com> References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> <1171642551.277929.233540@l53g2000cwa.googlegroups.com> <1171644713.924096.173940@h3g2000cwc.googlegroups.com> Message-ID: <1171646108.370697.239170@h3g2000cwc.googlegroups.com> On Feb 16, 11:51 am, "Endless Story" wrote: > On Feb 16, 11:34 am, Steve Holden wrote: > > > It sounds like you may have mistakenly added Cygwin binary directories > > to your Windows path. This isn't normally necessary, since the Cygwin > > shell makes all necessary path adjustments as it starts. Okay - here is from the Cygwin manual available online at http:// cygwin.com/cygwin-ug-net/cygwin-ug-net.html: "The PATH environment variable is used by Cygwin applications as a list of directories to search for executable files to run. This environment variable is converted from Windows format (e.g. C:\WinNT \system32;C:\WinNT) to UNIX format (e.g., /WinNT/system32:/WinNT) when a Cygwin process first starts. Set it so that it contains at least the x:\cygwin\bin directory where "x:\cygwin is the "root" of your cygwin installation if you wish to use cygwin tools outside of bash." From arkanes at gmail.com Mon Feb 5 08:52:17 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 5 Feb 2007 07:52:17 -0600 Subject: wxPython: TextCtrl delayed update when using TE_RICH(2) In-Reply-To: <45c5aa41$0$21142$7a628cd7@news.club-internet.fr> References: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> <45c5aa41$0$21142$7a628cd7@news.club-internet.fr> Message-ID: <4866bea60702050552h71e32f67lffa52fdd34b8b183@mail.gmail.com> On 2/4/07, jean-michel bain-cornu wrote: > Hi, > > def Execute(self, evt): > > print "Start query" > > time.sleep(5) > > > > The "Start query" message should show in the *messages* box when I > > press the button. Instead, it shows only after the time.sleep(5) > > delay. > > > > If I don't use the wx.TE_RICH / wx.TE_RICH2 style on *messages*, the > > text shows before the time.sleep(5) > > For this kind of stuff, I'd try to put "self.out.WriteText(string)" in > some 'Idle' event, which avoid to fall in focus loops or other objects > events management problems not easy to solve. > This doesn't have anything to do with focus loops or otherwise, it's because the OP isn't familiar with event based programming. You're performing a long-running task which is preventing the event loop from processing, so your text isn't updating and your application is unresponsive. You need to rewrite your task - either do everything asynchronously, or use a threaded approach. If you use the thread approach, be sure to not call the updates directly, you can use the wx.CallAfter mechanism to call gui functions in a threadsafe manner. There is a lot of information about this on the wxPython wiki and in the archives of the wxpython-users ML. From kbk at shore.net Thu Feb 22 02:01:39 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 22 Feb 2007 02:01:39 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200702220701.l1M71d59016556@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 408 open ( -9) / 3585 closed (+20) / 3993 total (+11) Bugs : 968 open ( +8) / 6505 closed ( +7) / 7473 total (+15) RFE : 267 open ( +1) / 251 closed ( +0) / 518 total ( +1) New / Reopened Patches ______________________ Handle requests to intern string subtype instances (2007-02-13) http://python.org/sf/1658799 opened by Hrvoje Nik?i? Minor pasting patch (2007-02-13) http://python.org/sf/1659326 opened by Tal Einat Minor AST tweaks (2007-02-13) http://python.org/sf/1659410 opened by Collin Winter functools.compose to chain functions together (2007-02-14) CLOSED http://python.org/sf/1660179 opened by Chris AtLee IDLE doesn't save files on closing (2007-02-15) CLOSED http://python.org/sf/1660202 opened by Toni Hide iteration variable in list comprehensions (2007-02-15) http://python.org/sf/1660500 opened by Nick Coghlan ftplib passive ftp problem on multihomed clients (2007-02-16) http://python.org/sf/1661754 opened by Tim Baum setuptools: avoid sets module for python>2.3 (2007-02-19) http://python.org/sf/1663226 opened by Amit Aronovitch enable "python -m doctest FILE" to run tests in FILE (2007-02-19) http://python.org/sf/1663234 opened by Stefan Behnel Fix for urllib.ftpwrapper.retrfile() and none existing files (2007-02-20) http://python.org/sf/1664522 opened by Phil Knirsch Patches Closed ______________ imputil must respect __path__ for package submodules (2003-02-12) http://python.org/sf/685268 closed by loewis Scalable zipfile extension (2003-09-27) http://python.org/sf/813436 closed by loewis zipfile and big zipped file (2004-07-17) http://python.org/sf/992750 closed by loewis ZipFile - support for file decryption (2003-03-06) http://python.org/sf/698833 closed by loewis Bug 1514451: zipfile "append" mode should create a file ... (2006-07-06) http://python.org/sf/1517891 closed by loewis socketmodule fails to build because missing NETLINK_DNRTMSG (2007-02-11) http://python.org/sf/1657276 closed by loewis gzip.GzipFile has no name attribute (2007-01-29) http://python.org/sf/1647484 closed by gustaebel Missing HCI sockets in bluetooth code from socketmodule (2006-02-15) http://python.org/sf/1432399 closed by loewis Patch to support lots of file descriptors (2006-02-19) http://python.org/sf/1434657 closed by loewis isapi.samples.advanced.py fix (2005-02-17) http://python.org/sf/1126187 closed by loewis Add IEEE Float support to wave.py (2005-02-19) http://python.org/sf/1144504 closed by loewis Make urllib2.OpenerDirector instances pickle-able (2005-02-20) http://python.org/sf/1144636 closed by jjlee functools.compose to chain functions together (2007-02-15) http://python.org/sf/1660179 closed by loewis IDLE doesn't save files on closing (2007-02-15) http://python.org/sf/1660202 closed by gbrandl decorator module (2006-03-12) http://python.org/sf/1448297 closed by gbrandl dictnotes.txt (2006-01-05) http://python.org/sf/1397848 closed by loewis Documentation for new Struct object (2006-05-24) http://python.org/sf/1494140 closed by gbrandl Detect incomplete readline implementation (2006-02-21) http://python.org/sf/1435651 closed by loewis add os.chflags() and os.lchflags() where available (2006-05-17) http://python.org/sf/1490190 closed by loewis Fix for bug #1486663 mutable types check kwargs in tp_new (2006-05-20) http://python.org/sf/1491939 closed by zseil New / Reopened Bugs ___________________ I think, I have found this bug on time.mktime() (2007-02-10) CLOSED http://python.org/sf/1656559 reopened by sergiomb This shouldn't be there: Note that this code that uses... (2007-02-13) CLOSED http://python.org/sf/1658794 opened by Alf Lerv?g os.wait child process fail when under stress (2007-02-13) http://python.org/sf/1658959 opened by The Groff Calling tparm from extension lib fails in Python 2.4 (2007-02-13) http://python.org/sf/1659171 opened by Richard B. Kreckel Calling tparm from extension lib fails in Python 2.4 (2007-02-13) CLOSED http://python.org/sf/1659173 opened by Richard B. Kreckel Python extension problems after re-install (2007-02-14) http://python.org/sf/1659705 opened by elf continuing problem with httplib multiple set-cookie headers (2007-02-14) http://python.org/sf/1660009 opened by David Margrave base64.urlsafe_b64encode() shouldn't use the = character (2007-02-16) http://python.org/sf/1661108 opened by Ryan Barrett Misleading behavior for [] and {} default arguments (2007-02-16) CLOSED http://python.org/sf/1661603 opened by Matthijs finditer stuck in infinite loop (2007-02-16) http://python.org/sf/1661745 opened by Milan [2.5 regression?] failure to import the ORBit extension (2007-02-17) http://python.org/sf/1662529 opened by Matthias Klose the re module can perform poorly: O(2**n) versus O(n**2) (2007-02-17) http://python.org/sf/1662581 opened by Gregory P. Smith Over-zealous keyword-arguments check for built-in set class (2006-05-11) CLOSED http://python.org/sf/1486663 reopened by rhettinger subprocess/popen close_fds perform poor if SC_OPEN_MAX is hi (2007-02-19) http://python.org/sf/1663329 opened by H. von Bargen PyType_IsSubtype segfaults (2007-02-19) http://python.org/sf/1663392 opened by navtej singh crash in exec statement if uncode filename cannot be decoded (2007-02-21) http://python.org/sf/1664966 opened by Stefan Schukat Hangup when using cgitb in a thread while still in import (2007-02-21) http://python.org/sf/1665206 opened by hoffie Documentation missing for OptionGroup class in optparse (2007-02-21) http://python.org/sf/1665333 opened by LunarYorn Bugs Closed ___________ I think, I have found this bug on time.mktime() (2007-02-10) http://python.org/sf/1656559 closed by loewis I think, I have found this bug on time.mktime() (2007-02-10) http://python.org/sf/1656559 closed by loewis zipfile "append" mode should create a file if not present (2006-06-29) http://python.org/sf/1514451 closed by loewis This shouldn't be there: Note that this code that uses... (2007-02-13) http://python.org/sf/1658794 closed by loewis Calling tparm from extension lib fails in Python 2.4 (2007-02-13) http://python.org/sf/1659173 closed by gbrandl Misleading behavior for [] and {} default arguments (2007-02-16) http://python.org/sf/1661603 closed by gbrandl logging formatter %(lineno)d does not work (2007-02-05) http://python.org/sf/1652788 closed by vsajip Over-zealous keyword-arguments check for built-in set class (2006-05-11) http://python.org/sf/1486663 closed by rhettinger Double free/corruption? (2007-02-06) http://python.org/sf/1653121 closed by sf-robot New / Reopened RFE __________________ Datetime enhancements (2007-02-21) http://python.org/sf/1665292 opened by Christian Heimes From jjl at pobox.com Thu Feb 1 11:02:08 2007 From: jjl at pobox.com (John J. Lee) Date: 01 Feb 2007 16:02:08 +0000 Subject: urllib2 hangs "forever" where there is no network interface References: <1170315718.860222.160810@k78g2000cwa.googlegroups.com> Message-ID: "dumbkiwi" writes: > I have written a script that uses the urllib2 module to download web > pages for parsing. > > If there is no network interface, urllib2 hangs for a very long time > before it raises an exception. I have set the socket timeout with > socket.setdefaulttimeout(), however, where there is no network > interface, this seems to be ignored - presumably, because without a > network interface, there is nothing for the socket module to interact > with. > > So, can someone point me in the right direction, so that I can catch > an exception where there is no network interface? Are you on Windows or something Unixy? Presumably Windows? (Unix systems almost always have at least a loopback interface) John From bdesth.quelquechose at free.quelquepart.fr Tue Feb 27 16:10:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Feb 2007 22:10:48 +0100 Subject: difference between string and list In-Reply-To: References: Message-ID: <45e49690$0$1407$426a74cc@news.free.fr> lincoln rutledge a ?crit : > I'm having trouble figuring out the difference between a string and a > list. ['R', 'e', 'a', 'l', 'l', 'y', ' ', '?', ' ', 'S', 'e', 'e', 'm', 's', ' ', 'q', 'u', 'i', 't', 'e', ' ', 'o', 'b', 'v', 'i', 'o', 'u', 's', ' ', 't', 'o', ' ', 'm', 'e', '.'] > I know that: > string = "foo bar" > > is a list of characters No. It's a string. Python doesn't have a "character" type. >, "foo bar", and string[0] is "f". Yes. And ? > while: > > list = ["foo", "bar"] > and list[0] is "foo". So ? > strings have methods like string.count("f") returns 1. What methods do > lists have? Open your interactive Python interpreter and type >>> help(list) > Is it a similar class to string? Not exactly. Both are sequences, that's all. FWIW, try this: "foo"[0] = "b" HTH From skip at pobox.com Fri Feb 2 11:39:57 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 2 Feb 2007 10:39:57 -0600 Subject: asyncore DoS vulnerability In-Reply-To: <1170430334.170669.215150@q2g2000cwa.googlegroups.com> References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> <1170422700.309941.203320@a34g2000cwb.googlegroups.com> <1170430334.170669.215150@q2g2000cwa.googlegroups.com> Message-ID: <17859.26973.898595.251480@montanaro.dyndns.org> billie> asyncore aims to be a framework, right? I think that when billie> select() limit is reached asyncore should just drop other billie> connections. That's all. You're asking asyncore to make a policy decision on behalf the controlling application. It has no idea what that application wants to do when the open file limit is reached. Maybe it should close the oldest connection instead of refusing all new ones. Maybe it should adjust the rate at which it accepts new connections. asyncore doesn't know. Skip From abubakerkiter2003 at yahoo.com Fri Feb 23 10:51:23 2007 From: abubakerkiter2003 at yahoo.com (abubakerkiter2003 at yahoo.com) Date: 23 Feb 2007 07:51:23 -0800 Subject: Apache Cgi (70007)The timeout specified has expired In-Reply-To: <1172245600.565599.225990@p10g2000cwp.googlegroups.com> References: <1172245600.565599.225990@p10g2000cwp.googlegroups.com> Message-ID: <1172245883.664263.207780@t69g2000cwt.googlegroups.com> naima.m... at gmail.com ?????: > Hello, > > When i run my python script, it works a moment and then stop with this > message in the log: > > (70007)The timeout specified has expired: ap_content_length_filter: > apr_bucket_read() failed refers to ...... > > I think my script is too long therefore the server stop it... > > how can i do to run all my python script? > > thanks for your help From cheekymonkey4_u at yahoo.com Sun Feb 18 17:57:19 2007 From: cheekymonkey4_u at yahoo.com (Agent Orange) Date: Sun, 18 Feb 2007 22:57:19 GMT Subject: Toliet Seat Secrets Message-ID: Toliet Seat - http://projectwiretap.blogspot.com/2007/02/toliet-seat-theater-presents.html Was Down apparently after Operations Hanger 36 unveiled its secret harrier stealth technology Feb, 18. approx 12:00 Thank you for another succesfull airshow says Kernel Clink. A 6 million dollar project amortization over 3 years. . From deets at nospam.web.de Thu Feb 22 08:50:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 14:50:09 +0100 Subject: Local class variables? (mod_python problem) References: Message-ID: <545lchF1vd5s1U2@mid.uni-berlin.de> Rory Campbell-Lange wrote: > We have a set of classes using static methods to retain reference > variables between operations. The problem is that the static variables > are not reset between operations when used through mod_python. > > Although it is possible to reset the class variables between invocations > of the system, this has the potential of 'wiping out' these variables > when another user is using the system. > > Is there a way of getting the equivalent of 'local class variables'? In > other words, a way of making 'print a' and 'print b' below provide the > same output? It's very unclear what you mean here, and I'm additionally under the impression that you are deep in the murky waters of accidential concurrent access errors here. I suggest you explain better what these variables are supposed to contain, for whom, and for how long, and then we might suggest a better solution. Diez From silovana.vjeverica at com.gmail Tue Feb 6 13:29:59 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Tue, 6 Feb 2007 19:29:59 +0100 Subject: Module problem References: <1170784450.372250.17760@s48g2000cws.googlegroups.com> Message-ID: Matimus wrote: > Do you have more than one version of Python installed? Is > win32clipboard installed for both versions? It could be that the Yup, that was the problem. Thanx! -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" From yinglcs at gmail.com Mon Feb 26 23:53:07 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 26 Feb 2007 20:53:07 -0800 Subject: How to use cmp() function to compare 2 files? In-Reply-To: <1172550136.069527.103600@t69g2000cwt.googlegroups.com> References: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> <1172550136.069527.103600@t69g2000cwt.googlegroups.com> Message-ID: <1172551987.182502.94000@p10g2000cwp.googlegroups.com> On Feb 26, 10:22 pm, "Dan Bishop" wrote: > On Feb 26, 10:09 pm, "ying... at gmail.com" wrote: > > > > > Hi, > > > i have 2 files which are different (1 line difference): > > $ diff groupresult20070226190027.xml groupresult20070226190027-2.xml > > 5c5 > > < x:22 y:516 w:740 h:120 area: > > --- > > > > x:22 y:516 w:740 h:1202 area: > > > But when I use the cmp() function to compare 2 files, it return "1", > > > $ python Python 2.4.3 (#1, Oct 23 2006, 14:19:47) > > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information.>>> cmp("groupresult20070226190027.xml", "groupresult20070226190027-2.xml") > > > 1 > > > Can you please tell me why? > > Because '.' > '-' (character 25 of each string). > > But this is comparing the filenames, which isn't what you want to do. > > > And how can I compare the content of 2 > > files in python? > > Use the difflib module. Thanks, but from here: http://doc.astro-wise.org/difflib.html it said it is just for comparing 2 sequence of strings, not files. How can I use that to compare content of 2 files? From davihigh at gmail.com Sat Feb 3 23:03:14 2007 From: davihigh at gmail.com (davihigh at gmail.com) Date: 3 Feb 2007 20:03:14 -0800 Subject: MozillaCookieJar doesn't work as expect Message-ID: <1170561794.381152.185290@v33g2000cwv.googlegroups.com> OS: WinXP, Python 2.4 latest version I found it doesn't actually load cookies from the exist cookies.txt. Instead, it generate a new one when visit that url. Who can help me check what's problem in following code? Many thanks in advance! cj = cookielib.MozillaCookieJar() cj.load("d:\\temp\\cookies.txt") # I want to use existing cookie value, not new generated opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) # then, user page r = urllib2.urlopen("http://xxxxx_page_that_need_loaded_cookie") results = r.read() open('user.html', 'w').write(results) # save cookies to file cj.save("./cookies") # with saved cookies, it is NOT the load one From jimhill at swcp.com Mon Feb 12 13:27:06 2007 From: jimhill at swcp.com (Jim Hill) Date: Mon, 12 Feb 2007 18:27:06 +0000 (UTC) Subject: Embedding, "import site", PYTHONHOME, and an old, old issue References: Message-ID: Gabriel Genellina wrote: >En Sat, 10 Feb 2007 03:57:05 -0300, Jim Hill escribi?: > >> int routine() { >> Py_Initialize(); >> ... >> } > >(Why routine() and not main()? Unfortunately you can't repeteadly >initialize/finalize the interpreter, you must do that only once.) This is a small routine tucked off to the side of a fairly large mostly-FORTRAN-with-some-C program. I need to parse a slash-delimited input file from a different program and fill up some arrays with the results. Rather than wrestle with FORTRAN's wretched file I/O I thought I'd do it this way. >Try this: >PyRun_SimpleString("import sys; print sys.path"); >to see where Python expects to find its library (or call the Py_GetPath >function). It returned a list of paths nearly identical to what the interactive interpreter does -- it's on a different machine and too long to retype here -- the interactive sys.path has an empty string as item 0, while the embedded sys.path returns the interactive[1:n]. >You may need to call Py_SetProgramName (before Py_Initialize) so it can >find where the standard library resides. Didn't do anything, alas. >At least for testing purposes, you can copy your executable into the same >directory where Python is installed. No can do -- it's not my machine and I don't have appropriate privileges. Thanks for trying to help me out but I'm on a crash deadline and it looks like I'll be doing some C parsing. Blech. Jim -- It's not "pretexting", it's "lying." From pavlovevidence at gmail.com Thu Feb 1 10:06:40 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 1 Feb 2007 07:06:40 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170308413.750283.80070@j27g2000cwj.googlegroups.com> References: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> <1170271023.955808.314010@q2g2000cwa.googlegroups.com> <1170275061.786779.74910@a34g2000cwb.googlegroups.com> <1170308413.750283.80070@j27g2000cwj.googlegroups.com> Message-ID: <1170342400.585693.282040@l53g2000cwa.googlegroups.com> On Feb 1, 12:40 am, "Michele Simionato" wrote: > On Jan 31, 9:24 pm, "Carl Banks" wrote: > > > Well, of all the things you can use threads for, this is probably the > > simplest, so I don't see any reason to prefer asynchronous method > > unless you're used to it. > > Well, actually there is a reason why I prefer the asynchronous > approach even for the simplest things: > I can stop my program at any time with CTRL-C. When developing a > threaded program, or I implement a > mechanism for stopping the threads (which should be safe enough to > survive the bugs introduced > while I develop, BTW), or I have to resort to kill -9, and I *hate* > that. Especially since kill -9 does not > honor try .. finally statements. > In short, I prefer to avoid threads, *especially* for the simplest > things. > I use threads only when I am forced to, typically when I am using a > multithreaded framework > interacting with a database. Fair enough. I'm just saying that just because something is good for funded, important, enterprise tasks, it doesn't mean very simple stuff automatically has to use it as well. For Pete's sake, even Perl works for simple scripts. Carl Banks From http Tue Feb 27 18:00:55 2007 From: http (Paul Rubin) Date: 27 Feb 2007 15:00:55 -0800 Subject: Vector, matrix, normalize, rotate. What package? References: <1172616572.045690.17550@k78g2000cwa.googlegroups.com> Message-ID: <7xslcr434o.fsf@ruckus.brouhaha.com> "Mattias Br?ndstr?m" writes: > I'm trying to find what package I should use if I want to: > 1. Create 3d vectors. > 2. Normalize those vectors. > 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in > radians. > 4. Perform matrix multiplication. If this is a math exercise, just use plain python and code it all by hand, there's not much to it. You might also like to read about quaternion multiplication--if you read German, the German Wikipedia article looks more helpful than the English one about that. http://de.wikipedia.org/wiki/Quaternion From nogradi at gmail.com Fri Feb 16 05:54:06 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 16 Feb 2007 11:54:06 +0100 Subject: Approaches of interprocess communication In-Reply-To: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> Message-ID: <5f56302b0702160254i5731f55bgafd1baa85d93dc6c@mail.gmail.com> > Supposing you have two separate processes running on the same box, > what approach would you suggest to communicate between those two > processes. > > Let me list the ones I know of: > > * Sockets > Advantage: Supported per se in nearly every programming language > without even the need to install additional packages > Disadvantage: Lot's of code to write, and it's kind of silly to > communicate via TCP/IP if the processes run on the same machine. > > * Webservices > Advantage: Relatively easy to use, can work across different > languages > Disadvantage: Even more overhead on the TCP/IP side that simple > sockets, as really bulky SOAP messages need to be passed around. > > * CORBA -- similar to webservices but more complicated to code. > > * Shared memory > I don't know much about this subject. > > Supposing both processes are written in Python, is there any other way > to achieve this? To me, shared memory sound the most suited approach. > But as said, I am still fuzzy in this area. Where can I find more > information on this subject? Hi, if your requirements are sufficiently light then pylinda might be an easy-to-use solution: http://www-users.cs.york.ac.uk/~aw/pylinda/ A simple example is here: http://www-users.cs.york.ac.uk/~aw/pylinda/beginner.html HTH, Daniel From gagsl-py at yahoo.com.ar Wed Feb 7 21:21:41 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Feb 2007 23:21:41 -0300 Subject: need help to kill a process References: <1170813580.163486.219190@l53g2000cwa.googlegroups.com> <1170877855.791892.277590@q2g2000cwa.googlegroups.com> Message-ID: En Wed, 07 Feb 2007 16:50:55 -0300, escribi?: >> import subprocess >> child1 = subprocess.Popen(["./TestTool"], cwd="/home") >> child2 = subprocess.Popen(["sh","run.sh","load.xml"], cwd="/usr") >> >> Popen objects have a pid attribute. You don't have to use os.system to >> kill them; use os.kill instead. >> You'll notice that I leave out the final &, because I don't know how to >> start a background process without using the shell. But I think you can >> use: bg [pid], afterwards, to get the same result. > > thx for the reply > os.kill worked fine for the first process.. for the second one the > kill managed to kill the shell but the application is still running.. Don't use the shell, if possible, and replace whatever run.sh does with python code. -- Gabriel Genellina From gert.cuykens at gmail.com Wed Feb 28 18:51:46 2007 From: gert.cuykens at gmail.com (gert) Date: 28 Feb 2007 15:51:46 -0800 Subject: urlDecode() Message-ID: <1172706706.152350.56390@z35g2000cwz.googlegroups.com> Anybody can tell me what i need to import to make urlDecode() work in python2.5 please. import urllib urllib.urlDecode(post) #doesn't exist urllib.urldecode(post) #doesn't exist urldecode(post) #doesn't exist urlDecode(post) #doesn't exist From deets at nospam.web.de Wed Feb 21 10:24:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 Feb 2007 16:24:11 +0100 Subject: Tkinter checkbuttons and variables In-Reply-To: References: Message-ID: <5436heF1v7b6dU1@mid.uni-berlin.de> Gigs_ schrieb: > from Tkinter import * > > states = [] > > def onpress(i): > states[i] = not states[i] > > > root = Tk() > for i in range(10): > chk = Checkbutton(root, text= str(i), command=lambda i=i: onpress(i)) > chk.pack(side=LEFT) > states.append(0) > root.mainloop() > print states > > after exiting i get everything like it suppose to but when i put command > like this: > command=lambda: onpress(i) > i got only last checkbutton check. > > Why i have to pass this default argument? Because python creates a closure around the lambda that allows expressions inside the lambda to access surrounding variables. However, these variables are looked up at _runtime_, when the command is actually executed. Naturally, the value of i then is 9, because that's what it has been assigned in the last loop iteration. Diez From tech-hr at smartcharter.com Tue Feb 27 01:46:02 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Mon, 26 Feb 2007 22:46:02 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> <45e33052$0$27235$742ec2ed@news.sonic.net> Message-ID: In article <45e33052$0$27235$742ec2ed at news.sonic.net>, Ray Dillinger wrote: > Tech HR wrote: > > > But we're a very young company (barely six months old at this point) so > > we're willing to listen to most anything at this point. (We're using > > Darcs for revision control. Haskell, anyone?) > > Tell us, where you would expect an applicant for one or more of these > jobs to live if they accepted a job with your firm? It's not at all > apparent from your website or job descriptions where the worksite is > physically located. We are in the Los Angeles area. (We've added a note at the bottom of the jobs page on our web site.) I can't be more specific at this time because we are in the process of finding permanent office space. Our temporary offices are in Santa Monica. We're hoping to find space near the Van Nuys airport, but the commercial real estate market here is very tight right now. From mmanns at gmx.de Fri Feb 23 12:38:54 2007 From: mmanns at gmx.de (Martin Manns) Date: Fri, 23 Feb 2007 12:38:54 -0500 Subject: Rational numbers / alternatives to mxNumber References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> Message-ID: <20070223123854.09149ced@localhost> On Fri, 23 Feb 2007 11:39:11 -0500 Martin Manns wrote: > + boost indeed is a quite nice C++ library. However, I fear that I > would end up writing the python wrappers for operators (+ - * / min > max cmp etc.) myself. I would like to avoid this since these operators > should work correctly for any type (not just int and float) and I have > little experience with verifying such generic code. The problems > encountered in the mxNumber wrapper support this notion. I just saw the pyboost-linux-0.1.1 package and tried it out. ImportError: /home/mn/notes/libboost_python.so.1.34.0: undefined symbol: PyUnicodeUCS4_FromEncodedObject It seems to have problems with UCS2 compiled python. Any robust rational wrapper out there? From __peter__ at web.de Fri Feb 2 12:25:49 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Feb 2007 18:25:49 +0100 Subject: from __future__ import absolute_import ? References: Message-ID: Peter Otten wrote: > If there are two modules 'foo', one at the toplevel and the other inside a > package 'bar', > > from __future__ import absolute_import > import foo > > will import the toplevel module whereas > > import foo > > will import bar.foo. ... provided these imports are performed from modules within 'bar'. Peter From samckain at southslope.net Wed Feb 14 12:30:31 2007 From: samckain at southslope.net (Steve) Date: Wed, 14 Feb 2007 11:30:31 -0600 Subject: list of range of floats References: Message-ID: On Wed, 14 Feb 2007 17:27:06 +0000, Dale Strickland-Clark wrote: > Steve wrote: > >> I'm trying to create a list range of floats and running into problems. >> I've been trying something like: >> >> a = 0.0 >> b = 10.0 >> >> flts = range(a, b) >> >> fltlst.append(flts) >> >> When I run it I get the following DeprecationWarning: integer argument >> expected, got float. How can I store a list of floats? >> >> TIA >> Steve > > range only does ints. If you want floats, you'll have to write your own > version. I was afraid of that. Thanks for the quick reply. Steve From nszabolcs at gmail.com Fri Feb 9 14:01:38 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 9 Feb 2007 11:01:38 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1171047698.558376.160500@v33g2000cwv.googlegroups.com> Srikanth wrote: > Yes, > > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. > > Thanks, > Srikanth try pida http://pida.co.uk/index.php/Main_Page From mbm at mediamonger.ch Mon Feb 26 10:08:56 2007 From: mbm at mediamonger.ch (=?ISO-8859-15?Q?Ma=EBl_Benjamin_Mettler?=) Date: Mon, 26 Feb 2007 16:08:56 +0100 Subject: How to delete PyGTK ComboBox entries? Message-ID: <45E2F808.9080300@mediamonger.ch> Hello list! I need to repopulate PyGTK ComboBox on a regular basis. In order to do so I have to remove all the entries and then add the new ones. I tried to remove all entries like that: def clear_comboboxes(boxreference): try: while True: boxreference.remove_text(0) except: pass And then repopulate by iterating through the list of desired entries and calling ComboBox.append_text(text). It works, but is painfully sloooooooow! Is there a faster way to completely change the entries in a ComboBox, by using an all erase method or overwriting the container object? I haven't found anything with google, as the searches are too ambiguous to yield usable results. Thanks, Ma?l From ask at me Mon Feb 5 23:00:35 2007 From: ask at me (alf) Date: Mon, 05 Feb 2007 22:00:35 -0600 Subject: Dlaczego ten destruktor nie dziala In-Reply-To: <20070204170540.09f393e7.sulsa@gazeta.pl> References: <20070204170503.4dbb1b14.sulsa@gazeta.pl> <20070204170540.09f393e7.sulsa@gazeta.pl> Message-ID: Sulsa wrote: > sorry, wrong group. the group is correct but language wrong, did you find out why the exception pops up From paul at boddie.org.uk Mon Feb 26 09:23:51 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 26 Feb 2007 06:23:51 -0800 Subject: The Python interactive interpreter has no command history In-Reply-To: References: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> Message-ID: <1172499831.364521.297020@t69g2000cwt.googlegroups.com> On 16 Feb, 11:40, Alan Franzoni wrote: > Il Thu, 15 Feb 2007 15:14:00 -0200, Eduardo "EdCrypt" O. Padoan ha scritto: > > > Are you using Ubuntu? The last comes with 2.4.x and 2.5. This only > > occurs on 2.5. This happens when you compile Python with libreadline > > installed, AFAIK. > > I'm on Edgy and command history works well both with 2.4 and 2.5 with my > config. If it's really an Edgy glitch, it must be configuration-related! I guess it depends on how one is building the software. According to the package information [1] libreadline5 is stated as a dependency, so if one uses the Debian tools to make a package from the sources (plus the diffs), one should get complaints about missing dependencies rather than inadvertently getting an installable version of Python with broken command history support. Paul [1] http://packages.ubuntu.com/edgy/python/python2.5 From h.b.furuseth at usit.uio.no Fri Feb 2 09:27:59 2007 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Fri, 02 Feb 2007 15:27:59 +0100 Subject: LDAP/LDIF Parsing References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> <45c26772$0$4272$426a74cc@news.free.fr> <45c339f3$0$432$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: >Hallvard B Furuseth a ?crit : >>> else: >>> # all LDAP attribs are multivalued by default, >>> # even when the schema says they are monovalued >>> if len(data) == 1: >>> return data[0] >>> else: >>> return data[:] >> IMHO, this just complicates the client code since the client needs to >> inserts checks of isinstance(return value, list) all over the place. >> Better to have a separate method which extracts just the first value of >> an attribute, if you want that. > > Most of the times, in a situation such as the one described by the OP, > one knows by advance if a given LDAP attribute will be used as > monovalued or multivalued. Well, this is at least my own experience... But if the attribute is multivalued, you don't know if it will contain just one value or not. If you expect telephoneNumber to be multivalued, but receive just one value '123', for value in foo.telephoneNumber: print value will print 1 2 3 BTW, Cruelemort, remember that attribute names are case-insensitive. If you ask the server to for attribute "cn", it might still return "CN". -- Hallvard From sjmachin at lexicon.net Sun Feb 11 06:21:13 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 03:21:13 -0800 Subject: Regular Expressions In-Reply-To: References: Message-ID: <1171192873.235348.196530@s48g2000cws.googlegroups.com> On Feb 11, 9:25 pm, Steven D'Aprano wrote: > On Sun, 11 Feb 2007 07:05:30 +0000, Steve Holden wrote: > > Geoff Hill wrote: > >> What's the way to go about learning Python's regular expressions? I feel > >> like such an idiot - being so strong in a programming language but knowing > >> nothing about RE. > > > In fact that's a pretty smart stance. > > That's a little harsh -- regexes have their place, together with pointer > arithmetic, bit manipulations, reverse polish notation and goto. The > problem is when people use them inappropriately e.g. using a regex when a > simple string.find will do. Thanks for the tip-off, Steve and Steven. Looks like I'll have to start hiding my 12C (datecode 2214) with its "GTO" button under the loose floor-board whenever I hear a knock at the door ;-) Looks like Agner Fog's gone a million, and there'll be a special place in hell for people who combine regexes with bit manipulation, like Navarro & Raffinot. And we won't even mention Heikki Hy,*7g^54d3j+__= From steve at REMOVEME.cybersource.com.au Thu Feb 1 21:17:49 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 02 Feb 2007 13:17:49 +1100 Subject: Help me with this!!! References: <1170325298.542389.298160@q2g2000cwa.googlegroups.com> <1170337596.369951.12310@m58g2000cwm.googlegroups.com> <1170348835.689256.184420@k78g2000cwa.googlegroups.com> Message-ID: On Thu, 01 Feb 2007 08:53:55 -0800, Ravi Teja wrote: >> > > It search a text inside that hex value. >> > > It works perfecly on a txt file but if I open a binary file (.exe,.bin >> > > ecc...) with the same value it wont work, why? >> > > Please help! >> >> > Because the pattern isn't in the file, perhaps. >> >> This pattern IS in the file (I made it and I double check with an hex >> editor). >> It display the file correcltly (print line) but... > > No! Peter is right. Regular expressions match ASCII representation of > data, not hex. In simple terms, do you see your pattern when you open > the file in notepad (or other text editor)? You do not use regex to > search binary files. I don't see why not. >>> pattern = "NULL\0" >>> source = "\0\01\02-more-bytes-here-NULL\0-more-bytes" >>> m = re.search(pattern, source) >>> m.group() 'NULL\x00' >>> m.span() (20, 25) Here's the Original Poster's code again: regex = re.compile(r"(?si)(\x8B\xF0\x85\xF6)(?P.*) (\xC6\x44\x24)",re.IGNORECASE) file = open(fileName, "rb") for line in file: if (match): print line file.close() I suggest that the reason it doesn't work is because he never actually uses the regex. Presumably the name "match" was assigned somewhere else to a false value, and so the code simply walks through the file doing nothing. -- Steven D'Aprano From vithi99 at hotmail.com Fri Feb 16 21:36:04 2007 From: vithi99 at hotmail.com (vithi) Date: 16 Feb 2007 18:36:04 -0800 Subject: how to use Dispatch to open an application in win32com.client Message-ID: <1171679764.164264.211480@j27g2000cwj.googlegroups.com> Hi' I am trying to launch an application. When I try like that When I try like that Excel is opening import win32com.client object = win32com.client.Dispatch("Excel.Application") object.Visible = 1 But when I try my application which is QeepIt.exe which is in the c:\ drive it is not running Any body tell me how to give path to open an exectable application in Dispatch modules I try like that object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") It give an error. From ishoej at gmail.com Sun Feb 11 17:16:49 2007 From: ishoej at gmail.com (Holger) Date: 11 Feb 2007 14:16:49 -0800 Subject: compound statement from C "?:" In-Reply-To: References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> Message-ID: <1171232208.939808.33890@j27g2000cwj.googlegroups.com> Thanks all for good input. It seems like there's no the-python-way for this one. Currently I'm forced to use cygwin - and python in cygwin is still not 2.5 so I can't use the new inline if-else ternary operator. > >> if n == 1: > >> print "I saw a car" > >> else: > >> print "I saw %d cars" % n Personally I don't like the if-else approach because of the don't- repeat-yourself philosophy > D'accord. Did I mention that, as a "for fun" approach, "s" * (n != 1) is > quite clever :-) > > Peter I like this one :-) > print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) And this one. /Holger From eurleif at ecritters.biz Wed Feb 7 23:07:15 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 07 Feb 2007 23:07:15 -0500 Subject: 'IF' Syntax For Alternative Conditions In-Reply-To: References: Message-ID: <45caa1f4$0$6823$4d3efbfe@news.sover.net> rshepard at nospam.appl-ecosys.com wrote: > However, I cannot find, nor create by trial-and-error, the syntax for > alternative conditions that are ORed; e.g., > > if cond1 OR if cond2: > do_something. if cond1 or cond2: do_something() From gagsl-py at yahoo.com.ar Thu Feb 15 10:14:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 12:14:53 -0300 Subject: AUX File Writing Error References: <1171515811.899456.93530@m58g2000cwm.googlegroups.com> <1171521299.082449.67940@s48g2000cws.googlegroups.com> <1171550093.691486.150530@a75g2000cwd.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 11:34:53 -0300, John Machin escribi?: >> > Probably not. AUX, CON, NUL, PRN, LPT, COM1, COM2 etc (with or without >> > an extension) are reserved in Windows for specific devices for >> > compatibility with MS-DOS 1.00 programs, which did that for >> > compatibility with CP/M. >> >> (This is OT now) Do you know why "AUX.csv" is invalid too? I can accept >> that AUX (without extension) is an invalid filename, but it is quite >> different from "AUX.csv" >> > > It is actually a valid file name, but the file is not on disk. I > presume that the OP got an error because it was in 'a' (append) mode > which requires an existing disk file. See below. > > C:\junk>copy con aux.csv > fubar > ^Z > 1 file(s) copied. The above gives me an "Access denied" error; perhaps because AUX is my serial port and it is currently in use. > Why? Who knows? We're talking CP/M, MS-DOS and Windows and you want to > know why? Probably too lazy to distinguish between 'AUX\0', 'AUX.\0' > and 'AUX.XYZ\0' ... probably stopped scanning on reaching the first > invalid character. If you're desperate to find out, dial up your > nearest RCPM and ask the sysop :-) Ahhhh... I think you hit the point, indirectly. On CP/M the filename was not stored as 'AUX\0' - remember, ONLY 8 characters plus 3 for extension, and NO PATH. A FileControlBlock (FCB) had exactly 11 characters reserved for the file name (plus the drive number). So it was actually "AUX " vs "AUX XYZ" and... well, the lazyness argument again. -- Gabriel Genellina From katrin.shafiepour at gmail.com Tue Feb 20 16:53:03 2007 From: katrin.shafiepour at gmail.com (Katrin Shafiepour) Date: Tue, 20 Feb 2007 21:53:03 +0000 Subject: pass variables via url with python? Message-ID: <3f7521780702201353h6b241a20o663893f865138ada@mail.gmail.com> Hi I'm quite new to python and I'm trying to pass variables via url! was wondering if you can help me? ThanQ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Fri Feb 9 12:00:20 2007 From: fumanchu at amor.org (fumanchu) Date: 9 Feb 2007 09:00:20 -0800 Subject: Database Programming with Python In-Reply-To: <1171034880.089616.113380@p10g2000cwp.googlegroups.com> References: <1171034880.089616.113380@p10g2000cwp.googlegroups.com> Message-ID: <1171040420.760665.326290@m58g2000cwm.googlegroups.com> On Feb 9, 7:28 am, Finger.Octo... at gmail.com wrote: > I wanted to connect Python to Ms-Access database using ADO or ODBC. I > have Python 2.5 and on mxODBC site, it has no higher version build > than 2.4. Moreoever, mxODBC is required for ADODB. > Can anyone guide me on this what should I do to make it work on Python > 2.5? I have python 2.5 running on server. You could use Dejavu 1.5, which has its own wrapper [1] for ADO (both MS Access and SQL Server/MSDE). No ODBC necessary or desired. If you want an ADO wrapper without the full Dejavu ORM, it's possible (but not heavily documented) to use dejavu's geniusql layer on its own. That would give you connection mgmt (and pooling), along with the ability to execute arbitrary SQL. Robert Brewer System Architect Amor Ministries fumanchu at amor.org [1] http://projects.amor.org/dejavu/browser/trunk/storage/storeado.py From nospam at nospam.net Mon Feb 19 12:54:26 2007 From: nospam at nospam.net (Andrew) Date: Mon, 19 Feb 2007 09:54:26 -0800 Subject: Raw Imager Message-ID: <12tjp2p98hqq4d4@corp.supernews.com> Im looking at building a tool for previewing raw images as Thumbnails no editing really just viewing in a simple Tkinter GUI however from what I can tell Pil does not support raw images Does anyone have a link to a module that would allow this I guess I would need support for as many different raw types as possible... if possible. Cheers Andrew From tiedon_jano at hotmail.com Tue Feb 20 09:22:22 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 20 Feb 2007 14:22:22 GMT Subject: Sorting directory contents In-Reply-To: References: Message-ID: Wolfgang Draxinger kirjoitti: > H folks, > > I got, hmm not really a problem, more a question of elegance: > > In a current project I have to read in some files in a given > directory in chronological order, so that I can concatenate the > contents in those files into a new one (it's XML and I have to > concatenate some subelements, about 4 levels below the root > element). It all works, but somehow I got the feeling, that my > solution is not as elegant as it could be: > > src_file_paths = dict() > for fname in os.listdir(sourcedir): > fpath = sourcedir+os.sep+fname > if not match_fname_pattern(fname): continue > src_file_paths[os.stat(fpath).st_mtime] = fpath > for ftime in src_file_paths.keys().sort(): > read_and_concatenate(src_file_paths[ftime]) > > of course listdir and sorting could be done in a separate > function, but I wonder if there was a more elegant approach. > > Wolfgang Draxinger I'm not claiming the following to be more elegant, but I would do it like this (not tested!): src_file_paths = dict() prefix = sourcedir + os.sep for fname in os.listdir(sourcedir): if match_fname_pattern(fname): fpath = prefix + fname src_file_paths[os.stat(fpath).st_mtime] = fpath for ftime in src_file_paths.keys().sort(): read_and_concatenate(src_file_paths[ftime]) Cheers, Jussi From paddy3118 at googlemail.com Sun Feb 11 17:08:24 2007 From: paddy3118 at googlemail.com (Paddy) Date: 11 Feb 2007 14:08:24 -0800 Subject: Regexps and lists Message-ID: <1171231704.605194.169960@l53g2000cwa.googlegroups.com> I don't know enough to write an R.E. engine so forgive me if I am being naive. I have had to atch text involving lists in the past. These are usually comma separated words such as "egg,beans,ham,spam,spam" you can match that with: r"(\w+)(,\w+)*" and when you look at the groups you get the following >>> import re >>> re.match(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups() ('egg', ',spam') >>> Notice how you only get the last match as the second groups value. It would be nice if a repeat operator acting on a group turned that group into a sequence returning every match, in order. (or an empty sequence for no matches). The above exaple would become: >>> import re >>> re.newmatch(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups() ('egg', ('beans', 'ham', 'spam', ',spam')) >>> 1, Is it possible? do any other RE engines do this? 2, Should it be added to Python? - Paddy. From tech-hr at smartcharter.com Tue Feb 27 02:43:36 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Mon, 26 Feb 2007 23:43:36 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> <45e33052$0$27235$742ec2ed@news.sonic.net> Message-ID: In article , Tech HR wrote: > In article <45e33052$0$27235$742ec2ed at news.sonic.net>, > Ray Dillinger wrote: > > > Tech HR wrote: > > > > > But we're a very young company (barely six months old at this point) so > > > we're willing to listen to most anything at this point. (We're using > > > Darcs for revision control. Haskell, anyone?) > > > > Tell us, where you would expect an applicant for one or more of these > > jobs to live if they accepted a job with your firm? It's not at all > > apparent from your website or job descriptions where the worksite is > > physically located. > > We are in the Los Angeles area. (We've added a note at the bottom of > the jobs page on our web site.) I can't be more specific at this time > because we are in the process of finding permanent office space. Our > temporary offices are in Santa Monica. We're hoping to find space near > the Van Nuys airport, but the commercial real estate market here is very > tight right now. Actually, it just occurred to me that the company location was also in the subject line of this thread ;-) From rNOSPAMon at flownet.com Thu Feb 1 16:48:01 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 01 Feb 2007 13:48:01 -0800 Subject: Python, readline and OS X Message-ID: I have installed Python 2.5 on my new Intel Mac but I can't for the life of me get readline to work. I have libreadline installed, I've tried copying readline.so from my Python 2.3 installation into 2.5, I've searched the web, and no joy. Could someone please give me a clue? rg From arnodel at googlemail.com Sun Feb 25 07:06:38 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 25 Feb 2007 04:06:38 -0800 Subject: finding out the precision of floats In-Reply-To: <1172402444.935723.192200@m58g2000cwm.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> Message-ID: <1172405198.187516.276310@h3g2000cwc.googlegroups.com> On Feb 25, 11:20 am, "John Machin" wrote: [...] > I'm a little puzzled: > > You don't seem to want a function that will tell you the actual number > of significant decimal digits in a particular number e.g. > > nsig(12300.0) -> 3 > nsig(0.00123400) -> 4 > etc > > You appear to be trying to determine what is the maximum number of > significant decimal digits afforded by the platform's implementation > of Python's float type. Yes you are correct. > Is Python implemented on a platform that > *doesn't* use IEEE 754 64-bit FP as the in-memory format for floats? I had no knowledge of IEEE 754 64-bit FP. The python doc says that floats are implemented using the C 'double' data type but I didn't realise there was a standard for this accross platforms . Thanks for clarifying this. As my question shows I am not versed in floating point arithmetic! Looking at the definition of IEEE 754, the mantissa is made of 53 significant binary digits, which means 53*log10(2) = 15.954589770191003 significant decimal digits (I got 16 with my previous dodgy calculation). Does it mean it is safe to assume that this would hold on any platform? -- Arnaud From larry.bates at websafe.com Mon Feb 12 18:22:59 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Feb 2007 17:22:59 -0600 Subject: Does anyone have the db_row module compiled for python 2.4 on windows? In-Reply-To: <1171321832.028911.45730@k78g2000cwa.googlegroups.com> References: <1171321832.028911.45730@k78g2000cwa.googlegroups.com> Message-ID: vj wrote: > Would really appreciate the binary files for the db_row. > > Thanks, > > VJ > If you don't get an answer you may want to take a look at replacing with SQLObject: http://sqlobject.org/ -Larry From larry.bates at websafe.com Tue Feb 13 11:19:52 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Feb 2007 10:19:52 -0600 Subject: _ssl.pyd is buggy? In-Reply-To: References: Message-ID: Laszlo Nagy wrote: > > Hello, > > I wrote a small program that uses xmlrpc over https. It should work as a > win32 application and as a win32 service too. There is a file called > Processor.py that contains the main thread of the program. It is called > from two files: win32_Application.py and win32_Service.py. The > application works perfectly. The service does not. I can start it from > the services mmc console, but it does not created logfiles, and does > nothing. It cannot be stopped and I have to kill pythonservice.exe. The > event log shows this: > > > Information: The AmazonOfferDownloaderService service has started. > Application error: Faulty application: python.exe, version: 0.0.0.0, > faulty modul: _ssl.pyd, version: 0.0.0.0, memory address: 0x00019b87. > > Is it possible that my _ssl.pyd is faulty? Please help me. > > Python version: 2.4.3 (#69, Mar 29 2006) > Windows version: Windows XP Professional, service pack 2, Hungarian (I > translated the above messages from the event log....) > > Thanks, > > Laszlo > > >>>> Here is the code for the application: > > import thread,threading,time > > from Processor import * > from servicelog import * > from win32_Config import * > > stopped = threading.Event() > stopped.clear() > processor = Processor(stopped) > thread.start_new_thread(processor.Process,()) > logger = getLogger('win32_Application') > logger.info("Staring as application. Please press CTRL+C to stop service.") > while 1: > try: > time.sleep(1) > except: > break > logger.info("Stopping application " + SERVICE_NAME) > stopped.set() > while not processor.stopped.isSet(): > logger.debug("Waiting for the processor to finish...") > time.sleep(1) > > logger.info("Application stopped.") > >>>> Here is the code for the service: > > from win32_Config import * > from Processor import * > from servicelog import * > > import win32serviceutil, win32service > import pywintypes, win32con, winerror > from win32event import * > from win32file import * > from win32pipe import * > from win32api import * > from ntsecuritycon import * > > import traceback > import thread,threading > > class Service(win32serviceutil.ServiceFramework): > _svc_name_ = SERVICE_NAME > _svc_display_name_ = SERVICE_DISPLAY > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.stopped = threading.Event() > self.stopped.clear() > self.logger = getLogger(SERVICE_NAME) > > def SvcStop(self): > self.logger.info("Got SvcStop, trying to stop service...") > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > self.stopped.set() > > def SvcDoRun(self): > """Write an event log record - in debug mode we will also see > this message printed.""" > try: > import servicemanager > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STARTED, > (self._svc_name_, '') > ) > self.logger.info("Started.") > self.logger.debug("Creating processor instance") > processor = Processor(self.stopped) > self.logger.debug("Starting processor thread") > thread.start_new_thread(processor.Process,()) > self.logger.debug("Waiting for the processor thread to finish") > self.stopped.wait() > self.logger.debug("Stopping") > time.sleep(1) > while not processor.stopped.isSet(): > > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) > time.sleep(5) > servicemanager.LogMsg( > servicemanager.EVENTLOG_INFORMATION_TYPE, > servicemanager.PYS_SERVICE_STOPPED, > (self._svc_name_, "") > ) > self.logger.info("Stopped") > except: > self.logger.error('',exc_info = sys.exc_info()) > > > if __name__=='__main__': > win32serviceutil.HandleCommandLine(Service) > > I was using _ssl.pyd to upload files to DAV server over ssl and found it to be a problem. I upgraded to Python 2.5 and the problem was fixed. I don't know if it is the same problem that is affecting you, but I couldn't get it to work on 2.4. FYI, Larry From jdsalt_AT_gotadsl.co.uk Fri Feb 23 02:34:19 2007 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Fri, 23 Feb 2007 01:34:19 -0600 Subject: network simulator in Python ? References: <1172078818.126692.17510@k78g2000cwa.googlegroups.com> <1172100413.550578.105830@h3g2000cwc.googlegroups.com> Message-ID: "jonathan.sabo at gmail.com" wrote in news:1172100413.550578.105830 at h3g2000cwc.googlegroups.com: > On Feb 21, 12:26 pm, "DanielJohnson" wrote: >> I was wondering if anyblody can suggest me a network simulator [Snips] >> I am looking for a simulator [Snips] > Google for Scapy I don't think Scapy is a simulator, is it? I second the recommendation for SimPy for writing simulation programs. If you require a simulator specifically, I don't know of one in Python. All the best, John. From jeff.templon at gmail.com Tue Feb 20 12:33:51 2007 From: jeff.templon at gmail.com (Jay Tee) Date: 20 Feb 2007 09:33:51 -0800 Subject: How to test if one dict is subset of another? In-Reply-To: <1171990539.710698.276050@v45g2000cwv.googlegroups.com> References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> <1171990539.710698.276050@v45g2000cwv.googlegroups.com> Message-ID: <1171992831.871231.86450@h3g2000cwc.googlegroups.com> Hi your post had the following construct: > for j in (index['user']['jeff'] & index['state']['running']): > do_something() but Python 2.3.4 (#1, Oct 11 2006, 06:18:43) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l1= [3, 4, 7, 2] >>> l2 = [2, 3] >>> l2 = [2, 3, 99] >>> l1 & l2 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for &: 'list' and 'list' what am I missing? Thanks JT From tiedon_jano at hotmail.com Tue Feb 13 03:44:18 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 13 Feb 2007 08:44:18 GMT Subject: can't find a way to display and print pdf through python. In-Reply-To: <12t2cgssrrbmf1a@corp.supernews.com> References: <12t17gsjh6vgh94@corp.supernews.com> <12t1ch1n8hj9n69@corp.supernews.com> <12t2cgssrrbmf1a@corp.supernews.com> Message-ID: Grant Edwards kirjoitti: > On 2007-02-12, Larry Bates wrote: >> Grant Edwards wrote: >>> On 2007-02-12, Larry Bates wrote: >>>> On 2007-02-12, Larry Bates wrote: >>>>>>> I at least need the code for useing some library for >>>>>>> connecting to acrobat reader and giving the print command on >>>>>>> windows and some thing similar on ubuntu linux. >>>>>> Just let the registered .PDF viewer do it for you. >>>>>> >>>>>> os.start('myfile.pdf') >>>>> Eh? I don't see os.start() it either 2.5 or 2.44 >>>>> documentation, and it's sure not there in 2.4.3: >>>> My bad. os.system() >>> That doesn't work either: >>> >>> $ ls -l user.pdf >>> -rw------- 1 grante users 35640 2005-11-21 14:33 user.pdf >>> >>> $ python >>> Python 2.4.3 (#1, Dec 10 2006, 22:09:09) >>> [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more >>> information. >>> >>> import os >>> >>> os.system('user.pdf') >>> sh: user.pdf: command not found >>> 32512 >>> >>> >> Works fine on my system. You linux guys just have it hard. >> The op said "windows". > > The posting to which you replied specified Linux. > >> I can't answer for ubuntu linux but maybe you can help there? > > I don't see how. Pdf files just aren't executable. > On Windows, this (where fileName is xyz.PDF, for example): webbrowser.open(r'file://' + fileName) starts Acrobat Reader with the document read in. I have no idea why, because Acrobat Reader sure ain't my browser;) Maybe someone could try this out on Linux. Cheers, Jussi From steve at holdenweb.com Tue Feb 20 21:12:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 20 Feb 2007 21:12:58 -0500 Subject: Regex Speed In-Reply-To: <1172013317.943062.303110@t69g2000cwt.googlegroups.com> References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172013317.943062.303110@t69g2000cwt.googlegroups.com> Message-ID: John Machin wrote: [...] > > To help you, we need either (a) basic information or (b) crystal > balls. [...] How on earth would having glass testicles help us help him? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From arkanes at gmail.com Mon Feb 5 16:00:21 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 5 Feb 2007 15:00:21 -0600 Subject: Unicode formatting for Strings In-Reply-To: References: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> Message-ID: <4866bea60702051300g754648baha185955d2dc1d12a@mail.gmail.com> On 2/5/07, Kent Johnson wrote: > robson.cozendey.rj at gmail.com wrote: > > Hi, > > > > I?m trying desperately to tell the interpreter to put an '?' in my > > string, so here is the code snippet: > > > > # -*- coding: utf-8 -*- > > filename = u"Ataris Aqu?ticos #2.txt" > > f = open(filename, 'w') > > > > Then I save it with Windows Notepad, in the UTF-8 format. So: > > > > 1) I put the "magic comment" at the start of the file > > 2) I write u"" to specify my unicode string > > 3) I save it in the UTF-8 format > > > > And even so, I get an error! > > > > File "Ataris Aqu?ticos #2.py", line 1 > > SyntaxError: Non-ASCII character '\xff' in file Ataris Aqu?ticos #2.py > > on line 1 > > It looks like you are saving the file in Unicode format (not utf-8) and > Python is choking on the Byte Order Mark that Notepad puts at the > beginning of the document. > Notepad does support saving to UTF-8, and I was able to do this without the problem the OP was having. I also saved both with and without a BOM (in UTF-8) using SciTe, and Python worked correctly in both cases. > Try using an editor that will save utf-8 without a BOM, e.g. jedit or > TextPad. > > Kent > -- > http://mail.python.org/mailman/listinfo/python-list > From tleeuwenburg at gmail.com Thu Feb 15 21:15:39 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 15 Feb 2007 18:15:39 -0800 Subject: The Python Papers Volume 2 Issue 1 HTML now available Message-ID: <1171592139.626135.274060@p10g2000cwp.googlegroups.com> http://archive.pythonpapers.org/ThePythonPapersVolume2Issue1.html Hi Pythonistas! The HTML version of the latest edition of The Python Papers is now available from the above URL. The editors understand that the web layout lacks the sophistication of the PDF, or indeed that possible under HTML. However, we will endeavour to improve on the quality of future releases as we gain familiarity with the dual-format publishing model. In the meantime, we hope you enjoy the content of this new edition. Cheers, -T (Editor-In-Chief) From horpner at yahoo.com Tue Feb 13 06:40:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 13 Feb 2007 12:40:15 +0100 Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: On 2007-02-12, Thomas Nelson wrote: > I realize I'm approaching this backwards from the direction > most people go, but does anyone know of a good c/c++ > introduction for python programmers? To become productive in C++ in a short time, especially with a Python background, I highly recommend Koenig & Moo _Accelerated C++_. It's not enough C++ to join a C++ team at a professional development house (of course no book can provide that), but it's all the best bits. If you get through that, then proceed directly to the source, Stroustrup _The C++ Programming language_. -- Neil Cerutti You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor From karoly.kiripolszky at gmail.com Sat Feb 3 08:47:08 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 3 Feb 2007 05:47:08 -0800 Subject: strange test for None Message-ID: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> in my server i use the following piece of code: ims = self.headers["if-modified-since"] if ims != None: t = int(ims) and i'm always getting the following error: t = int(ims) ValueError: invalid literal for int(): None i wanna know what the hell is going on... first i tried to test using is not None, but it makes no difference. From theller at ctypes.org Wed Feb 7 11:47:39 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 07 Feb 2007 17:47:39 +0100 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <1170862664.972024.322260@a75g2000cwd.googlegroups.com> References: <45C9A137.8090009@v.loewis.de> <1170861460.614883.108310@k78g2000cwa.googlegroups.com> <1170862664.972024.322260@a75g2000cwd.googlegroups.com> Message-ID: <45CA02AB.9090106@ctypes.org> Carl Banks schrieb: > On Feb 7, 10:17 am, "Carl Banks" wrote: >> On Feb 7, 8:51 am, Thomas Heller wrote: >> >> >> >> > Martin v. L?wis schrieb: >> >> > > I'm happy to announce partial 1.0; a module to implement >> > > partial classes in Python. It is available from >> >> > >http://cheeseshop.python.org/pypi/partial/1.0 >> >> > > A partial class is a fragment of a class definition; >> > > partial classes allow to spread the definition of >> > > a class over several modules. One location serves >> > > as the original definition of the class. >> >> > > To extend a class original_module.FullClass with >> > > an additional function, one writes >> >> > > from partial import * >> > > import original_module >> >> > > class ExtendedClass(partial, original_module.FullClass): >> > > def additional_method(self, args): >> > > body >> > > more_methods >> >> > > This module is licensed under the Academic Free License v3.0. >> >> > > Please send comments and feedback to mar... at v.loewis.de >> >> > Nice idea. >> >> Indeed. I was going to make a post asking for advice on high-level >> delegation (basically you have a generic mostly-OO framework, which >> the user extends mostly by subclassing, but how do the generic classes >> know about the user-extened classes?). I knew of many solutions, but >> all had significant drawbacks. But this seems like it'd work great, >> maybe with a few minor inconveniences but nothing like the icky hacks >> I've been using. >> >> Ironic, since I myself posted a very simple example of how to do this >> with a class hook here on c.l.python a while back. > > And looking back at that post, I said that using such a hack would be > "truly evil". To every thing there is a season.... Do you have a pointer to that post? Thomas From duncan.booth at invalid.invalid Tue Feb 6 03:35:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Feb 2007 08:35:08 GMT Subject: Python compiled on Windows References: Message-ID: Franz Steinhaeusler wrote: > @Duncan: Yes, you are not wrong! :) > But this is not really open source in my opinion. > Ok there is the VC++ toolkit for download. Which I agree totally is a real pain finding the right versions to download. > > I'm just curious, if there ever had compiled on windows using > that toolkit or even with gcc, and with gcc, whether there are > problems or/and differences in speed and run time behaviour. > Yes, people have compiled Python with gcc on windows. I believe it is slightly slower than the standard release, but I would guess that may depend on the exact versions of gcc/msc you choose to compare, and the exact compiler options you choose (or I may even be imagining it entirely). As I understand it, you can use Mingw to compile extension modules which are compatible with the standard release of Python, and of course there is always cygwin. But I still don't understand what difference it makes to anyone between: an application (could be open or closed source) running on an open source language (Python) compiled with a closed source compiler on a closed source OS. versus an application (could be open or closed source) running on an open source language (Python) compiled with an open source compiler on a closed source OS. at the end of the day you still have a mix of open and closed source components. If it makes you feel better to be using an open source compiler that's fine, but it doesn't really do anything for me. From tdelaney at avaya.com Wed Feb 14 17:27:24 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 15 Feb 2007 09:27:24 +1100 Subject: python not returning true Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EC97@au3010avexu1.global.avaya.com> John Machin wrote: agent-s wrote: >> btw Steven you are so witty I hope to one day pwn noobs on newsgroups >> too. > > Wit has nothing to do with it. The fact that you are a Python noob is > also irrelevant. Your problem statement was unintelligible, as is your > response. What does "pwn" mean? Or to put it more succinctly ... http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From sickcodemonkey at gmail.com Tue Feb 6 22:28:31 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 6 Feb 2007 22:28:31 -0500 Subject: Dictionary/Hash question In-Reply-To: References: <2adc542f0702061531g7504de83ob01b56933794a37e@mail.gmail.com> <2adc542f0702061718h5a943312id61c3ac77c074a95@mail.gmail.com> Message-ID: <2adc542f0702061928p27c8585eta82c20e0cbf7c30@mail.gmail.com> qualm after qualm. Before you read this, my OS is Linux, up2date, and minimal RAM (512). On purpose becuase I want this app to run on anything. I have 2 very good solutions to this problem (AND I WANT TO THANK 'Gabriel Genellina' AND 'Don Morrison' with comparing 2 LARGE files). (LARGE means anywhere from 2MB to 800MB) The files that my script needs to read in and interpret can contain anywhere from 5 million lines to 65 million lines I have attached 2 versions of code for you to analyze. ================= I am having issues with performance. Instance 1: dict_compare.py {which is attached} Is awesome, in that I have read a file and stored it into a hash table, but if you run it, the program decides to stall after writing all of the date. Instance 2: dictNew.py Runs great but it is a little slower than Instance 1 (dict_compare.py). BUT WHEN IT FINISHES, IT STOPS THE APPLICATION.... no additional minutes..... Can anyone tell me why Intance1 takes so long to finish? I looooove both methods, but I cannot understand the timeframe differences. HELP!!!!!!!!!!! ======================== Output Test1: [user at SickCodeMonkey hash]# date Tue Feb 6 21:23:52 EST 2007 [user at SickCodeMonkey hash]# python dict_compare.py date starting list 2 finished storing information in lists. storing File1 in dictionary. finished comparing 2 lists. Stopped processing done [user at SickCodeMonkey hash]# date Tue Feb 6 21:36:14 EST 2007 Total: Over 10 minutes ------------------------------------ Output Test2: Tue Feb 6 21:38:55 EST 2007 [user at SickCodeMonkey hash]# python dictNew.py date finished comparing 2 lists. Stopped processing done [user at SickCodeMonkey hash]# date Tue Feb 6 21:40:36 EST 2007 Total: Less than 2 minutes On 2/6/07, Gabriel Genellina wrote: > > En Tue, 06 Feb 2007 22:18:07 -0300, Sick Monkey > escribi?: > > > I have never seen this "with open(fname,'r') as finput:" > > > > It is actually throwing an error . Do I have to import a special > > library to > > use this? > > > > File "dictNew.py", line 23 > > with open(fname,'r') as finput: > > ^ > > SyntaxError: invalid syntax > > Oh, sorry. You need two things: > - Python 2.5 > - include this line at the very beginning of your script: from __future__ > import with_statement > > If you're using an earlier version, you can write: > > finput = open(fname,'r') > try > ... > finally > finput.close() > > (Or just omit the try/finally and rely on the garbage collector, but it's > not the recommended practice, specially when external resources are > involved, like files). > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dictNew.py Type: application/x-python Size: 2502 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dict_compare.py Type: application/x-python Size: 2691 bytes Desc: not available URL: From steven.bethard at gmail.com Wed Feb 7 19:27:29 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 07 Feb 2007 17:27:29 -0700 Subject: Array delete In-Reply-To: References: <45BC84B6.9080505@riddergarn.dk> Message-ID: <9qOdneU6ws_w81fYnZ2dnUVZ_uejnZ2d@comcast.com> Jerry Hill wrote: > On 1/28/07, Scripter47 wrote: >> Can someone plz make a function for that takes a array, and then search >> in it for duplicates, if it finds 2 or more items thats the same string >> then delete all except 1. > > >>> myList = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10] > >>> myList = list(set(myList)) > >>> print myList > [8, 1, 2, 4, 10] > > Maintaining sort order is left as an exercise for the reader. A "simple" two-liner that maintains order: >>> items = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10] >>> seen = set() >>> [x for x in items if x not in seen and not seen.add(x)] [1, 2, 4, 8, 10] Mmm... what a beautiful abuse of "and". ;-) STeVe From harlinseritt at yahoo.com Sun Feb 18 22:00:35 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 18 Feb 2007 19:00:35 -0800 Subject: Logging errors to a file Message-ID: <1171854035.318628.28730@p10g2000cwp.googlegroups.com> Is there any way to automatically log errors that occur within an executed script to a file? Thanks, Harlin From samckain at southslope.net Wed Feb 14 13:13:14 2007 From: samckain at southslope.net (Steve) Date: Wed, 14 Feb 2007 12:13:14 -0600 Subject: list of range of floats References: Message-ID: On Wed, 14 Feb 2007 17:29:26 +0000, Simon Brunning wrote: > On 2/14/07, Steve wrote: >> I'm trying to create a list range of floats and running into problems. >> I've been trying something like: >> >> a = 0.0 >> b = 10.0 >> >> flts = range(a, b) >> >> fltlst.append(flts) >> >> When I run it I get the following DeprecationWarning: integer argument >> expected, got float. How can I store a list of floats? > > There would be an *enormous* number of floats between zero and ten. Do > you really want all of them in your list? I hope you have a few > terrabytes of RAM... > > Or do you just want the integer values as floats? > > fits = list(float(a) for a in range(0, 10)) After re-reading my original post I was pretty vague. I'm trying to creat a list of ranges of floats, 0.0 10.0, 11 20, etc then checking to see if an float, example 12.5 falls in the list and if so get the list index of where it is in the index. Does this make sense? Steve From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 15:44:02 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 21:44:02 +0100 Subject: Object type check In-Reply-To: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> Message-ID: <45ca32ed$0$32232$426a74cc@news.free.fr> king kikapu a ?crit : > Hi to all, > > in statically-types languages, let's say C# for example, we use > polymorphism through interfaces. So we define an interface I with > method M and then a class C that implements I interface and write code > for the M method. > So, if we have a function that takes a parameter of type I, we know > before-hand that it will have an M method to call. > > But in dynamic languages this is not the case and we can pass whatever > we want to that function. Yes. And this is a Good Thing (tm). > Assuming that someone writes a library in > Python that other programmers will use, what is the correct way to > check inside that function if the parameter passed is of the correct > type, maybe "isinstance" BIF ? The correct way in Python is to *not* check. Just document what kind of interface you expect, and it's ok. If the people using your code are stupid and lazy enough to not read the doc, then you can't help . From jeremit0 at gmail.com Thu Feb 1 11:50:13 2007 From: jeremit0 at gmail.com (jeremito) Date: 1 Feb 2007 08:50:13 -0800 Subject: how to add class attributes in __new__ Message-ID: <1170348611.562439.122780@a34g2000cwb.googlegroups.com> I am subclassing the array class and have __new__ to initialize and create my class. In that class I create not only do I create an array object, but I also create some other data in __new__ I want to have access to outside of __new__. I tried self.mydata = mydata but that didn't work. Can someone point me in the right direction? Thanks, Jeremy From pink at odahoda.de Wed Feb 21 17:34:49 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 21 Feb 2007 23:34:49 +0100 Subject: Creating a daemon process in Python References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> <1172095596.050555.225750@j27g2000cwj.googlegroups.com> Message-ID: garrickp at gmail.com wrote: > On Feb 21, 9:33 am, Eirikur Hallgrimsson > wrote: >> Sakagami Hiroki wrote: >> > What is the easiest way to create a daemon process in Python? > > I've found it even easier to use the built in threading modules: > > import time > > t1 = time.time() > print "t_poc.py called at", t1 > > import threading > > def im_a_thread(): > time.sleep(10) > print "This is your thread speaking at", time.time() > > thread = threading.Thread(target=im_a_thread) > thread.setDaemon(True) > thread.start() > t2 = time.time() > print "Time elapsed in main thread:", t2 - t1 > > > Of course, your mileage may vary. That's not a daemon process (which are used to execute 'background services' in UNIX environments). -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From arkanes at gmail.com Thu Feb 22 09:36:40 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 22 Feb 2007 08:36:40 -0600 Subject: How to test whether a host is reachable? In-Reply-To: References: Message-ID: <4866bea60702220636m9af8ee1uc9d685d0bd12707a@mail.gmail.com> On 2/22/07, Fabian Steiner wrote: > Hello! > > As the subject says I need to test whether a host computer in our > network is reachable or not. At the moment I simply attempt to connect > to a given port that is open when the machine is online: > > [...] > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > try: > sock.connect(('192.168.0.100', 80)) > except socket.error: > print >>sys.stderr "Server offline" > sock.close() > [...] > > Now I am wondering if there isn't any better method which would be more > general. In fact, I think of something like a python version of ping > which only tries to send ICMP packets. However, I don't know what the > code has to look like then. Any ideas or suggestions? > This is the only reliable way of telling if you can communicate with a service on a machine. A ping will tell you if it's connected to the network, but not if it is actually providing any services. If you really want a ping, the common way is to just execute the systems ping. From ronpro at cox.net Tue Feb 13 20:10:54 2007 From: ronpro at cox.net (Ron Provost) Date: Tue, 13 Feb 2007 20:10:54 -0500 Subject: Is python2.5's Tix wrapper broken? Message-ID: I have a piece of software I wrote some time ago using Python and the Tix wrapper. I just upgraded to Python 2.5 and to my surprise my software no longer functions. There's a problem with the Tix wrapper. Under a clean install of Python the following should display an empty root window on the screen and happily. >>> import Tix >>> root = Tix.Tk() Under Python2.5, the empty root window is displayed but I also get a Traceback: Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\lib-tk\Tix.py", line 210, in __init__ self.tk.eval('package require Tix') _tkinter.TclError: can't find package Tix Of course I can fix this with a cheap try block, but wonder if there's a better way. try: root = Tix.Tk() except: print "Tk exception caught" Is Tix now broken or is there a new "proper" way to get a Tk root window? Thanks, Ron From http Wed Feb 14 18:29:20 2007 From: http (Paul Rubin) Date: 14 Feb 2007 15:29:20 -0800 Subject: rot13 in a more Pythonic style? References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: <7x64a42u9b.fsf@ruckus.brouhaha.com> "Andy Dingley" writes: > c_rot13 = lambdaf c : (((c, uc_rot13(c)) [c in > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']), lc_rot13(c) )[c in > 'abcdefghijklmnopqrstuvwxyz'] Oh, I see what you mean, you have separate upper and lower case maps and you're asking how to select one in an expression. Pythonistas seem to prefer using multiple statements: def c_rot13(c): if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': return uc_rot13(c) elif c in 'abcdefghijklmnopqrstuvwxyz': return lc_rot13(c) return c You could use the new ternary expression though: c_rot13 = lambda c: \ uc_rot13(c) if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' else \ (lc_rot13(c) if c in 'abcdefghijklmnopqrstuvwxyz' else \ c) if I have that right. From flupke at nonexistingdomain.com Thu Feb 8 08:02:24 2007 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 08 Feb 2007 13:02:24 GMT Subject: postgres backup script and popen2 Message-ID: Hi, i made a backup script to backup my postgres database. Problem is that it prompts for a password. It thought i could solve this by using popen2. I tested popen2 with dir (i'm on windows 2000, python 2.4.3) and it works. However when i try popen2 and my pg_dump command, it prompts for a password and I was under the impression that i was going to be able to dynamically communicate with the process. sin, sout = popen2(backup_command) sin.readline() # the password prompt sout.write("password") sin.readlines() How can i catch the password prompt and feed the password from my code? Thanks, Benedict From maric at aristote.info Wed Feb 14 23:43:11 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 15 Feb 2007 05:43:11 +0100 Subject: threading and multicores, pros and cons In-Reply-To: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> Message-ID: <200702150543.12593.maric@aristote.info> Le mercredi 14 f?vrier 2007 16:24, garrickp at gmail.com a ?crit?: > "Some time back, a group did remove the GIL from the python core, and > implemented locks on the core code to make it threadsafe. Well, the > problem was that while it worked, the necessary locks it made single > threaded code take significantly longer to execute." Very interesting point, this is exactly the sort of thing I'm looking for. Any valuable link on this ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 Mobile: +33 632 77 00 21 From kilianheckrodt at yahoo.com Fri Feb 23 15:38:11 2007 From: kilianheckrodt at yahoo.com (kilian heckrodt) Date: Fri, 23 Feb 2007 21:38:11 +0100 Subject: Who has not attended these free tutorial courses ? In-Reply-To: <1172257564.241642.300140@m58g2000cwm.googlegroups.com> References: <1172257564.241642.300140@m58g2000cwm.googlegroups.com> Message-ID: stj911 at rock.com wrote: Please note that this is a math newsgroup and not a i-post-my-favoured-conspiracy-theory newsgroup > "President Bush ... you are under arrest" - 911 truth video by Dr > Morgan Reynolds, Former Chief Economist under Bush > > You can also save them by right clicking the > links and saving them as flv files and download a free flv player. > google is your best friend. > > "Bush Administration Insider Says U.S. Government Behind 911.flv" > "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w" <--- > key video > > "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http:// > youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" > > "911 Truth, Consequences of Revealing the Truth about 911.flv" > "http:// > youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" > > "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv" > "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" > > "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax- > v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" > > "Bush gets caught off guard on 9/11 prior knowledge question.flv" > "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" > > "Bush gets caught off guard on 911 prior knowledge question.flv" > "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" > > "World Trade Center -- Controlled Demolition.flv" "http:// > v187.youtube.com/get_video?video_id=87fyJ-3o2ws" > > "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv" > "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90" > > The Answer: Why do they hate our freedoms :)))) > From johnjsal at NOSPAMgmail.com Wed Feb 7 15:56:08 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 07 Feb 2007 15:56:08 -0500 Subject: Can somebody give me a python code for this? In-Reply-To: References: Message-ID: <45ca3ce3$0$32403$c3e8da3@news.astraweb.com> John wrote: > I solved it myself. > Don't bother. Heh heh, I don't think they were going to anyway. From mail at timgolden.me.uk Mon Feb 26 10:33:30 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Feb 2007 15:33:30 +0000 Subject: ez_setup.py In-Reply-To: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> Message-ID: <45E2FDCA.2000703@timgolden.me.uk> Nader Emami wrote: > L.S., > > I have installed locally Python-2.4.4 without any problem. Then I would > install the "ez_setup.py" to be able using of "easy_install" tool, but I > get the next error: > > %python ez_setup.py > Traceback (most recent call last): > File "ez_setup.py", line 223, in ? > main(sys.argv[1:]) > File "ez_setup.py", line 155, in main > egg = download_setuptools(version, delay=0) > File "ez_setup.py", line 111, in download_setuptools > import urllib2, shutil > File "/usr/people/emami/lib/python2.4/urllib2.py", line 108, in ? > import cookielib > File "/usr/people/emami/lib/python2.4/cookielib.py", line 35, in ? > from calendar import timegm > File "/usr/people/emami/calendar.py", line 23, in ? > import pygtk > ImportError: No module named pygtk > > I don't understand what is the problem! Could somebody tell me what I > have to do to solve it? You have a module called "calendar" in your user directory /usr/people/emami/calendar.py which is shadowing the stdlib calendar module -- which doesn't get used much so you've probably never noticed. Either rename your local one or take your home folder off the Python path... at least for long enough for ez_setup to do its stuff. TJG From arkanes at gmail.com Tue Feb 20 15:24:32 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 20 Feb 2007 14:24:32 -0600 Subject: wxPython: non-GUI thread launching new frame? Delegates? In-Reply-To: <1172001661.882918.193600@l53g2000cwa.googlegroups.com> References: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> <5405fnF1upuuoU1@mid.uni-berlin.de> <1172001661.882918.193600@l53g2000cwa.googlegroups.com> Message-ID: <4866bea60702201224k6d29391ds32baf56c49e6b3d0@mail.gmail.com> On 20 Feb 2007 12:01:02 -0800, cyberco wrote: > Ah! Great tip, thanks! > Now instead of calling: > > parent.onRequest(param) > > I call: > > wx.CallAfter(lambda x: parent.onRequest(x), param) > You don't need the lambda - you can use: wx.CallAfter(parent.OnRequest, param) From exarkun at divmod.com Thu Feb 22 08:01:55 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 22 Feb 2007 08:01:55 -0500 Subject: plugin development best practices In-Reply-To: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> Message-ID: <20070222130155.25807.998526049.divmod.quotient.29589@ohm> On 22 Feb 2007 04:53:02 -0800, Flavio wrote: >Hi, > >Nowadays the addition of functionality to programs by means of >plugins is very frequent. > >I want to know the opinions of experienced Python developers about the >best practices when it comes to developing a plugin system for a >Python package. > >Should plugins be modules in a separate package? >Should there be a registry of available plugins? how would such a >registry be implemented? etc. > >thanks, > Best practice may be to not develop a new plugin system. There are quite a few available already. Most likely, at least one of them is suitable for your application. Here are a couple starting points: http://twistedmatrix.com/projects/core/documentation/howto/plugin.html http://peak.telecommunity.com/DevCenter/setuptools#dynamic-discovery-of-services-and-plugins Jean-Paul From robert.kern at gmail.com Fri Feb 9 15:35:41 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 09 Feb 2007 12:35:41 -0800 Subject: ANN: Wing IDE 2.1.4 Released In-Reply-To: <45ccd9a4$0$49207$14726298@news.sunsite.dk> References: <45ccd9a4$0$49207$14726298@news.sunsite.dk> Message-ID: Damjan wrote: >> This is a bug fix release that among other things fixes handling of >> UTF-8 byte order marks, > > What are UTF-8 byte order marks ?!? > There's only one order in the UTF-8 bytes! It's a misnomer, but one that persists. http://unicode.org/unicode/faq/utf_bom.html#29 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rshepard at foobar.appl-ecosys.com Thu Feb 8 09:30:41 2007 From: rshepard at foobar.appl-ecosys.com (rshepard at foobar.appl-ecosys.com) Date: 8 Feb 2007 14:30:41 GMT Subject: 'IF' Syntax For Alternative Conditions References: <7x3b5h7071.fsf@ruckus.brouhaha.com> Message-ID: On 2007-02-08, Paul Rubin wrote: > rshepard at nospam.appl-ecosys.com writes: >> if cond1: >> if cond2: >> do_something. > > You can write: > if cond1 and cond2: > do_something > >> if cond1 OR if cond2: >> do_something. > > if cond1 or cond2: > do_something > >> I've tried using the C syntax for OR (||) but python complained. I'm sure >> there's a way to do this rather than using if cond1: elif cond2: both with >> the same code to execute. > > Python uses the "and" and "or" keywords for && and ||. Allow me to thank all of you who responded with this one article. For whatever reason, it did not occur to me to use the words 'and' and 'or.' And, I did not see this in the tutorial or introduction ... which is my fault. So, I do thank all of you. Rich From Shawn at Milochik.com Thu Feb 8 12:20:57 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Thu, 8 Feb 2007 12:20:57 -0500 Subject: Fwd: Python new user question - file writeline error In-Reply-To: <1170954351.593141.94290@v33g2000cwv.googlegroups.com> References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> <1170954351.593141.94290@v33g2000cwv.googlegroups.com> Message-ID: <2dc0c81b0702080920w63b6b323v387c711051913abc@mail.gmail.com> On 8 Feb 2007 09:05:51 -0800, Gabriel Genellina wrote: > On 8 feb, 12:41, "Shawn Milo" wrote: > > > I have come up with something that's working fine. However, I'm fairly > > new to Python, so I'd really appreciate any suggestions on how this > > can be made more Pythonic. > > A few comments: > > You don't need the formatDatePart function; delete it, and replace > newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) > with > newDate = ",%04.4d-%02.2d-%02.2d," % (yearNum,monthNum,dayNum) > > and before: > dayNum, monthNum, yearNum = [int(num) for num in > someDate[1:-1].split('/')] > > And this: outfile.writelines(line) > should be: outfile.write(line) > (writelines works almost by accident here). > > You forget again to use () to call the close methods: > infile.close() > outfile.close() > > I don't like the final replace, but for a script like this I think > it's OK. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > Gabriel, Thanks for the comments! The new version is below. I thought it made a little more sense to format the newDate = ... line the way I have it below, although I did incorporate your suggestions. Also, the formatting options you provided seemed to specify not only string padding, but also decimal places, so I changed it. Please let me know if there is some other meaning behind the way you did it. As for not liking the replace line, what would you suggest instead? Shawn #! /usr/bin/python import sys import re month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} infile=file('TVA-0316','r') outfile=file('tmp.out','w') regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") for line in infile: matches = regex.findall(line) for someDate in matches: dayNum = someDate[1:3] monthNum = month[someDate[4:7]] yearNum = someDate[8:12] newDate = ",%04d-%02d-%02d," % (int(yearNum),int(monthNum),int(dayNum)) line = line.replace(someDate, newDate) outfile.write(line) infile.close() outfile.close() From tleeuwenburg at gmail.com Thu Feb 15 21:16:09 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 15 Feb 2007 18:16:09 -0800 Subject: The Python Papers Volume 2 Issue 1 HTML now available Message-ID: <1171592169.522951.302430@v45g2000cwv.googlegroups.com> http://archive.pythonpapers.org/ThePythonPapersVolume2Issue1.html Hi Pythonistas! The HTML version of the latest edition of The Python Papers is now available from the above URL. The editors understand that the web layout lacks the sophistication of the PDF, or indeed that possible under HTML. However, we will endeavour to improve on the quality of future releases as we gain familiarity with the dual-format publishing model. In the meantime, we hope you enjoy the content of this new edition. Cheers, -T (Editor-In-Chief) From eric_brunel at despammed.com Wed Feb 21 10:34:50 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 21 Feb 2007 16:34:50 +0100 Subject: Tkinter checkbuttons and variables References: Message-ID: On Wed, 21 Feb 2007 15:50:57 +0100, Gigs_ wrote: > from Tkinter import * > > states = [] > > def onpress(i): > states[i] = not states[i] > > > root = Tk() > for i in range(10): > chk = Checkbutton(root, text= str(i), command=lambda i=i: > onpress(i)) > chk.pack(side=LEFT) > states.append(0) > root.mainloop() > print states > > after exiting i get everything like it suppose to but when i put command > like this: > command=lambda: onpress(i) > i got only last checkbutton check. > > Why i have to pass this default argument? I'm basically not answering your question here, but the usual way to get a checkbuttons's state is as follows: states = [] root = Tk() for i in range(10): stateVar = BooleanVar() chk = Checkbutton(root, text=str(i), variable=stateVar) chk.pack(side=LEFT) states.append(stateVar) root.mainloop() print [v.get() for v in states] If you want to get the value of one of your states, use the get() method on BooleanVar. If you want to change such a state, use the set(value) method. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From anil.jupiter9 at gmail.com Sun Feb 18 09:30:03 2007 From: anil.jupiter9 at gmail.com (jupiter) Date: 18 Feb 2007 06:30:03 -0800 Subject: function & class Message-ID: <1171809003.491107.243550@q2g2000cwa.googlegroups.com> hi friends, I have a program like some variable definations a function ( arg1, agr2): do something with arg1 & arg2 return a list if condition do this function(arg1,arg2) else if condition do this function else do this My problem is I want to use threading and I might need to pass values between function and classes. I am not sure how this can be done. I have read about classes and I know they are like function however does not return anything where as function does. If I define class and then function in this class how do I access this function ????? I am not sure and confused about classes and functions as how to go about them is there any simple way to understand difference between them and when to use what and how to pass data/reference pointer between them ? @nil Pythonist From jonathan-lists at cleverdevil.org Mon Feb 12 14:35:55 2007 From: jonathan-lists at cleverdevil.org (Jonathan LaCour) Date: Mon, 12 Feb 2007 14:35:55 -0500 Subject: Announcing Elixir! Message-ID: <6FF6917B-CE2F-4E22-9264-609B5F46222E@cleverdevil.org> Today, we are pleased to announce the release of Elixir (http://elixir.ematia.de), a declarative mapper for SQLAlchemy. Elixir is the successor to ActiveMapper and TurboEntity, and is a collaboration between Daniel Haus, Jonathan LaCour and Ga?tan de Menten. Elixir's website provides installation instructions, a tutorial, extensive documentation, and more. The eventual goal of Elixir is to become an official SQLAlchemy extension after some time soliciting feedback, bug reports, and testing from users. Daniel Haus http://www.danielhaus.de Ga?tan de Menten http://openhex.com Jonathan LaCour http://cleverdevil.org From me at privacy.net Sun Feb 25 10:07:16 2007 From: me at privacy.net (Dan Sommers) Date: Sun, 25 Feb 2007 10:07:16 -0500 Subject: Endianness conversion References: <45e05c49$0$20809$5fc30a8@news.tiscali.it> <45e07570$0$20809$5fc30a8@news.tiscali.it> Message-ID: On Sat, 24 Feb 2007 17:27:12 +0000, Toby wrote: > Dan Sommers wrote: >> You could try the struct module. If your input comes in fixed sized >> chunks, just call struct.unpack and struct.pack once per chunk. > > Thanks, but it was a bit awkward to use for big chunks. def swapper( bytestring ): someHs = len( bytestring ) / 2 * "H" # could check for odd-lengths? unpackfmt = "<" + someHs packfmt = ">" + someHs return struct.pack( packfmt, *struct.unpack( unpackfmt, bytestring ) -- Dan Sommers Atoms are not things. -- Werner Heisenberg. From jgrzebyta at NO.gazeta.pl.SPAM Sun Feb 18 20:18:11 2007 From: jgrzebyta at NO.gazeta.pl.SPAM (Jacol) Date: Mon, 19 Feb 2007 01:18:11 +0000 Subject: How to detect closing of wx.Panel? Message-ID: Hi everybody, I have poblem with detecting closing of wx.Panel by user. How to detect that event? The wx.EVT_CLOSE event concerns wx.Frame class only. Neither Close() nor Destroy() aren't executed if the event occurs (if user close a panel). Thus extanding these both methods doesn't make sens (I've tested that). With many thanks & Best wishes, Jacek From stdazi at gmail.com Fri Feb 16 10:30:15 2007 From: stdazi at gmail.com (stdazi) Date: 16 Feb 2007 07:30:15 -0800 Subject: why I don't like range/xrange Message-ID: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Hello! Many times I was suggested to use xrange and range instead of the while constructs, and indeed, they are quite more elegant - but, after calculating the overhead (and losen flexibility) when working with range/xrange, and while loops, you get to the conclusion that it isn't really worth using range/xrange loops. I'd like to show some examples and I'll be glad if someone can suggest some other fixes than while a loop :-) a) range overfllow : for i in range(0, 1 << len(S)) : ..... OverflowError: range() result has too many items ok, so we fix this one with xrange ! b) xrange long int overflow : for i in xrange(0, 1 << len(S)) : ........ OverflowError: long int too large to convert to int Next thing I miss is the flexibility as in C for loops : for (i = 0; some_function() /* or other condition */ ; i++) or, for (i = 0 ; i < 10 ; i++) i = 10; I don't think range/xrange sucks, but I really think there should be some other constructs to improve the looping flexibility. Other thing may be, that I just miss an equally elegant alternative that's why I'd like to hear some suggestions on how to fix the above issues.. (btw, I've already browsed the archives related to my issue,but i don't see any good solution) Thanks Jernej. From lycka at carmen.se Thu Feb 1 08:04:40 2007 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 01 Feb 2007 14:04:40 +0100 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170046719.708692.243290@s48g2000cws.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: NoName wrote: > Perl: > @char=("A".."Z","a".."z",0..9); > do{print join("", at char[map{rand @char}(1..8)])}while(<>); If you generate passwords like that to normal computer users, you'll end up with a lot of "my password doesn't work" tickets. You should skip the symbols that are easy to mistake for each other. Skip at least Il1 and 0O. On the other hand, you could probably use other characters besides letters and digits to make the passwords stronger. Which ones to use is unfortunately platform dependent. From tiedon_jano at hotmail.com Wed Feb 21 07:45:53 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Wed, 21 Feb 2007 12:45:53 GMT Subject: Sorting directory contents In-Reply-To: <45DB0D28.6060608@websafe.com> References: <45DB0D28.6060608@websafe.com> Message-ID: <5aXCh.145$9e6.142@read3.inet.fi> Larry Bates kirjoitti: > Wolfgang Draxinger wrote: >> Jussi Salmela wrote: >> >>> I'm not claiming the following to be more elegant, but I would >>> do it like this (not tested!): >>> >>> src_file_paths = dict() >>> prefix = sourcedir + os.sep >>> for fname in os.listdir(sourcedir): >>> if match_fname_pattern(fname): >>> fpath = prefix + fname >>> src_file_paths[os.stat(fpath).st_mtime] = fpath >>> for ftime in src_file_paths.keys().sort(): >>> read_and_concatenate(src_file_paths[ftime]) >> Well, both versions, mine and yours won't work as it was written >> down, as they neglegt the fact, that different files can have >> the same st_mtime and that .sort() doesn't return a >> sorted list. >> >> However this code works (tested) and behaves just like listdir, >> only that it sorts files chronologically, then alphabetically. >> >> def listdir_chrono(dirpath): >> import os >> files_dict = dict() >> for fname in os.listdir(dirpath): >> mtime = os.stat(dirpath+os.sep+fname).st_mtime >> if not mtime in files_dict: >> files_dict[mtime] = list() >> files_dict[mtime].append(fname) >> >> mtimes = files_dict.keys() >> mtimes.sort() >> filenames = list() >> for mtime in mtimes: >> fnames = files_dict[mtime] >> fnames.sort() >> for fname in fnames: >> filenames.append(fname) >> return filenames >> >> Wolfgang Draxinger > > Four suggestions: > > 1) You might want to use os.path.join(dirpath, fname) instead of > dirpath+os.sep+fname. > > 2) You may be able to use glob.glob() to filter the files > more easily. > > 3) You didn't handle the possibility that there is s subdirectory > in the current directory. You need to check to make sure it is > a file you are processing as os.listdir() returns files AND > directories. > > 4) If you just put a tuple containing (mtime, filename) in a list > each time through the loop you can just sort that list at the > end it will be sorted by mtime and then alphabetically. > > Example (not tested): > > def listdir_chrono(dirpath): > import os > # > # Get a list of full pathnames for all the files in dirpath > # and exclude all the subdirectories. Note: This might be > # able to be replaced by glob.glob() to simplify. I would then > # add a second optional parameter: mask="" that would allow me > # to pass in a mask. > # > # List comprehensions are our friend when we are processing > # lists of things. > # > files=[os.path.join(dirpath, x) for x in os.listdir(dirpath) > if not os.path.isdir(os.path.join(dirpath, x)] > > # > # Get a list of tuples that contain (mtime, filename) that > # I can sort. > # > flist=[(os.stat(x).st_mtime, x) for x in files] > > # > # Sort them. Sort will sort on mtime, then on filename > # > flist.sort() > # > # Extract a list of the filenames only and return it > # > return [x[1] for x in flist] > # > # or if you only want the basenames of the files > # > #return [os.path.basename(x[1]) for x in flist] > > > > -Larry Bates > And as in Peter Ottens glob.glob variation, this shortens considerably by using sort with key instead of a separate list flist: files.sort(key=lambda x:(os.stat(x).st_mtime, x)) Cheers, Jussi From paul at subsignal.org Sun Feb 18 23:40:12 2007 From: paul at subsignal.org (paul) Date: Mon, 19 Feb 2007 05:40:12 +0100 Subject: I need a crack for pyext1.2.5 plugin In-Reply-To: References: <1171853809.836540.157490@l53g2000cwa.googlegroups.com> Message-ID: Oliver Sosa Cano schrieb: > Sorry if this is the wrong place to make that question. It is the wrong place. > > Pyext is a plugin that acoplate with pydev, it's 'software privativo' > like said Stallman, but it's very interesting. You should ask Stallman how software developers should pay their bills and further ignore some of his drivel. > I have version 1.2.5. > I use Eclipse 'cos it's simply great!! > If somebody could tell me some alternative... The author of pydev-extension provides pydev FOR FREE!! If you want pydev-extension you should by a license. cheers Paul From tech-hr at smartcharter.com Tue Feb 27 01:54:47 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Mon, 26 Feb 2007 22:54:47 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: In article , Bruce Lewis wrote: > Tech HR writes: > > > (Actually, > > it's turning out to be hard to find Python programmers too, but it's > > easier to train a Java programmer or a Perler on Python than Lisp. > > Is this speculation or experience? A little of both. We're a pretty young company :-) From dave.opstad at monotypeimaging.com Wed Feb 21 10:41:30 2007 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Wed, 21 Feb 2007 07:41:30 -0800 Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <1171988959.628359.260710@l53g2000cwa.googlegroups.com> <7xk5yc7pnj.fsf@ruckus.brouhaha.com> Message-ID: In article <7xk5yc7pnj.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > [...] However, Python seems to use the -ed suffix for the > non-mutating versions of these functions, e.g. sorted(list) instead > of the mutating list.sort(). I've found this to be useful in my own Python libraries. For instance, a graphic object has move(), scale() etc. methods which mutate, and moved(), scaled() etc. methods which return new instances. It's English-specific, but still mnemonically useful. From fuzzyman at gmail.com Fri Feb 16 09:42:55 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Feb 2007 06:42:55 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: <1171636975.653884.122850@p10g2000cwp.googlegroups.com> On Feb 16, 2:01 pm, "Edward K Ream" wrote: > > Why won't it be possible to make 'print' in Python 3 that supports all > > the functionality of the current print statement, and then translate to > > that ? > > I saw an assertion to the effect that it wasn't possible - but no proof. > > As discussed in the original post, the problem is the reverse: the Python > 2.x print statement does not support the keyword args required by the pep, > so that print(foo) **in Python 2.x** can not simulate the effect of the > print statement with a trailing comma. Here is the theorum carefully stated > and proved. > > Theorem: is not possible to define a function called print in Python 3.x > such that > > A) print (whatever) is syntaxtically valid in Python 2.x and > > B) print(whatever) outputs what 'print whatever' outputs in Python 2.x for > all values of 'whatever'. > > Proof: > > It is impossible for the print function to simulate the effect of the print > statement with a trailing comma. Indeed, print ('line'), and print > ('line',) (note the position of the commas) are valid in Python 2.x, but > neither does what is wanted. And print('line',end='') is invalid in Python > 2.x. Let's look at some examples: > > 1. The following works (prints 'line after\n') in Python 2.x, but will not > suppress the newline in Python 3.x: > > print('line'), > print('after') > > 2. The following doesn't work in Python 2.x. (It prints > "('line',)\nafter"). > > print ('line',) > print ('after') > > 3. print ('line',end='') produces a syntax error in Python 2.x: > > print ('line',end='') > ^ > SyntaxError: invalid syntax > > That's the proof. Can you find a flaw in it? > I mentioned the 2to3 translator- the goal of which is *precisely* to allow you to write code that will run on Python 2.X and when translated run under Python 3.0. You then repeated the problem with the 'print' statement. It may be true that you won't be able to write code that runs untranslated on 2 and 3. That doesn't stop you writing code for Python 2.X, then translating a version for Python 3. (Uhm... indeed that's the point of 2to3.) So you only have one codebase to maintain and you can still use print... Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream... at charter.net > Leo:http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- From kpoman at gmail.com Mon Feb 26 10:32:27 2007 From: kpoman at gmail.com (kpoman at gmail.com) Date: 26 Feb 2007 07:32:27 -0800 Subject: ctypes and using c_char_p without NULL terminated string Message-ID: <1172503947.332129.60930@q2g2000cwa.googlegroups.com> Hi to all, I am trying to use some dll which needs some data types that I can't find in python. From the dll documentation, I am trying to use this: HRESULT IMKWsq::Compress ( [in] VARIANT rawImage, [in] short sizeX, [in] short sizeY, [out] VARIANT * wsqImage, [out, retval] short * result ) I then tried using the following python code to achieve this: # CODE START import os import sys from ctypes import * import win32con MKWSQ_OK = 0 MKWSQ_MEMORY_ALLOC_ERROR = (MKWSQ_OK+200) #// Memory allocation error MKWSQ_MEMORY_FREE_ERROR = (MKWSQ_OK+499) #// Memory disallocation MKWSQ_INPUT_FORMAT_ERROR = (MKWSQ_OK+700) #// Error in the format of the compressed data MKWSQ_NULL_INPUT_ERROR = (MKWSQ_OK+5000) #// input buffer is NULL MKWSQ_ROWSIZE_ERROR = (MKWSQ_OK+5003) #// Number of rows in the image must be betwen 64 and 4000 MKWSQ_COLSIZE_ERROR = (MKWSQ_OK+5004) #// Number of columns in the image must be between 64 and 4000 MKWSQ_RATIO_ERROR = (MKWSQ_OK+5005) #// The minimum compression ratio value is 1.6 and the maximum 80, usually 12 for 15 real MKWSQ_INPUT_PTR_ERROR = (MKWSQ_OK+5006) #// compress_buffer must be the address of a char pointer MKWSQ_OUTPUTSIZE_ERROR = (MKWSQ_OK+5007) #// compressed_filesize must be the address of a long MKWSQ_RATIO_PTR_ERROR = (MKWSQ_OK+5008) #// ratio_achieved must be the address of a float MKWSQ_NULL_OUTPUT_ERROR = (MKWSQ_OK+6000) #// compress_buffer has a NULL value MKWSQ_OUTPUT_ROWSIZE_ERROR = (MKWSQ_OK+6002) #// rows must be the adress of an int MKWSQ_OUTPUT_COLSIZE_ERROR = (MKWSQ_OK+6003) #// cols must be the adress of an int MKWSQ_OUTPUT_SIZE_ERROR = (MKWSQ_OK+6006) #// output_filesize must be the adress of a long MKWSQ_OUTPUT_PTR_ERROR = (MKWSQ_OK+6007) #// output_buffer must be the adress of a char* MKWSQ_DONGLE_ERROR = (MKWSQ_OK+9045) #// dongle or dongle driver is not present MKWSQ_DONGLE_TYPE_ERROR = (MKWSQ_OK+9046) #// the dongle licence does not authorize to use the function MKWSQ_LICENSE_ERROR = (MKWSQ_OK+133) #// invalid or nonexistent software license #Cargo la libreria e memoria _wsq = cdll.mkwsq def MKWsq_compress( iBuffer, iFreeBufferOption, iRows, iCols, iRatio, oCompressedBuffer, oCompressedFileSize, oRatioAchieved): ''' Esta es la funcion de compresion ''' return _wsq.MKWsq_compress(iBuffer, iFreeBufferOption, iRows, iCols, iRatio, 0, 0, byref(oCompressedBuffer), byref(oCompressedFileSize), byref(oRatioAchieved)) def MKWsq_decompress(iCompressedBuffer, oRows, oCols, oFileSize, oBuffer): '''Funcion que se encarga de descomprimir la huella''' return _wsq.MKWsq_decompress(iCompressedBuffer, 0, oRows, oCols, 0, 0, oFileSize, c_char_p(oBuffer)) def MKWsq_free(iCompressedBuffer): ''' Funcion para liberar la memoria alocada ''' return _wsq.MKWsq_free(iCompressedBuffer) if __name__ == '__main__': '''test del modulo''' #Prueba de compresion desde RAW fh=open("test.raw","r") imRaw=fh.read() fh.close() fSize=c_long() ratio=c_float(12.0) ratioAchieved=c_float() #imWSQ=c_ubyte(win32con.NULL) #declara la variable como NULL imWSQ=c_char_p('\x00'*(20*1024)) status=MKWsq_compress(imRaw, 1,416,416,ratio,imWSQ,fSize,ratioAchieved) print "Status=%d\tSize=%d bytes Ratio=%f"% (status,fSize.value,ratioAchieved.value) print repr(imWSQ) print len(imWSQ.value[:10]) filito=open("file.wsq","wb") filito.write(imWSQ[:fSize.value]) filito.close() # CODE END which gives me the following result: c:\>python MKWsq_new.py Status=0 Size=12735 bytes Ratio=13.589006 c_char_p('\xff\xa0\xff\xa8') 4 Traceback (most recent call last): File "MKWsq_new.py", line 65, in ? filito.write(imWSQ[:fSize.value]) TypeError: unsubscriptable object c:\> the problem is on this result line: c_char_p('\xff\xa0\xff\xa8') because of the c_char_p spec, it is a \x00 (null) character terminated string, but my result has some null characters on it. Which ctype should I then use to be able to retrieve the result from python ? Thanks in advance, Patricio From stargaming at gmail.com Fri Feb 2 23:40:39 2007 From: stargaming at gmail.com (Stargaming) Date: Sat, 03 Feb 2007 05:40:39 +0100 Subject: from... import... In-Reply-To: <9s28s29864vgkdbtevi8fna5h1r04ekgr9@4ax.com> References: <9s28s29864vgkdbtevi8fna5h1r04ekgr9@4ax.com> Message-ID: fatwallet961 at yahoo.com schrieb: > what's the from ... import keyword use for? > for example - from contenttype import getContentType > > import os > import sys > import getopt > import types > import re > import pprint > import logging > from contenttype import getContentType > > In Java what kind of statement is similar this? > > thanks http://docs.python.org/ref/import.html ("The first form of" and following, sixth paragraph) HTH, Stargaming From Hieu.D.Hoang at gmail.com Sat Feb 10 08:25:31 2007 From: Hieu.D.Hoang at gmail.com (Hieu.D.Hoang at gmail.com) Date: 10 Feb 2007 05:25:31 -0800 Subject: Glob returning an empty list when passed a variable In-Reply-To: References: <1171029831.052514.168790@k78g2000cwa.googlegroups.com> Message-ID: <1171113931.544838.103810@a75g2000cwd.googlegroups.com> On Feb 10, 3:32 pm, Steve Holden wrote: > > >>> "% s" % 'banana' > 'banana' > >>> "% s" % 1 > '1' > >>> "% s" % -1 > '-1' > >>> > With some number: In [2]: "% 3s" % 'a' Out[2]: ' a' Hieu From techtonik at gmail.com Sat Feb 10 06:48:31 2007 From: techtonik at gmail.com (techtonik) Date: 10 Feb 2007 03:48:31 -0800 Subject: Need a cross-platform way to execute binary In-Reply-To: References: <1171098220.101483.138910@q2g2000cwa.googlegroups.com> Message-ID: <1171108111.691268.168510@v45g2000cwv.googlegroups.com> On Feb 10, 12:03 pm, "Gabriel Genellina" wrote: > > Does anybody know simple cross-platform method of probing if > > executable binary is available and launching it. > > > Problem no.1: test if executable file is available > > I'll take windows platform as the most relevant in this case. > > os.access() doesn't handle env PATHEXT and can't detect if a given > > path would be executable or not. Here "executable" means file that > > could be be launched by system() (if there are any other ways - I'd be > > happy to know them) > > > Suppose I have "ufo2exe" executable two directories up. > >>>> os.access("../../ufo2map.exe", os.X_OK) > > True > > > However... > >>>> os.access("../../ufo2map", os.X_OK) > > False > > That's right - such file does not exist. On Windows, in general, X_OK is > the same as F_OK: for any existing file, whatever name or extension, > returns True. Permissions are managed thru ACL and this simple function > does NOT consider them. It shouldn't matter if the file exists or not. Quoting http:// docs.python.org/lib/os-file-dir.html: " X_OK Value to include in the mode parameter of access() to determine if path can be executed. " See - there is no "file" notation as only "path" is tested and "path" is pretty executable. I think this should be clarified in os.access() documentation to make the whole business less confusing if not implemented in interpreter itself. After all the purpose of cross- platform language is to free developer from writing platform-specific code. > > > But... > >>>> os.system("..\..\ufo2map") > > ---- ufo2map 1.0 ---- > > 0 > > (Beware of single \ on normal strings!) > Use win32api.FindExecutable; should return the full path to ufo2map.exe. > "foo.txt" would return notepad.exe (or whatever you have associated to > text files). That is exactly what would be launched by os.system("foo.txt") Why isn't it possible to integrate the functionality in os.access() - IIUC Python interpreter still uses Windows API itself on this platform. > > Problem no.2: launch executable file > > The same windows platform again. All python commands are using forward > > slashes for paths, but system doesn't handle this situation (it could > > at least try to convert immediate forward slashes to backwards) > > Use os.path.normpath on the filename. (If you got it from FindExecutable > above, that would not be needed) > > > os.access() thinks this file is executable, but os.system() fails ... > >>>> os.access("../../ufo2map.exe", os.X_OK) > > True > >>>> os.system("../../ufo2map.exe") > > '..' is not recognized as an internal or external command, > > operable program or batch file. > > 1 > > > the contrary - access() fails to tell this path can be launched, but > > file Is executable, ... > >>>> os.access("..\..\ufo2map", os.X_OK) > > False > > Same as above - such file does not exist. Same as above - access() tests path, not file, so the argument is not valid. > >>>> os.system("..\..\ufo2map") > > ---- ufo2map 1.0 ---- > > 0 > > Is there any workaround in Python or I have to stick with platforms- > > specific quirks? > > I'm using Python 2.4.2 > > I think you will have to treat each platform differently. Just for > starting, the concept of "executable" is not the same across platforms. > But you could make some generic functions (with different implementations > on different platforms). I would prefer to know as little about underlying platforms as possible. It would only be a big plus for Python. -- --t. From tiedon_jano at hotmail.com Tue Feb 20 08:31:21 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 20 Feb 2007 13:31:21 GMT Subject: file io (lagged values) newbie question In-Reply-To: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> Message-ID: hiro kirjoitti: > Hey there, I'm currently doing data preprocessing (generating lagged > values for a time series) and I'm having some difficulties trying to > write a file to disk. A friend of mine, wrote this quick example for > me: > > > tweaked code: > ------------------------------------------------------------------------------------------------------------------- > f=open('c:/kaka.txt','r') > array=f.readlines() > f.close() > f=open('c:/kakaDump.txt','w') > lineSize = 4 > skip = 4 > condition = 1 > startIndex = 0 > > for letter in array: > line = [] > startIndex = array.index(letter) > > for indexNum in range(startIndex, startIndex + (skip - 1), 1): > if indexNum > (len(array) - 1): > break > else: > line.append(array[indexNum]) > > for indexNum in range(startIndex + skip, (startIndex + > lineSize) + 1, 1): > if indexNum > (len(array) - 1): > break > else: > line.append(array[indexNum]) > > f.writelines(line) > > ------------------------------------------------------------------------------------------------------------------------------- > C:\>more kakaDump.txt > 1 > 2 > 3 > 5 > 2 > 3 > 4 > 6 > 3 > 4 > 5 > 74 > 5 > 6 > 5 > 6 > 76 > 77 > > For those familiar with neural networks, the input file is a time > series and the output file needs to have 3 lagged variables for > training and a (two time steps ahead) variable for the target. Ie: > > input file > 1 > 2 > 3 > 4 > 5 > 6 > 7 > > output file > 1 2 3 5 > 2 3 4 6 > 3 4 5 7 > 4 5 6 > 5 6 7 > 6 7 > 7 > > Thanks in advanced, > > > D. > I think your file kaka.txt lacks a CR-LF i.e. '\n' i.e. "Enter" after the last line. To get the desired output format you also need to drop the CR-LF:s after each line to have the required values printed on the same line. Here's my version of your code with a couple remarks added: #--------------------------------------------------------- f = open('kaka.txt','r') # The Windows root directory C:\ is a special directory # designed to be used by Windows itself. To put it # politely: it's unwise to do program development in # that directory array = f.readlines() f.close() # This drops the '\n' from each line: array = [x[:-1] for x in array] #print array f = open('kakaDump.txt','w') lineSize = 4 skip = 4 condition = 1 startIndex = 0 for letter in array: line = [] startIndex = array.index(letter) for indexNum in range(startIndex, startIndex + (skip - 1), 1): if indexNum > (len(array) - 1): break else: line.append(array[indexNum]) # This adds a space between each item in a row # and after the last item, but it's "only" a space: line.append(' ') for indexNum in range(startIndex + skip, (startIndex + lineSize) + 1, 1): if indexNum > (len(array) - 1): break else: line.append(array[indexNum]) # This completes the line: line.append('\n') f.writelines(line) f.close() #--------------------------------------------------------- I also have my own completely different version which to me looks cleaner than yours but as they say: "Beauty is in the eye of the beholder" #--------------------------------------------------------- lineSize = 4 lsm1 = lineSize - 1 f = open('kaka.txt','r') inData = f.read() f.close() inLst = inData.split() inCount = len(inLst) inLst += [' ']*lineSize print inLst f = open('kakaDump.txt','w') for ind,elem in enumerate(inLst): if ind == inCount: break for i in range(lsm1): f.write('%s ' % inLst[ind + i]) f.write('%s\n' % inLst[ind + lineSize]) f.close() #--------------------------------------------------------- HTH, Jussi From gagsl-py at yahoo.com.ar Thu Feb 8 11:31:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 8 Feb 2007 08:31:42 -0800 Subject: Referencing vars, methods and classes by name In-Reply-To: <7xveid6ni0.fsf@ruckus.brouhaha.com> References: <1170922726.753896.245140@j27g2000cwj.googlegroups.com> <7xbqk52gt8.fsf@ruckus.brouhaha.com> <7xveid6ni0.fsf@ruckus.brouhaha.com> Message-ID: <1170952302.866455.52220@a34g2000cwb.googlegroups.com> On 8 feb, 05:51, Paul Rubin wrote: > "Gabriel Genellina" writes: > > > obj.getattr(a)() > > > but even that is a bit ugly, depending. > > Surely you meant to say getattr(obj, a)() > > Yeah, darn. Counterintuitive. I keep making that error in my own > code too. Maybe I should put in an RFE. The "method" way is using __getattribute__ or __getattr__. A generic function helps on using it on objects of any kind - like len() Perhaps it was more important with old style classes. -- Gabriel Genellina From mmanns at gmx.de Fri Feb 23 11:39:11 2007 From: mmanns at gmx.de (Martin Manns) Date: Fri, 23 Feb 2007 11:39:11 -0500 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: <20070223113911.05dcc555@localhost> On Fri, 23 Feb 2007 09:52:06 -0600 Larry Bates wrote: > I quick search of Google turned up: > > http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg > http://calcrpnpy.sourceforge.net/clnum.html > http://gmpy.sourceforge.net/ Sorry that I did not point these out initially. + clnum seems to be slower and for speed may be compiled to wrap gmp so that it is just an additional layer between python and gmp . + gmpy is looking pretty unmaintained (dead) to me (newest update of cvs 10 months ago). + boost indeed is a quite nice C++ library. However, I fear that I would end up writing the python wrappers for operators (+ - * / min max cmp etc.) myself. I would like to avoid this since these operators should work correctly for any type (not just int and float) and I have little experience with verifying such generic code. The problems encountered in the mxNumber wrapper support this notion. Martin From gagsl-py at yahoo.com.ar Tue Feb 6 17:28:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 19:28:52 -0300 Subject: Help reading binary data from files References: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> Message-ID: En Tue, 06 Feb 2007 19:01:20 -0300, jeff escribi?: > I am stumped trying to read binary data from simple files. Here is a > code snippet, where I am trying to simply print little-endian encoded > data from files in a directory. > > for name in os.listdir(DOWNLOAD_DIR): > filename = s.path.join(DOWNLOAD_DIR, name) > if os.path.isfile(filename): > f = open(filename, 'rb') > while True: > ele = unpack(' print ele > > > When the code runs, 0 is always the data printed, but the data files > are not all zero. Looks fine to me... -- Gabriel Genellina From nszabolcs at gmail.com Wed Feb 7 16:25:45 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 7 Feb 2007 13:25:45 -0800 Subject: mplayer bug or python bug? In-Reply-To: References: Message-ID: <1170883545.215931.210470@s48g2000cws.googlegroups.com> Marco wrote: > The following code is my test program for control mplayer. > in movies/ there are about 20 movies, the code plays them in circle, > but mplayer will crash silently after a circle, the "sliently" means I > can handle popen2 without except, but no movie. i had some problem with mplayer slave mode too. everything worked ok, but after some movies i got "broken pipe" "caught signal xy" error message on stderr and mplayer quit. mplayer always crashed on the same files and always at the very end (which you normally don't notice since you only want to view 1 file so probably it has nothing to do with slave mode, but buggy mplayer + buggy files) my solution was: check for error and restart mplayer if it crashed (i parsed every output so i knew where are we in the playlist) btw if you just want to use the script to play files in loop, then mplayer has a -loop option as well. From lbates at websafe.com Tue Feb 20 18:43:53 2007 From: lbates at websafe.com (Larry Bates) Date: Tue, 20 Feb 2007 17:43:53 -0600 Subject: setup.py installation and module search path In-Reply-To: <1172010954.151670.274470@p10g2000cwp.googlegroups.com> References: <1172010954.151670.274470@p10g2000cwp.googlegroups.com> Message-ID: <4OGdnbwDvckpGkbYnZ2dnUVZ_qninZ2d@comcast.com> Russ wrote: > When I run setup.py to install a pure python package, is it supposed > to > automatically set my search path to find the installed modules? Or am > I > supposed to set my PYTHONPATH variable myself in my .bashrc file? > > And what if I don't have root priviledge? Then what is supposed to > happen? Can anyone give me a clue? Thanks. > I'm no expert, but I think what normally happens is the module gets installed into ../pythonxx/lib/site-packages/ and if it installs __init__.py file there they get automatically searched. At least that the way things work for me. -Larry From horpner at yahoo.com Thu Feb 15 11:37:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Feb 2007 17:37:18 +0100 Subject: Method overloading? References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> <1171519115.463977.220700@j27g2000cwj.googlegroups.com> Message-ID: On 2007-02-15, Steven D'Aprano wrote: >> def multiAccept( argOfVariousTypes ): >> if isinstance(argOfVariousTypes,int): >> # treat like an int >> elif isinstance(argOfVariousTypes,float): >> # treat like a float >> elif isinstance(argOfVariousTypes,(list,tuple)): >> # treat like a container > > Is that really called "overloading"? I've never (knowingly) > come across the term being used in that context before. I've > always known that as "multiple dispatch" or "polymorphism", > depending on whether you or the compiler handles the > dispatching. It's due to vague terminology that we're using. What the OP wanted to know about was static polymorphism of names based on function signatures, often refered to informally in the context of C++ as "function overloading", though it's really "identifier overloading where identifier refers to a function or member function". What Python provides is dynamic polymorphism of names with single-dispatch. I think. ;-) -- Neil Cerutti From http Mon Feb 19 03:23:51 2007 From: http (Paul Rubin) Date: 19 Feb 2007 00:23:51 -0800 Subject: How do I create an array of functions? References: Message-ID: <7xr6smpnc8.fsf@ruckus.brouhaha.com> "Steven W. Orr" writes: > I have a table of integers and each time I look up a value from the > table I want to call a function using the table entry as an index into > an array whose values are the different functions. I haven't seen > anything on how to do this in python. func_array = [f1, f2, f3] # array of functions index = table_lookup() func_array[index](x,y,z) # select a function and call it From larry.bates at websafe.com Fri Feb 2 09:19:53 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 02 Feb 2007 08:19:53 -0600 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: ardief wrote: > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] > > I have the feeling it's trivial, and I've scoured the group archives - > sets might be a possibility, but I'm not sure how to operate on a list > of lists with sets. > > This function also gives me what I want, more or less, but I don't > know how to make it run until it's covered all the possibilities, if > that makes sense... > > def sigh(list): > for a in list: > i = list.index(a) > if a != list[-1]: ##if a is not the last one, i.e. there is a > next one > n = alist[i+1] > if a[0] == n[0]: > a.append(n[1:]) > del alist[i+1] > > Sorry about the lengthy message and thanks for your suggestions - I'm > trying to learn... > One solution: l=[['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c','4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] d={} for k, v in l: if d.has_key(k): d[k].append(v) else: d[k]=[v] print "d=", d l=[x for x in d.items()] print l -Larry From redvasily at gmail.com Sun Feb 11 23:20:32 2007 From: redvasily at gmail.com (Vasily Sulatskov) Date: 11 Feb 2007 20:20:32 -0800 Subject: Saving PyOpenGl figures as ps In-Reply-To: <1171231889.667812.72930@q2g2000cwa.googlegroups.com> References: <1171231889.667812.72930@q2g2000cwa.googlegroups.com> Message-ID: <1171254032.597645.295920@v45g2000cwv.googlegroups.com> On Feb 12, 3:11 am, "Frank" wrote: > Hi, > > I installed pyopengl (opengl for python) on my linux box and > everything works fine. But now I want to save the generated images as, > e.g., ps or eps. How can I do that and how can I adjust the resolution > (if necessary)? This is probably simple but for some reason I can not > find out how to do that. > > I appreciate every hint! Well, that's not that simple. Search the web, there are several tutorials about PostScipt output. From Mark.Geyzer at gmail.com Sun Feb 11 07:58:27 2007 From: Mark.Geyzer at gmail.com (volcano) Date: 11 Feb 2007 04:58:27 -0800 Subject: How to access an absolute address through Python? In-Reply-To: References: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> <1171197574.776135.96980@k78g2000cwa.googlegroups.com> Message-ID: <1171198707.889681.177270@h3g2000cwc.googlegroups.com> On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch wrote: > In <1171197574.776135.96... at k78g2000cwa.googlegroups.com>, volcano wrote: > > On Feb 11, 2:21 pm, Ma?l Benjamin Mettler wrote: > >> volcano schrieb: > > >> > Can it be done, and if yes - how? > > >> Define address. Are you talking about URLs? File paths? Postal > >> addresses? Memory addresses? Whatever addresses? > >> I'm afraid the people on this list can't read your thoughts... > > > I presumed that "absolute" address somehow qualifies my question. If > > it is not - I was talking about physical computer memory, on PC - to > > be more specific. > > In pure Python it's not possible and even in C it might be difficult to > get an absolute *physical* memory address unless you run DOS. Modern > operating systems tend to use some virtualisation of memory. :-) > > What's your goal? What do you expect at the memory address you want to > access? > > Ciao, > Marc 'BlackJack' Rintsch My goal is to sync program with external equipment through a register defined as an absolute physical address. I know how to do it from C - was curious if it may be done from Python. Can it be done? Thanks, Mark From SoutoJohn at gmail.com Sun Feb 4 08:16:27 2007 From: SoutoJohn at gmail.com (SoutoJohn at gmail.com) Date: 4 Feb 2007 05:16:27 -0800 Subject: CTypes In-Reply-To: <1170592004.632364.65340@v33g2000cwv.googlegroups.com> References: <1170518516.080789.293110@v33g2000cwv.googlegroups.com> <1170544958.865802.120010@s48g2000cws.googlegroups.com> <1170592004.632364.65340@v33g2000cwv.googlegroups.com> Message-ID: <1170594987.511527.215030@p10g2000cwp.googlegroups.com> On Feb 4, 7:26 am, "Mark" wrote: Hey, I really appreciate you responding to my post. I've been on this problem for some days now and it was getting to me. Sad that pywinauto doesn't run on Win98SE, are there any other Python libraries for 'automating' Windows COM? If not I looked into AutoIt, which is a Windows automation tool. It has a DLL which I believe contains all the methods it does in the scripting language it has. I read over the (yeah, 'the'. I keep finding the exact same tutorial) ctypes tutorial, and I don't get it. I don't get how to load a DLL. So if I had a script file 'test.py' and a DLL 'AutoIt3X.DLL' in the same folder, how could I load it? The tutorial did something like dll=windll.kernel32, which I understands loads the kernel but I don't see how I could apply that to load AutoIt3X. Thanks in advanced. From m_tayseer82 at yahoo.com Mon Feb 26 05:43:23 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Mon, 26 Feb 2007 02:43:23 -0800 (PST) Subject: newbie question(file-delete trailing comma) In-Reply-To: <860807.3780.qm@web7805.mail.in.yahoo.com> Message-ID: <507974.41978.qm@web31101.mail.mud.yahoo.com> in_file = open('in.txt') out_file = open('out.txt', 'w') for line in in_file: print >> out_file, line.strip(',') kavitha thankaian wrote: hi, i have a file which has the contents as follows: a,b,c,d, a1,b1,c1,d1, a2,b2,c2,d2, i would like to delete all the trailing commas,, if someoneknows pls help me,, kavitha --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Now that's room service! Choose from over 150,000 hotels in 45,000 destinations on Yahoo! Travel to find your fit. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Sat Feb 3 16:21:00 2007 From: paddy3118 at netscape.net (Paddy) Date: 3 Feb 2007 13:21:00 -0800 Subject: raise or not to raise [Newbie] In-Reply-To: References: Message-ID: <1170537660.217174.206760@j27g2000cwj.googlegroups.com> On Feb 3, 9:07 pm, Jacol wrote: > I understand that author generated exception and than extracted the name of > function from the exeption. But is any sens in using exeptions service if > we have smthing simpler: just print for example? In my opinion no, it > doesn't make sens. > > Jacek You can terminate your program by raising an exception that you don't otherwise catch and handle. e.g: >>> def with_error(): ... print "Print this then raise an error" ... raise Exception("Bye Bye") ... >>> >>> with_error() Print this then raise an error Traceback (most recent call last): File "", line 1, in File "", line 3, in with_error Exception: Bye Bye >>> Notice how the traceback, automatically added to un-caught exceptions, shows were it was raised. Your link points to a very old version of Python and error handling has changed. Please use a more recent tutorial such as THE Python tutorial here: http://docs.python.org/tut/node10.html - Paddy. From aleaxit at gmail.com Fri Feb 23 18:27:07 2007 From: aleaxit at gmail.com (aleaxit at gmail.com) Date: 23 Feb 2007 15:27:07 -0800 Subject: Rational numbers In-Reply-To: <1172260810.779025.135670@j27g2000cwj.googlegroups.com> References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> Message-ID: <1172273227.863743.155210@p10g2000cwp.googlegroups.com> On Feb 23, 12:00 pm, cas... at comcast.net wrote: ... > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of > > > cvs 10 months ago). > > I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex > has not updated cvs with the fix. Heh, I see why one might get that impression -- I'm in the process of moving gmpy from sourceforge (where I find it harder and harder, and ever more problematic, to work) to code.google.com 's new hosting facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and particularly including your fix, Case) is already available at http://code.google.com/p/gmpy/ but I have made no official announcement yet (partly because what's available is yet limited: sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX 10.4 on Macs with intel processors)... building binaries for Windows (not having a Windows machine or development system) or Universal binaries for the Mac (due to problems building Universal versions of the underlying GMP in its latest, 4.2 incarnation... I'm running out of PPC-based Macs, and have none left with MaxOSX 10.3...) is much more problematic for me. To call this (Google Code) release 1.02, with a "1.04" (?) out from another source, may be confusing, but I'd rather not "force" the number upwards I do have one new co-owner on the Google Code "version" of gmpy (Chip Turner, once author of a similar GMP wrapper for perl, now a Python convert and a colleague of mine) but I suspect that won't make the building of Windows (and Universal Mac) binaries much easier. If anybody who has easy access to Microsoft's MSVC++.NET (and is willing to try building GMP 4.2 with/for it), or a PPC Mac with XCode installed (possibly with MacOSX 10.3...), wants to volunteer to build "the missing binaries" for the platforms that the current owners of gmpy can't easily support, we could complete, test and release the definitive 1.02, and move on with the development (I could get enthusiastic about this again, if I could develop just the sources, and the binaries for the one architecture I really use -- Macs w/intel -- rather than strive each time with binaries for architectures that are quite a pain for me...!-). Anybody who's interested in helping out is welcome to mail me and/or use the "wiki" and "issues" entry of the Google Code gmpy site... Thanks, Alex From fredrik at pythonware.com Thu Feb 15 07:47:17 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Feb 2007 13:47:17 +0100 Subject: How much memory used by a name References: <45d36eea$0$24957$426a74cc@news.free.fr> <61d0e2b40702141241o188b710bg408b1a4c703183a0@mail.gmail.com> Message-ID: Bernard Lebel wrote: > Bruno: good question. We're talking about text files that can have > 300,000 lines, if not more. Currently, the way I have coded the file > writing, every line calls for a write() to the file object, which in > turns write to the text file. The file is on the network. assuming an average line length of 30 (for program code) to 60-80 characters (for human text), that's no more than 12-24 megabytes of data. few modern computers should have any trouble holding that in memory. just build the list in memory, and use a single "writelines" call to write everything to disk. (alternatively, try write("".join(data)). that'll use twice as much memory, but may be a little bit faster) > This is taking a long time, and I'm looking for ways to speed up this > process. I though that keeping the list in memory and dropping to the > file at the very end could be a possible approach. chances are that you're already I/O bound, though... From Hobbes2176 at yahoo.com Wed Feb 21 15:49:35 2007 From: Hobbes2176 at yahoo.com (Mark E. Fenner) Date: Wed, 21 Feb 2007 20:49:35 GMT Subject: Debug Build of Python Message-ID: Hi all, Just curious how to get an "all bells and whistles" debug build of python. In the source for 2.4.3, I see the following debug related options: >From README: (1) e.g. "make OPT=-g" will build a debugging version of Python on most platforms (2) Additional debugging code to help debug memory management problems can be enabled by using the --with-pydebug option to the configure script. >From Misc/SpecialBuilds.txt: This file describes some special Python build types enabled via compile-time preprocessor defines. Here we have a bunch of defines documented. Where should these be be set? Is there a particular .h file? Are any of them implied by the debugging options to make and ./configure? Regards, Mark From free at hbghhixf.com Thu Feb 1 06:12:36 2007 From: free at hbghhixf.com (Play UK lotto + Euromillions For FREE) Date: Thu, 01 Feb 2007 11:12:36 GMT Subject: Play UK Lotto + Euromillions fo FREE Message-ID: Play the UK lotto + Euromillions for free. see www.carlnalex.pwp.blueonder.co.uk From bignose+hates-spam at benfinney.id.au Thu Feb 1 21:19:16 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 13:19:16 +1100 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> Message-ID: <87ododuwrf.fsf@benfinney.id.au> John Nagle writes: > Just a followup. I'm still trying to get Python, MySQL, MySQLdb, > M2Crypto, and maybe mod_python to work on a shared hosting server. >From your description in the rest of the message, it seems that it's the *hosting providers* who are unable to do this, not you. > And these are companies that say they support Python. > > Python still isn't ready for prime time in the web hosting world. That doesn't follow. It's just as valid to say that the web hosting providers (that you've interacted with so far) aren't ready to support the Python functionality you want. -- \ "To be is to do" -- Plato | `\ "To do is to be" -- Aristotle | _o__) "Do be do be do" -- Sinatra | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Thu Feb 22 05:07:27 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Feb 2007 21:07:27 +1100 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: On Thu, 22 Feb 2007 16:29:17 +1100, Peter Mayne wrote: > Why use print in the interactive interpreter? Just type the expression. Many reasons. Here are four: >>> print None None >>> None >>> print 0.1 0.1 >>> 0.1 0.10000000000000001 >>> print 'null = \0' null = >>> 'null = \0' 'null = \x00' >>> print 1, 2, 3 1 2 3 >>> 1, 2, 3 (1, 2, 3) I'm sure you can find your own examples. -- Steven. From gagsl-py at yahoo.com.ar Thu Feb 1 15:21:20 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 17:21:20 -0300 Subject: Quad Perspective Transformation References: <1170348396.754807.206560@m58g2000cwm.googlegroups.com> Message-ID: En Thu, 01 Feb 2007 13:46:37 -0300, Kamilche escribi?: > I have a need to tile a bitmap across an arbitrary quadrilateral, and > apply perspective to it. > The Python Imaging Library (PIL) has an undocumented function that > might work, but I can't figure out how to make it work. You're > supposed to pass it 8 parameters, a b c d e f g h . I don't know exactly how it's implemented, but the usual perspective transformation matrix has exactly 8 non zero parameters. Any text on computer graphics should cover it. My first hit on Google: http://bishopw.loni.ucla.edu/AIR5/2Dperspective.html -- Gabriel Genellina From gagsl-py at yahoo.com.ar Thu Feb 15 13:36:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Feb 2007 15:36:35 -0300 Subject: Recursive calls and stack References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: En Thu, 15 Feb 2007 13:37:19 -0300, Neil Cerutti escribi?: > On 2007-02-15, Gabriel Genellina wrote: >> En Wed, 14 Feb 2007 10:41:53 -0300, Neil Cerutti >> escribi?: >>> So the effect is that mutual recursion isn't actually any >>> harder. >> >> But some kind of language support is required in this case. At >> least I don't know how to handle mutual recursion (apart from >> inlining one function inside the other...). But I'm certainly >> not a "program transformation guru" (neither a novice!) so I >> would not be surprised if someone says it can be done... > > What happens (using the model of an imaginary virtual machine, > perhaps like the Python interpreter) is the following. > > A normal function call pushes a call-frame onto a stack. The > call-frame contains information necessary for returning from the > function, and usually a place to store its local variables and > parameters. > > A function called in "tail" position simply overwrites the > current call-frame with the new one instead of pushing it onto > the stack. This is the "kind of language support" menctioned. For tail recursion you don't require that support. -- Gabriel Genellina From jm.suresh at gmail.com Wed Feb 14 01:09:37 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 13 Feb 2007 22:09:37 -0800 Subject: Recursive calls and stack Message-ID: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Hi, I have a program which literately finds the object that overlapping a point. The horizontal and vertical search are called recursively from inside each other. Is this way of implementation fill the stack space with the local variables inside each call. If this is not good, is there a better way to implement? Or python itself will understand that the calls happen in the last line, so local variables need not be pushed into the stack? def find_point(pt): return _hor_search(pt, random_obj) def _hor_search(pt, obj): ... object = ... ... if object meets some condition: return object else: return _ver_search(pt, object) def _ver_search(pt, obj): ... object = ... ... if object meets some condition: return object else: return _hor_search(pt, object) - Suresh From jjlee at reportlab.com Tue Feb 27 06:31:27 2007 From: jjlee at reportlab.com (John J. Lee) Date: Tue, 27 Feb 2007 11:31:27 +0000 (GMT Standard Time) Subject: Job Ad: Full-time Python software developer, Wimbledon, London, England Message-ID: `ReportLab `_ (Wimbledon, London, England) ==================================================================== **Job Description**: ReportLab develop enterprise reporting and document generation solutions using cutting-edge Python technology, and have a growing business with an excellent blue chip customer base. You may also know us from our open source PDF and graphics library... We are looking for a full-time Python software developer for immediate start. We are now developing a new generation of applications to publish PDF on demand for specific vertical markets in the travel and financial services industries using our own core products. These involve flexible admin interfaces to let customers enter and approve data prior to publishing with our own PDF products. We are making use of the very latest and best ideas in web development to help create value for our customers and a scalable business model for ourselves. There will be opportunities for travel to exotic locations to visit travel industry customers. We're looking for a good all-rounder to join our team and work on this, as well as many other projects. The ideal candidate will either be a **graduate or have up to 3 years experience** and will have the following skills: - Python programming - or enough evidence of skill elsewhere to persuade us you can learn it quickly - Good analysis skills - the ability to listen to customers, figure out where the value lies, and help decide what to build in the first place - Understanding of web frameworks, databases, XML. Django experience is a plus - Know CSS and HTML (an eye for visual design is a plus) - Know JavaScript beyond the usual form validation (AJAX a plus) - Have the common sense to know when coding is NOT the answer You must have good written English, good aptitude for programming, and an ability to Get Things Done. You must be eligible to work in the UK, and have a passport allowing travel to most world locations. Driving license is also an advantage. You will get responsibilities which are not possible in large companies including a chance to work with the latest and best technologies; to see substantial, cutting-edge projects from commencement to delivery with world class clients; and to help design and roll out entire software services with fantastic upside potential. **What Python is used for**: Just about everything. * **Contact**: Alisa Pasic * **E-mail contact**: vacancies at reportlab.com * **Web**: http://www.reportlab.com/careers.html John From http Thu Feb 22 13:36:19 2007 From: http (Paul Rubin) Date: 22 Feb 2007 10:36:19 -0800 Subject: How to covert ASCII to integer in Python? References: Message-ID: <7xd542qbto.fsf@ruckus.brouhaha.com> "John" writes: > I just found ord(c), which convert ascii to integer. > Anybody know what the reverse is? chr(i) From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 16:03:13 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 28 Feb 2007 22:03:13 +0100 Subject: Question about raise and exceptions. In-Reply-To: References: Message-ID: <45e5e640$0$18215$426a74cc@news.free.fr> Daniel Klein a ?crit : > On Wed, 28 Feb 2007 13:48:54 -0500 (EST), "Steven W. Orr" > wrote: > > >>When I run it I get this: >> >>884 > ./t_fsm.py >>Traceback (most recent call last): >> File "./t_fsm.py", line 3, in ? >> from fsm import * >> File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76 >> raise TransitionError, self.curr_state, newstate, "Going to error >>state %d from state %d" % (self.curr_state, newstate) >> ^ >>SyntaxError: invalid syntax > > > The arguments for TransitionError must be a tuple, Err... > eg: > > msg = "Going to error state %d from state %d" % (self.curr_state, > newstate) > raise TransitionError(self, curr_state, newstate, msg) Where did you see a tuple here ? You're code is *calling* TransitionError, passing it the needed arguments. Note that it's the correct syntax - but not the correct explanation !-) From NikitaTheSpider at gmail.com Thu Feb 8 14:44:49 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 08 Feb 2007 14:44:49 -0500 Subject: postgres backup script and popen2 References: <1170951829.472924.65040@q2g2000cwa.googlegroups.com> Message-ID: In article <1170951829.472924.65040 at q2g2000cwa.googlegroups.com>, "Gabriel Genellina" wrote: > On 8 feb, 10:27, Ma?l Benjamin Mettler wrote: > > > flupke schrieb: > > > i made a backup script to backup my postgres database. > > > Problem is that it prompts for a password. It thought i > > > could solve this by using popen2. > > > > Use pexpect:http://pexpect.sourceforge.net/ > > pexpect could work. But a better way would be to supply the password > on the command line. I don't know how postgres does that things, but I > hope there is some way to automate the backup process... See the Postgres documentation for the .pgpass file. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From Mike.Dwyer at globalpay.com Tue Feb 6 12:16:47 2007 From: Mike.Dwyer at globalpay.com (Dwyer, Mike # ATLANTA) Date: Tue, 6 Feb 2007 12:16:47 -0500 Subject: Testing a website with HTTPS login and cookies Message-ID: Did you ever get a response to your posting on "Testing a website with HTTPS login and cookies"? The reason I ask is that I need to do a similar thing, and am not being very successful getting pointers or sample code. Any response appreciated. /mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at cosc.canterbury.ac.nz Sat Feb 3 19:20:02 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 04 Feb 2007 13:20:02 +1300 Subject: Decimating Excel files In-Reply-To: References: Message-ID: <52kn9eF1odticU1@mid.individual.net> gonzlobo wrote: > 2. Decimate an Excel file & write... say every other line (user > selectable)... to a new file. Every other line would be bicimating or something, wouldn't it? -- Greg From ed at leafe.com Mon Feb 12 10:32:21 2007 From: ed at leafe.com (Ed Leafe) Date: Mon, 12 Feb 2007 10:32:21 -0500 Subject: Newbie Question In-Reply-To: <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> References: <12sn8clg5iqlp81@corp.supernews.com> <1170976573.303441.27460@k78g2000cwa.googlegroups.com> <1171025546.002411.213190@q2g2000cwa.googlegroups.com> <9bf79$45cc71cb$d443bb3a$1116@news.speedlinq.nl> <1171282541.900959.261020@a34g2000cwb.googlegroups.com> <8a0cd$45d080c5$d443bb3a$12479@news.speedlinq.nl> Message-ID: <4FC28EE0-86B6-44D4-A005-20FE288077B3@leafe.com> On Feb 12, 2007, at 9:59 AM, Stef Mientki wrote: > but to be honest ... > ... I never even tried to write a GUI in Python, ... > ... just looked at others examples, > ... and still not seen what I can perform in Delphi ;-) You should definitely look at our product: Dabo. Both myself and my partner come from a desktop application background in which GUI tools made it easy to focus on what the app was doing instead of worrying about if it would look like you think it will look when writing the UI in code. Dabo is still a work in progress; we have most of the individual tools working well, and are just beginning to put them all together in a full IDE. Take a look at our screencasts to see Dabo in action; I'd recommend the more recent ones, as they show the current state of the tools: Building a Database Application using the Dabo Class Designer (Parts 1 & 2) http://leafe.com/screencasts/dataenvironment1.html http://leafe.com/screencasts/dataenvironment2.html Populating a Grid Using Business Objects http://leafe.com/screencasts/populategrid.html -- Ed Leafe -- http://leafe.com -- http://dabodev.com From gagsl-py at yahoo.com.ar Sat Feb 17 18:00:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 20:00:19 -0300 Subject: how to use Dispatch to open an application in win32com.client References: <1171679786.355275.191860@h3g2000cwc.googlegroups.com> <1171745243.399770.259180@k78g2000cwa.googlegroups.com> Message-ID: En Sat, 17 Feb 2007 17:47:23 -0300, vithi escribi?: > Hi > Since I haven't see any help or tutorial on com there is a application > is installed in the server I am login to the server then what code do > I have to implement to launch the application registered in a server. > how do I write a code to tell my computer to go in to the perticular > server and launch program "XYZ " Try to explain a bit better what do you want to do. What is "the server"? Do you want to open and execute a program on "another" computer? Or is it on the "same" computer? > do you think this code alone enough to go and look for xyz > application in the server, I don't get it > Give me any sample code or more help. It help me a lot. > object = win32com.client.Dispatch("xyz.Application") Does the manual for "xyz" say that it is a COM application? Did someone told you that "xyz" works that way? Did you find "xyz" actually registered as a COM application? If not, forget about that line, won't work at all. -- Gabriel Genellina From __peter__ at web.de Wed Feb 21 06:28:34 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Feb 2007 12:28:34 +0100 Subject: Sorting directory contents References: Message-ID: Wolfgang Draxinger wrote: > I got, hmm not really a problem, more a question of elegance: > > In a current project I have to read in some files in a given > directory in chronological order, so that I can concatenate the > contents in those files into a new one (it's XML and I have to > concatenate some subelements, about 4 levels below the root > element). It all works, but somehow I got the feeling, that my > solution is not as elegant as it could be: > > src_file_paths = dict() > for fname in os.listdir(sourcedir): > fpath = sourcedir+os.sep+fname > if not match_fname_pattern(fname): continue > src_file_paths[os.stat(fpath).st_mtime] = fpath > for ftime in src_file_paths.keys().sort(): > read_and_concatenate(src_file_paths[ftime]) > > of course listdir and sorting could be done in a separate > function, but I wonder if there was a more elegant approach. If glob.glob() is good enough to replace your custom match_fname_pattern() you can save a few steps: pattern = os.path.join(sourcedir, "*.xml") files = glob.glob(pattern) files.sort(key=os.path.getmtime) for fn in files: read_and_concatenate(fn) Peter From sickcodemonkey at gmail.com Tue Feb 6 20:18:07 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 6 Feb 2007 20:18:07 -0500 Subject: Dictionary/Hash question In-Reply-To: References: <2adc542f0702061531g7504de83ob01b56933794a37e@mail.gmail.com> Message-ID: <2adc542f0702061718h5a943312id61c3ac77c074a95@mail.gmail.com> I have never seen this "with open(fname,'r') as finput:" It is actually throwing an error . Do I have to import a special library to use this? File "dictNew.py", line 23 with open(fname,'r') as finput: ^ SyntaxError: invalid syntax On 2/6/07, Gabriel Genellina wrote: > > En Tue, 06 Feb 2007 20:31:17 -0300, Sick Monkey > escribi?: > > > Even though I am starting to get the hang of Python, I continue to find > > myself finding problems that I cannot solve. > > I have never used dictionaries before and I feel that they really help > > improve efficiency when trying to analyze huge amounts of data (rather > > than > > having nested loops). > > You are right, a list is not the right data structure in your case. > But a dictionary is a mapping from keys to values, and you have no values > to store. > In this case one should use a set: like a list, but without ordering, and > no duplicated elements. > Also, it's not necesary to read all lines at once, you can process both > files line by line. And since reading both files appears to be the same > thing, you can make a function: > > def mailsfromfile(fname): > result = set() > with open(fname,'r') as finput: > for line in finput: > mails = some_regular_expression.findall(line) > if mails: > result.update(mails) > return result > > mails1 = mailsfromfile(f1name) > mails2 = mailsfromfile(f2name) > > for mail in mails1 & mails2: # & = set intersection, mails present on both > files > # write mail to output file > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Tue Feb 20 16:03:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 20 Feb 2007 22:03:43 +0100 Subject: file io (lagged values) newbie question In-Reply-To: References: <1171952262.579752.179280@k78g2000cwa.googlegroups.com> <1171984082.488529.76040@p10g2000cwp.googlegroups.com> Message-ID: <45db5ac8$0$7473$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 20 Feb 2007 07:08:02 -0800, John Machin wrote: > > >>>def write_series(data, f): >>> """Write a time series data to file f. >>> >>> data should be a list of integers. >>> f should be an already opened file-like object. >>> """ >>> # Convert data into a string for writing. >>> s = str(data) >>> s = s[1:-1] # strip the leading and trailing [] delimiters >>> s = s.replace(',', '') # delete the commas >>> # Now write it to the file object >>> f.write(s) >>> f.write('\n') >> >>And that's not cruft? > > > No. Why do you think it is crufty? Because it is ? > > Would it be less crufty if I wrote it as a cryptic one liner without > comments? > > f.write(str(data)[1:-1].replace(',', '') + '\n') Nope. It's still a WTF. > Okay, it depends on the string conversion of a list. Nope. It depends on the *representation* of a list. > But that's not going > to change any time soon. > >>Try this: f.write(' '.join(str(x) for x in data) + '\n') > > > That will only work in Python 2.5 or better. Really ? Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> " ".join(str(x) for x in range(10)) '0 1 2 3 4 5 6 7 8 9' >>> From robert.kern at gmail.com Wed Feb 7 16:33:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 07 Feb 2007 15:33:57 -0600 Subject: string.find for case insensitive search In-Reply-To: References: <1170881616.244669.116220@q2g2000cwa.googlegroups.com> Message-ID: Don Morrison wrote: > lower() is also deprecated :) oh well The string method .lower() is not deprecated. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bdesth.quelquechose at free.quelquepart.fr Mon Feb 26 16:01:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 26 Feb 2007 22:01:35 +0100 Subject: about framework In-Reply-To: <1172516247.711812.301390@8g2000cwh.googlegroups.com> References: <1172516247.711812.301390@8g2000cwh.googlegroups.com> Message-ID: <45e342ef$0$29385$426a74cc@news.free.fr> raf a ?crit : > On Feb 24, 10:09 pm, memcac... at aol.com wrote: > >>Python has some web framework.I'm not familiar with all of them. >>Do you think which is best popular of them?Thanks. >>


**************************************
AOL now offers free >>email to everyone. Find out more about what's free from AOL athttp://www.aol.com. > > > take a look at http://djangoproject.org > This answers the "popular" part of the question. For the "best" part, look here : http://pylonshq.com/ !-) From facundo at taniquetil.com.ar Tue Feb 27 07:11:41 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Tue, 27 Feb 2007 12:11:41 +0000 (UTC) Subject: Bypassing __setattr__ for changing special attributes References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> <1171955882.929647.86700@v33g2000cwv.googlegroups.com> Message-ID: Ziga Seilnacht wrote: >>>> object.__setattr__(f, '__class__', Bar) >>>> f.__class__ is Bar > True Interesting, but... why I must do this? And, I must *always* do this? With Foo and Bar like the OP coded (just two new style classes, f is instance of Foo), see this: >>> f <__main__.Foo object at 0xb7d1280c> >>> setattr(f, '__class__', Bar) >>> f <__main__.Foo object at 0xb7d1280c> Ok, didn't work, try your way: >>> object.__setattr__(f, '__class__', Bar) >>> f <__main__.Bar object at 0xb7d1280c> Wow! Ok, but getting back to Foo, with the *former* method: >>> setattr(f, '__class__', Foo) >>> f <__main__.Foo object at 0xb7d1280c> I can't explain this to myself, :( Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From attn.steven.kuo at gmail.com Mon Feb 26 21:19:20 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 26 Feb 2007 18:19:20 -0800 Subject: classobj? In-Reply-To: References: Message-ID: <1172542760.288738.72550@8g2000cwh.googlegroups.com> On Feb 26, 5:43 pm, Venky wrote: > Hi, > > I am trying to create classes at runtime based on input from a textfile. > I am trying to use the function new.classobj. I am able to create the > new classes successfully, however I fail to understand on how to add > this new class to the current dictionary. > > cl = new.classobj('SomeClass', (BaseClass, ), {}) > > After this call, how do I instantiate SomeClass? > > I understand cl() will instantiate this, however this defeats my > purpose, since the name of the class is obtained at runtime. > Do you mean that you want to add it to globals()? globals()['SomeClass'] = cl myinst = SomeClass() print isinstance(myinst, SomeClass) print isinstance(myinst, BaseClass) -- Hope this helps, Steven From h at realh.co.uk Sat Feb 3 19:31:25 2007 From: h at realh.co.uk (Tony Houghton) Date: Sun, 4 Feb 2007 00:31:25 +0000 (UTC) Subject: Determining encoding of a file References: Message-ID: In , Ben Finney wrote: > Tony Houghton writes: > >> In Linux it's possible for filesystems to have a different encoding >> from the system's setting. Given a filename, is there a (preferably) >> portable way to determine its encoding? > > If there were, PEP 263 would not be necessary. > > > > It's possible to *guess*, with no guarantee of getting the right > answer; but it's far better to be explicitly *told* what the encoding > is. That seems to be specific to the encoding used in py source files anyway. What I want to be able to do is guess the encoding of any file for loading into a text editor based on gtksourceview which is pure utf-8. The best I can do is assume it's in the system encoding with locale.getdefaultlocale()[1]. Come to think of it, I wouldn't really be any better off knowing if the filesystem has a diferent encoding anyway because it doesn't necessarily determine what's used in the contents of its files, only its filenames. And Linux at least seems to be able to translate those on the fly. -- TH * http://www.realh.co.uk From robert.kern at gmail.com Wed Feb 28 00:40:52 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Feb 2007 23:40:52 -0600 Subject: f2py and Fortran90 gfortran_filename error In-Reply-To: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> References: <1172639755.691509.204760@v33g2000cwv.googlegroups.com> Message-ID: Tyler wrote: > Hello All: > > Since my last post I have attempted to use the f2py program which > comes with numpy. It's better to ask these questions on numpy-discussion, instead. There are more f2py users per capita there. http://www.scipy.org/Mailing_Lists > I am able to create a .so file fine; > however, when I import it into Python, I receive the following > message: > >>>> import matsolve2 > Traceback (most recent call last): > File "", line 1, in ? > ImportError: ./matsolve2.so: undefined symbol: _gfortran_filename > > > The steps I used to create the matsolve2.so file are as follows: > > (1) Created a Fortran90 program matsolve.f90 > > Note: The program compiles fine and prints the proper output for the > simple matrix specified. I have also attached below the file > matsolve.f90 if it helps at all. > > (2) f2py matsolve.f90 -m matsolve2 -h matsolve2.pyf > (3) f2py -c matsolve2.pyf --f90exec=/usr/bin/gfortran matsolve.f90 > > Note: I had to specify the f90 path as f2py did not automatically find > it. You want to specify the *kind* of Fortran compiler such that f2py knows what compile/link flags to use. Only use the --f90exec option to inform f2py that the actual executable is named something odd or is in an unexpected place, like /opt/gfortran/bin/gfortran-4.3, for example. The correct option to use is --fcompiler=gnu95 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nospamformeSVP at gmail.com Tue Feb 20 10:48:07 2007 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 20 Feb 2007 10:48:07 -0500 Subject: Found a product for running Python-based websites off CDROM -have anybody tried it? In-Reply-To: References: Message-ID: David Wishnie wrote: > Hello, > > Recently I've found a product that allows to create CDs or DVDs with > mod_python -based websites > (and CGI python of course) so that apache-based webserver, python and > mod_python are run directly > off CD on Windows, MacOS X and Linux at the same time (also it seems > to support perl, java, > php and mysql + SQLite as databases). > > http://www.stunnix.com/prod/aws/overview.shtml > > Have anybody tried it? I'm considering to use it for several projects. > > Thanks, > David > That is an expensive product ($789) especially considering it mostly consists of FOSS pieces. I found XAMPP, a FOSS, that is almost the same thing: http://portableapps.com/apps/development/xampp and this thread for getting mod_python running (scroll down a bit to the second post): http://www.apachefriends.org/f/viewtopic.php?t=21169&highlight=python I have not tried this yet. Don. From bdesth.quelquechose at free.quelquepart.fr Wed Feb 7 16:08:42 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Feb 2007 22:08:42 +0100 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170860862.438897.244820@a75g2000cwd.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> <1170780175.118806.11700@k78g2000cwa.googlegroups.com> <45c8d18d$0$418$426a34cc@news.free.fr> <1170795607.938431.144340@p10g2000cwp.googlegroups.com> <45c8f5b5$0$19714$426a74cc@news.free.fr> <1170854927.013819.320020@a75g2000cwd.googlegroups.com> <1170860862.438897.244820@a75g2000cwd.googlegroups.com> Message-ID: <45ca38ba$0$30127$426a74cc@news.free.fr> jeremito a ?crit : (snip) >> >>Thanks again! Sometimes the problem is simply not knowing where to >>find the documentation, http://python.org/doc is usually a good start !-) >>or finding the right portion of the >>documentation. Yes, this is not always obvious. FWIW, browsing docs is probably the most time-consuming task of programmers. > One more question. I will be asking for the value of cs.xT *many* > (~millions) times. Therefore I don't want it's value to be calculated > on the fly. As Jussi said, first make it right. And then, *if* you have a *real* performance problem, profile your code to find where bottlenecks really are. > How can I set the value of xT whenever xS, xF, or xG are > changed, but not allow it to be set directly? From the example given > previously, it seems like it can't be done this way. A naive solution might be to turn all these attributes into properties, so you could recompute and store the values of xA and xT each time xS, xF or xG are modified. The example I gave you should be enough to get you started here. But beware: in Python, function calls are somewhat expansive, so you may end up slowing down your code. Once again, first focus on cleanly solving the problem, and if *and only if* you have objective performance problems, then *profile* your code before trying to solve the wrong problem. From http Tue Feb 20 21:14:56 2007 From: http (Paul Rubin) Date: 20 Feb 2007 18:14:56 -0800 Subject: Python 3.0 unfit for serious work? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> Message-ID: <7x1wkkxnmn.fsf@ruckus.brouhaha.com> John Nagle writes: > There's always the possiblity that Python 3 won't happen. Look at > what happened with Perl 6. That's been talked about for > seven years now. The user base just wasn't interested. > Perl 5 was good enough, and users migrated to PHP for the > little stuff and other languages for the bigger stuff. > As Wikipedia says, "As of 2007, Perl 6 was still under development, > with no planned completion date." I like to think PyPy will replace CPython as the main Python implementation. Python 3.0 can then fork the language fairly radically, like C++ vs C (ok, not so attractive an example) or Scheme vs Lisp. Both dialects would stay active. It seems to me that the flavor of Python programming has changed significantly over the past few releases. That trend will likely continue and even accelerate. From ptmcg at austin.rr.com Sun Feb 18 21:56:49 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 18 Feb 2007 18:56:49 -0800 Subject: I need a crack for pyext1.2.5 plugin In-Reply-To: References: Message-ID: <1171853809.836540.157490@l53g2000cwa.googlegroups.com> On Feb 18, 8:07 pm, "Oliver Sosa Cano" wrote: > Hi pythoneros. I'm a cuban guy interested in python and I need the crack of an Eclipse plugin: pyext 1.2.5 > > Thanks very much > > cheers > > Oliver Sosa Never heard of pyext - Google turns up this link http://grrrr.org/ext/py/, but this is pyext 0.2.0. If by "crack" you mean "bootlegged user key for commercial software," this is the wrong place for that stuff. On the other hand, if you tell us what kind of Eclipse work you are doing that requires this elusive plug-in, someone may have a suggestion on where to find it, or an equivalent. -- Paul From jstroud at mbi.ucla.edu Sun Feb 11 19:59:40 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 11 Feb 2007 16:59:40 -0800 Subject: help please!! In-Reply-To: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> References: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Message-ID: darren112 wrote: > Hi Im new to python and I desperately need help with this task.... > This is everything of what I need to do....... > > The program to be written in Python obviously...... > > The program should support brute-forcing of the authentication process > for a Telnet server via a dictionary attack. > > The python program is required to take four parameters: a) the IP > address of a Computer, b) the port number that the Telnet server is > running on the computer , c) the name of a file containing a list if > usernames, and b) the name of a file containing a list of word/phrases > to be used as passwords. > > The program should then attempt to authenticate itself to the Telnet > server via trying every password for every username. The program > should report when it is successful. > > Please help me.... And as I am new to all this please post step by > step instructions... > I'm guessing this is a troll rather than a script kiddy. It seems more like bait than an "honest" question. From mintern at cse.ohio-state.edu Thu Feb 22 11:43:30 2007 From: mintern at cse.ohio-state.edu (Brandon Mintern) Date: Thu, 22 Feb 2007 11:43:30 -0500 Subject: paths in modules References: <_YOdnU50mqTXWEDYnZ2dnUVZ_qfinZ2d@comcast.com> Message-ID: On Thu, 22 Feb 2007 10:30:59 -0600, Larry Bates wrote: > Normally this would be: > > f = os.popen('./wrapper_dir/utility_dir/some_external_utility') > > -Larry Yes, but the problem with that solution is, let's say that I further abstract the whole thing and I add a directory outside of my toplevel_dir, which has the syntax: from toplevel_dir.wrapper_dir import some_wrapper some_wrapper.use_external_utility() Now, once again, the module is broken. This is what I was trying to avoid. At any rate, Paul's solution was exactly what I was looking for. From michele.simionato at gmail.com Wed Feb 7 02:06:18 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Feb 2007 23:06:18 -0800 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: Message-ID: <1170831978.314228.115660@q2g2000cwa.googlegroups.com> On Feb 6, 4:40 pm, Steven Bethard wrote: > Jean-Paul Calderone wrote: > > > Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve I have seen breakage in Zope, due to the switch from old-style exceptions to new-style exceptions. Michele Simionato From sjmachin at lexicon.net Wed Feb 14 04:08:48 2007 From: sjmachin at lexicon.net (John Machin) Date: 14 Feb 2007 01:08:48 -0800 Subject: python not returning true In-Reply-To: References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> <1171437351.206085.236450@q2g2000cwa.googlegroups.com> Message-ID: <1171444128.138234.50640@l53g2000cwa.googlegroups.com> On Feb 14, 7:02 pm, "Terry Reedy" wrote: > "John Machin" wrote in message > > news:1171437351.206085.236450 at q2g2000cwa.googlegroups.com... > > | On Feb 14, 5:45 pm, "agent-s" wrote: > | > btw Steven you are so witty I hope to one day pwn noobs on newsgroups > | > too. > > Sorry, but you are 'pwning' yourself here ;-) And the referent of "you" would be .....? > > | Wit has nothing to do with it. The fact that you are a Python noob is > | also irrelevant. Your problem statement was unintelligible, as is your > | response. What does "pwn" mean? > > I believe that it is a misspelling of 'own' used by pvp (person versus > person, as opposed to person versus monster) gamers to demonstrate their > in-ness. But perhaps agent-s can enlightenment us further. So "enlightenment" has been verbed, has it? I didn't realise that the language had been transitioned so far :-) Cheers, John From nagle at animats.com Wed Feb 14 02:11:37 2007 From: nagle at animats.com (John Nagle) Date: Tue, 13 Feb 2007 23:11:37 -0800 Subject: How can this Perl regular expression be expressed in Python? In-Reply-To: References: <8WvAh.14675$O02.10228@newssvr11.news.prodigy.net> Message-ID: Gabriel Genellina wrote: > En Wed, 14 Feb 2007 01:07:33 -0300, John Nagle > escribi?: > >> Here's a large Perl regular expression, from a Perl address parser in >> CPAN: >> >> use re 'eval'; >> $Addr_Match{street} = qr/ >> (?: >> # special case for addresses like 100 South Street >> (?:($Addr_Match{direct})\W+ (?{ $_{street} = $^N }) >> ($Addr_Match{type})\b (?{ $_{type} = $^N })) >> | >> (?:($Addr_Match{direct})\W+ (?{ $_{prefix} = $^N }))? >> (?: >> ([^,]+) (?{ $_{street} = $^N }) >> (?:[^\w,]+($Addr_Match{type})\b (?{ $_{type} = $^N })) >> (?:[^\w,]+($Addr_Match{direct})\b (?{ $_{suffix} = $^N >> }))? >> | >> ([^,]*\d) (?{ $_{street} = $^N }) >> ($Addr_Match{direct})\b (?{ $_{suffix} = $^N }) >> | >> ([^,]+?) (?{ $_{street} = $^N }) >> (?:[^\w,]+($Addr_Match{type})\b (?{ $_{type} = $^N }))? >> (?:[^\w,]+($Addr_Match{direct})\b (?{ $_{suffix} = $^N >> }))? >> ) >> ) >> /ix; >> >> I'm trying to convert this to Python. >> >> Those entries like "$(Addr_Match{direct}) are other regular expressions, >> being used here as subexpressions. Those have already been converted >> to forms like "Addr_Match.direct" in Python. But how to call them? >> Is that possible in Python, and if so, where is it documented? > > > That would be string interpolation, like this: > > Addr_Match = {"direct": "some_re_string", > "type": "other_re" > } > > regexp = "%(direct)s %(type)s" % Addr_Match You're right. I looked at the Perl code, and the strings are just being inserted, not precompiled as regular expressions and called. Incidentally, does anybody know what "$^N" means in Perl? That abbreviation isn't in the list of special variables. John Nagle From zsikic at rogers.com Wed Feb 21 12:57:35 2007 From: zsikic at rogers.com (Zeljko Sikic) Date: Wed, 21 Feb 2007 12:57:35 -0500 Subject: Converting a text data file from positional to tab delimited. Message-ID: <20070221181157.AA78F1E4002@bag.python.org> Hi, You should try www.TextMaster.ca and download SW which can convert text file from fix positioned to TAB delimited or any other text format. Regards, Jake -------------- next part -------------- An HTML attachment was scrubbed... URL: From aldcwatson at gmail.com Thu Feb 22 12:06:06 2007 From: aldcwatson at gmail.com (Andy Watson) Date: 22 Feb 2007 09:06:06 -0800 Subject: Possible to set cpython heap size? Message-ID: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> I have an application that scans and processes a bunch of text files. The content I'm pulling out and holding in memory is at least 200MB. I'd love to be able to tell the CPython virtual machine that I need a heap of, say 300MB up front rather than have it grow as needed. I've had a scan through the archives of comp.lang.python and the python docs but cannot find a way to do this. Is this possible to configure the PVM this way? Much appreciated, Andy -- From sakagami at gmail.com Wed Feb 21 11:05:44 2007 From: sakagami at gmail.com (Sakagami Hiroki) Date: 21 Feb 2007 08:05:44 -0800 Subject: Creating a daemon process in Python Message-ID: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Hi, What is the easiest way to create a daemon process in Python? Google says I should call fork() and other system calls manually, but is there no os.daemon() and the like? Regards, -- Sakagami Hiroki From cityhunter007 at gmail.com Wed Feb 7 17:32:59 2007 From: cityhunter007 at gmail.com (James) Date: 7 Feb 2007 14:32:59 -0800 Subject: Python new user question - file writeline error In-Reply-To: References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> Message-ID: <1170887579.160693.78160@a34g2000cwb.googlegroups.com> On Feb 7, 4:59 pm, "Shawn Milo" wrote: > On 7 Feb 2007 11:31:32 -0800, James wrote: > > > > > Hello, > > > I'm a newbie to Python & wondering someone can help me with this... > > > I have this code: > > -------------------------- > > #! /usr/bin/python > > > import sys > > > month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG': > > 8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > > infile=file('TVA-0316','r') > > outfile=file('tmp.out','w') > > > for line in infile: > > item = line.split(',') > > dob = item[6].split('/') > > dob = dob[2]+'-'+str(month[dob[1]])+'-'+dob[0] > > lbdt = item[8].split('/') > > lbdt = lbdt[2]+'-'+str(month[lbdt[1]])+'-'+lbdt[0] > > lbrc = item[10].split('/') > > lbrc = lbrc[2]+'-'+str(month[lbrc[1]])+'-'+lbrc[0] > > lbrp = item[14].split('/') > > lbrp = lbrp[2]+'-'+str(month[lbrp[1]])+'-'+lbrp[0] > > item[6] = dob > > item[8] = lbdt > > item[10]=lbrc > > item[14]=lbrp > > list = ','.join(item) > > outfile.writelines(list) > > infile.close > > outfile.close > > ----------------------------- > > > And the data file(TVA-0316) looks like this: > > ----------------------------- > > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > > NOV/2006,V1,,,21/NOV/2006,AST,19,U/L,5,40,, > > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > > NOV/2006,V1,,,21/NOV/2006,GGT,34,U/L,11,32,h, > > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > > NOV/2006,V1,,,21/NOV/2006,ALT,31,U/L,5,29,h, > > 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/ > > NOV/2006,V1,,,21/NOV/2006,ALKP,61,U/L,40,135,, > > ----------------------------- > > > Basically I'm reading in each line and converting all date fields (05/ > > MAR/1950) to different format (1950-03-05) in order to load into MySQL > > table. > > > I have two issues: > > 1. the outfile doesn't complete with no error message. when I check > > the last line in the python interpreter, it has read and processed the > > last line, but the output file stopped before. > > 2. Is this the best way to do this in Python? > > 3. (Out of scope) is there a way to load this CSV file directly into > > MySQL data field without converting the format? > > > Thank you. > > > James > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Your script worked for me. I'm not sure what the next step is in > troubleshooting it. Is it possible that your whitespace isn't quite > right? I had to reformat it, but I assume it was because of the way > cut & paste worked from Gmail. > > I usually use Perl for data stuff like this, but I don't see why > Python wouldn't be a great solution. However, I would re-write it > using regexes, to seek and replace sections that are formatted like a > date, rather than breaking it into a variable for each field, changing > each date individually, then putting them back together. > > As for how MySQL likes having dates formatted in CSV input: I can't > help there, but I'm sure someone else can. > > I'm pretty new to Python myself, but if you'd like help with a > Perl/regex solution, I'm up for it. For that matter, whipping up a > Python/regex solution would probably be good for me. Let me know. > > Shawn Thank you very much for your kind offer. I'm also coming from Perl myself - heard many good things about Python so I'm trying it out - but it seems harder than I thought :( James From andymac at bullseye.apana.org.au Fri Feb 23 18:51:20 2007 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 24 Feb 2007 09:51:20 +1000 Subject: Possible to set cpython heap size? In-Reply-To: <4866bea60702221158r5ef03db8pe300f2725f9d9735@mail.gmail.com> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <1172172532.503432.223650@v33g2000cwv.googlegroups.com> <4866bea60702221158r5ef03db8pe300f2725f9d9735@mail.gmail.com> Message-ID: <45DF7DF8.60303@bullseye.andymac.org> Chris Mellon wrote: > On 22 Feb 2007 11:28:52 -0800, Andy Watson wrote: >> On Feb 22, 10:53 am, a bunch of folks wrote: >> >>> Memory is basically free. >> This is true if you are simply scanning a file into memory. However, >> I'm storing the contents in some in-memory data structures and doing >> some data manipulation. This is my speculation: >> >> Several small objects per scanned line get allocated, and then >> unreferenced. If the heap is relatively small, GC has to do some work >> in order to make space for subsequent scan results. At some point, it >> realises it cannot keep up and has to extend the heap. At this point, >> VM and physical memory is committed, since it needs to be used. And >> this keeps going on. At some point, GC will take a good deal of time >> to compact the heap, since I and loading in so much data and creating >> a lot of smaller objects. >> >> If I could have a heap that is larger and does not need to be >> dynamically extended, then the Python GC could work more efficiently. >> > > I haven't even looked at Python memory management internals since 2.3, > and not in detail then, so I'm sure someone will correct me in the > case that I am wrong. > > However, I believe that this is almost exactly how CPython GC does not > work. CPython is refcounted with a generational GC for cycle > detection. There's a memory pool that is used for object allocation > (more than one, I think, for different types of objects) and those can > be extended but they are not, to my knowledge, compacted. > > If you're creating the same small objects for each scanned lines, and > especially if they are tuples or new-style objects with __slots__, > then the memory use for those objects should be more or less constant. > Your memory growth is probably related to the information you're > saving, not to your scanned objects, and since those are long-lived > objects I simple don't see how heap pre-allocation could be helpful > there. Python's internal memory management is split: - allocations up to 256 bytes (the majority of objects) are handled by a custom allocator, which uses 256kB arenas malloc()ed from the OS on demand. With 2.5 some additional work was done to allow returning completely empty arenas to the OS; 2.3 and 2.4 don't return arenas at all. - all allocations over 256 bytes, including container objects that are extended beyond 256 bytes, are made by malloc(). I can't recall off-hand whether the free-list structures for ints (and floats?) use the Python allocator or direct malloc(); as the free-lists don't release any entries, I suspect not. The maximum allocation size and arena size used by the Python allocator are hard-coded for algorithmic and performance reasons, and cannot be practically be changed, especially at runtime. No active compaction takes place in arenas, even with GC. The only time object data is relocated between arenas is when an object is resized. If Andy Watson is creating loads of objects that aren't being managed by Python's allocator (by being larger than 256 bytes, or in a type free-list), then the platform malloc() behaviour applies. Some platform allocators can be tuned via environment variables and the like, in which case review of the platform documentation is indicated. Some platform allocators are notorious for poor behaviour in certain circumstances, and coalescing blocks while deallocating is one particularly nasty problem for code that creates and destroys lots of small variably sized objects. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From exarkun at divmod.com Thu Feb 1 07:43:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Feb 2007 07:43:20 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170309756.501758.303800@a34g2000cwb.googlegroups.com> Message-ID: <20070201124320.25807.326267222.divmod.quotient.6081@ohm> On 31 Jan 2007 22:02:36 -0800, Michele Simionato wrote: >On Jan 31, 8:31 pm, "Carl J. Van Arsdall" >wrote: >> >> Well, since it will be io based, why not use threads? They are easy to >> use and it would do the job just fine. Then leverage some other >> technology on top of that. >> >> You could go as far as using wget via os.system() in a thread, if the >> app is simple enough. > >Calling os.system in a thread look really perverse to me, you would >loose CTRL-C without any benefit. >Why not to use subprocess.Popen instead? > >I am unhappy with the current situation in Python. Whereas for most >things Python is such that the simplest >things look simple, this is not the case for threads. Unfortunately we >have a threading module in the >standard library, but not a "Twisted for pedestrian" module, so people >overlook the simplest solution >in favor of the complex one. >Another thing I miss is a facility to run an iterator in the Tkinter >mainloop: since Tkinter is not thread-safe, >writing a multiple-download progress bar in Tkinter using threads is >definitely less obvious than running >an iterator in the main loop, as I discovered the hard way. Writing a >facility to run iterators in Twisted >is a three-liner, but it is not already there, nor standard :-( > Have you seen the recently introduced twisted.internet.task.coiterate()? It sounds like it might be what you're after. Jean-Paul From ptmcg at austin.rr.com Wed Feb 28 01:14:41 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Feb 2007 22:14:41 -0800 Subject: Yet another unique() function... In-Reply-To: <7xzm6z6lf4.fsf@ruckus.brouhaha.com> References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> <7x8xej80a5.fsf@ruckus.brouhaha.com> <7xzm6z6lf4.fsf@ruckus.brouhaha.com> Message-ID: <1172643281.565788.12380@8g2000cwh.googlegroups.com> On Feb 27, 8:55 pm, Paul Rubin wrote: > Paul Rubin writes: > > def unique(seq, keepstr=True): > > t = type(seq) > > if t==str: > > t = (list, ''.join)[bool(keepstr)] > > seen = [] > > return t(c for c in seq if (c not in seen, seen.append(c))[0]) > > Preferable: > > def unique(seq, keepstr=True): > t = type(seq) > if t==str: > t = (list, ''.join)[bool(keepstr)] > seen = [] > return t(c for c in seq if not (c in seen or seen.append(c))) Any reason not to use a set for the 'seen' variable? Avoids searching through a linear list. The input order is preserved because the return value is created in the generator expression, not by using the seen variable directly. def unique2(seq, keepstr=True): t = type(seq) if t==str: t = (list, ''.join)[bool(keepstr)] seen = set() return t(c for c in seq if not (c in seen or seen.add(c))) -- Paul From dustin.getz at gmail.com Mon Feb 26 16:45:36 2007 From: dustin.getz at gmail.com (dustin.getz at gmail.com) Date: 26 Feb 2007 13:45:36 -0800 Subject: modifying a list while iterating through In-Reply-To: <1172456132.151803.75800@p10g2000cwp.googlegroups.com> References: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> <1172456132.151803.75800@p10g2000cwp.googlegroups.com> Message-ID: <1172526336.150880.291720@z35g2000cwz.googlegroups.com> On Feb 25, 9:15 pm, attn.steven.... at gmail.com wrote: > On Feb 25, 5:12 pm, dustin.g... at gmail.com wrote: > > > consider the following working loop where Packet is a subclass of > > list, with Packet.insert(index, iterable) inserting each item in > > iterable into Packet at consecutive indexes starting at index. > > > i=0 > > while(i > if packet[i:i+5]==Packet("01110"): > > packet.insert(i, "01111") > > i+=10 #skip the 5 bits inserted, and skip the 5 bits just > > checked bc overlap should not trigger insertion > > else: i+=1 > > > is there a way to do this more elegantly? seems like a big kludge. > > If Packet consists of '0's and '1's, then it may be > easier to convert to, or base the class on str (strings): > > packet = "1010101111011100111010001" > print "BEFORE ", packet > li = packet.split("01110") > packet = "0111001111".join(li) > print "AFTER ", packet > > -- > Hope this helps, > Steven Steven, George, Thanks for your responses. Yea, that would work. My original question still stands, though, in situations where a simple string replacement might not be sufficient. Is there a way to insert into a list whilst iterating through it? for example, consider a list of binary values. for index in range(len(iterable)): item=iterable[index] if item==1: iterable.insert(index,0) obv this wouldn't work because now all future indexes will be off by the number of previously inserted items. using a while loop to fix this ugly and counterintuitive. From acncgc at yahoo.com Sat Feb 10 01:28:26 2007 From: acncgc at yahoo.com (acncgc) Date: Sat, 10 Feb 2007 06:28:26 -0000 Subject: LoadLibrary(pythondll) failed Message-ID: I get an following error as I turn on my laptop; LoadLibrary(pythondll) failed After this error internet browser ( IE or mozilla) doesn't connect. I can't browse any site. Any idea?? From ruan at jcmills.com Wed Feb 7 14:15:41 2007 From: ruan at jcmills.com (John) Date: Wed, 7 Feb 2007 14:15:41 -0500 Subject: Can somebody give me a python code for this? Message-ID: Given an array of elements, look at it as a binary tree. Start at the last interior node, and downheap it. Then downheap the previous interior node, and continue in this fashion, up to the root. From donn at u.washington.edu Thu Feb 15 18:16:01 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 15 Feb 2007 15:16:01 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> Message-ID: In article <7xr6srgm3c.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > skip at pobox.com writes: > > My original comment was that tuples could be thought of more like > > C structs or Pascal records. > > Should f(*args) receive a list rather than a tuple arg? No, clearly not. Function parameters are good example of exactly what tuples are about, with some extra struct/dict stuff for emphasis. If t is a valid argument tuple for function f, then can t[1:] also be a valia argument tuple for function f? For ordinary functions without special argument handling, no. We know that without having to know anything about t, and not much about f. This is characteristic of tuple applications. Donn Cave, donn at u.washington.edu From tinaweb at bestemselv.com Tue Feb 27 13:04:20 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 27 Feb 2007 19:04:20 +0100 Subject: HTML to dictionary In-Reply-To: References: Message-ID: Thanks people, I learned a lot!! :) I went for Herbert's solution in my application but I explored, and learned from, all of them. Tina From txdyjsyz at gmail.com Tue Feb 6 04:51:40 2007 From: txdyjsyz at gmail.com (mars) Date: 6 Feb 2007 01:51:40 -0800 Subject: How to prevent from race conditions to share data between many process and thread in python Message-ID: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> I use TurboGears to do some web service. TurboGears use cherrypy. When web browser access this site, the cherrypy will call my python program. So my program looks like a lib. When web browser access the site, the http server will fock a process or gerenate a thread. I need share some data or operate some files. How can I prevent from race conditions. Is there any way can I lock this. Thank you in advance! From supervau at gmail.com Mon Feb 5 00:46:10 2007 From: supervau at gmail.com (Frank) Date: 4 Feb 2007 21:46:10 -0800 Subject: problems loading modules Message-ID: <1170654370.545302.277060@k78g2000cwa.googlegroups.com> Hi, I have the following weird behavior when I load modules: >>> import random >>> print random.randrange(10) 8 >>> Everything is fine. >>> import random >>> from numpy import * >>> >>> print random.randrange(10) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'randrange' >>> Here it does not work. >>> from numpy import * >>> import random >>> >>> print random.randrange(10) 8 >>> Now everything is back to normal. That means the order the modules are loaded matters! I would expect there is a problem with my installation because I guess this should normally be independent of the loaded modules. Here are my questions: 1. Does anyone has this behavior too? 2. How can I fix this problem? I use linux with fedora core 6 and python 2.4.4 I appreciate any hint. Thanks! Frank From lance at augustmail.com Mon Feb 19 18:10:16 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Mon, 19 Feb 2007 23:10:16 GMT Subject: Newbie help looping/reducing code Message-ID: Hey all, Can someone help me reduce this code? It sure seems like there ought to be a way to loop this or combine things so that there is only 1 or 3 lines to this instead of 6. I've been scratching my head over this for a while though I can't come up with anything. Just as a note, I need even_odd_round left alone because it is not always used. I just included for clarity. As always, thanks in advance, Lance T2B = even_odd_round(float(str(T2B))) VS = even_odd_round(float(str(VS))) SS = even_odd_round(float(str(SS))) sh.Cells(21,lastcol+1).Value = float(str(T2B))/100 sh.Cells(22,lastcol+1).Value = float(str(VS))/100 sh.Cells(23,lastcol+1).Value = float(str(SS))/100 def even_odd_round(num): if(round(num,2) + .5 == int(round(num,2)) + 1): if num > .5: if(int(num) % 2): num = round(num,2) + .1 #an odd number else: num = round(num,2) - .1 #an even number else: num = 1 rounded_num = int(round(num,0)) return rounded_num From _karlo_ at _mosor.net_ Mon Feb 26 22:13:59 2007 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Tue, 27 Feb 2007 03:13:59 +0000 (UTC) Subject: Tip: 'Open IPython here' in Windows context menu Message-ID: Based on the idea from 'Open Command Window Here' utility from MS - add a context menu item, which allows you to open IPython in selected directory. ---cut-here--- Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\ipython] @="IPython here" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\ipython\command] @="\"C:\\Program Files\\JPSoft\\TCMD8\\tcmd.exe\" /k cd %L & C:\\Python \\Scripts\\ipython.py" ---cut-here--- Save this as a "something.reg" file, doubleclick it and import into Windows registry. And that's it. While in Windows Explorer, right click any directory, and select "Ipython here" item... Btw, as you can see, I'm not using ordinary Windows cmd.exe, instead of it I use Take Command by JPsoft. If you want to use cmd.exe instead, just replace tcmd.exe path, with cmd.exes'. Hope this will be usefull to someone... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From jorge.vargas at gmail.com Wed Feb 21 17:46:07 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 21 Feb 2007 18:46:07 -0400 Subject: BDFL in wikipedia In-Reply-To: References: <32822fe60702201827k36f8bd53k69908869a19f00e6@mail.gmail.com> <20070221082830.31BD26F4CF3@longblack.object-craft.com.au> Message-ID: <32822fe60702211446p60991ef1ya3ab13facc6a6673@mail.gmail.com> On 2/21/07, Gabriel Genellina wrote: > En Wed, 21 Feb 2007 05:28:30 -0300, Andrew McNamara > escribi?: > > >> Hi I just hit this page in wikipedia BDFL[1] > >> and it redirected me to Guido's wikipedia[2] entry > >> [1] http://en.wikipedia.org/wiki/BDFL > > > > I suspect, in this case, the redirect is implicit. It's happening > > because the Wikipedia search engine finds no page called BDFL, and the > > Guido_van_Rossum is the next closest match. > > No, both BDFL and Benevolent_Dict... have an explicit redirect to Guido's > entry. > It used to be quite different in the past, but the topic has been heavily > discussed and edited. > See > http://en.wikipedia.org/wiki/Talk:Benevolent_Dictator_for_Life#Concerned_about_accuracy_-_BDs_versus_BDFLs > Guido appears to be the *only* one called BDFL. > ahhh thanks Gabriel that should clear it out :) > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Wed Feb 7 17:57:35 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 07 Feb 2007 16:57:35 -0600 Subject: Re-installing Numeric and PIL Files In-Reply-To: References: Message-ID: W. Watson wrote: > For some reason Python 2.2.4 cannot find the Numeric module. It's been > suggested that I should re-install the Numeric file. How do that? Also the > PIL. The three install files are: > python-2.4.4.msi > PIL-1.1.5.win32-py2.4.exe > Numeric-24.2.win32-py2.4.exe The latter two are executable installers. Run them. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From uval at rz.uni-karlsruhe.de Mon Feb 19 11:29:22 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Mon, 19 Feb 2007 17:29:22 +0100 Subject: pylab, integral of sinc function In-Reply-To: References: Message-ID: my fault In [31]: simple_integral(lambda x:sinc(x/pi), -1000, 1000) Out[31]: 3.14046624406611 From Finger.Octopus at gmail.com Sat Feb 3 12:16:13 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 3 Feb 2007 09:16:13 -0800 Subject: How can I access data from MS Access? In-Reply-To: <45c4bee4$0$453$426a74cc@news.free.fr> References: <1170517420.026596.74880@s48g2000cws.googlegroups.com> <45c4bee4$0$453$426a74cc@news.free.fr> Message-ID: <1170522973.012926.252510@k78g2000cwa.googlegroups.com> On Feb 3, 10:27 pm, Bruno Desthuilliers wrote: > Finger.Octo... at gmail.com a ?crit :> How to access data from MS Access? I tried ADOdb for Python but it > > doesn't seems to work. > > > Even the official examples dont work, like this one: > > > import adodb > > conn = adodb.NewADOConnection('access') # mxodbc required > > dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\inetpub\\adodb\ > > \northwind.mdb;" > > conn.Connect(dsn) > > > (I have downloaded mxodbc, but still it doesn't works) > > "doesn't work" is the worst possible description of a problem. Did it > print out some insults in a foreign language ? wipe out your HD ? Else ? I havn't said "doesn't work", I rather doesn't seem to work. From aldcwatson at gmail.com Thu Feb 22 14:28:52 2007 From: aldcwatson at gmail.com (Andy Watson) Date: 22 Feb 2007 11:28:52 -0800 Subject: Possible to set cpython heap size? In-Reply-To: References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> Message-ID: <1172172532.503432.223650@v33g2000cwv.googlegroups.com> On Feb 22, 10:53 am, a bunch of folks wrote: > Memory is basically free. This is true if you are simply scanning a file into memory. However, I'm storing the contents in some in-memory data structures and doing some data manipulation. This is my speculation: Several small objects per scanned line get allocated, and then unreferenced. If the heap is relatively small, GC has to do some work in order to make space for subsequent scan results. At some point, it realises it cannot keep up and has to extend the heap. At this point, VM and physical memory is committed, since it needs to be used. And this keeps going on. At some point, GC will take a good deal of time to compact the heap, since I and loading in so much data and creating a lot of smaller objects. If I could have a heap that is larger and does not need to be dynamically extended, then the Python GC could work more efficiently. Interesting discussion. Cheers, Andy -- From seir.corall at gmail.com Mon Feb 26 12:50:43 2007 From: seir.corall at gmail.com (Alexander Orchard) Date: Mon, 26 Feb 2007 12:50:43 -0500 Subject: I don't quite understand this error... Message-ID: <5c87851f0702260950h5994ab22nccd3d2db2ff5e7d1@mail.gmail.com> I'm trying to create a simple accounting system based off of an example GUI. The coding is as follows: #!/usr/bin/python from Tkinter import * from os import urandom from twisted.internet import tksupport from twisted.internet import reactor from accounts import accountlist def whichSelected () : print "At %s of %d" % (select.curselection(), len(accountlist)) return int(select.curselection()[0]) def addEntry () : accountlist.append ([userVar.get(), passwVar.get(), balanceVar.get()]) setSelect () def Withdrawl() : user, passw, balance = accountlist[whichSelected()] userVar.set(user) passwVar.set(passw) balanceVar.set(balance) balanceVar -= amount balance.set(balanceVar) setSelect () def Deposit() : user, passw, balance = accountlist[whichSelected()] balance += amount accountlist[whichSelected()] = [user, passw, balance] setSelect () def loadEntry () : user, passw, balance = accountlist[whichSelected()] userVar.set(user) passwVar.set(passw) balanceVar.set(balance) def makeWindow () : global userVar, passwVar, balanceVar, amount, select win = Tk() frame1 = Frame(win) frame1.pack() Label(frame1, text="User Name").grid(row=0, column=0, sticky=W) userVar = StringVar() user = Entry(frame1, textvariable=userVar) user.grid(row=0, column=1, sticky=W) Label(frame1, text="Password").grid(row=1, column=0, sticky=W) passwVar= StringVar() passw= Entry(frame1, textvariable=passwVar) passw.grid(row=1, column=1, sticky=W) Label(frame1, text="Balance ($)").grid(row=2, column=0, sticky=W) balanceVar= IntVar() balance= Entry(frame1, textvariable=balanceVar) balance.grid(row=2, column=1, sticky=W) frame2 = Frame(win) frame2.pack() b1 = Button(frame2,text=" Add ",command=addEntry) b2 = Button(frame2,text="Withdraw Amount",command=Withdrawl) b3 = Button(frame2,text="Deposit Amount",command=Deposit) b4 = Button(frame2,text=" Load ",command=loadEntry) b1.pack(side=LEFT); b2.pack(side=LEFT) b3.pack(side=LEFT); b4.pack(side=LEFT) frame3 = Frame(win) frame3.pack() scroll = Scrollbar(frame3, orient=VERTICAL) select = Listbox(frame3, yscrollcommand=scroll.set, height=6) scroll.config (command=select.yview) scroll.pack(side=RIGHT, fill=Y) select.pack(side=LEFT, fill=BOTH, expand=1) frame4 = Frame(win) frame4.pack() Label(frame4, text="Amount ($)").grid(row=0, column=0, sticky=W) amountVar= IntVar() amount= Entry(frame4, textvariable=amountVar) amount.grid(row=0, column=1, sticky=W) return win def setSelect () : accountlist.sort() select.delete(0,END) for user,passw,balance in accountlist : select.insert (END, user) # Install the Reactor support def main(): root = makeWindow() setSelect () tksupport.install(root) # root.pack() print "starting event loop" reactor.run() #if __name__ == "__main__": main() Also, for reference, the "accounts" imported from are as follows: accountlist = [ ['Alex', 'shera', '400'], ['Sam', 'tish', '0'] ] Thus far, everything works fine unless I'm trying the Deposit or Withdrawal functions. (I know they're different, but both give roughly the same error.) Whenever I attempt one of these functions I get the following error message: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Python24\AEOpaypal.py", line 27, in Deposit user, passw, balance = accountlist[whichSelected()] File "C:\Python24\AEOpaypal.py", line 11, in whichSelected return int(select.curselection()[0]) IndexError: tuple index out of range I honestly don't understand what's going on... I've managed to stumble my way through understanding what error messages mean, but I'm not sure what do here. Just to clarify, to deposit money, first you select the account, and click "Load" to bring it up on screen. Then you put the amount in the "Amount" text box. Then you click "Deposit Amount" Thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From thermostat at gmail.com Thu Feb 1 15:28:11 2007 From: thermostat at gmail.com (Dan) Date: 1 Feb 2007 12:28:11 -0800 Subject: xml.dom.minidom memory usage In-Reply-To: References: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> Message-ID: <1170361691.427042.63500@a34g2000cwb.googlegroups.com> On Feb 1, 3:12 pm, Jonathan Curran wrote: > Dan, > The DOM (Document Object Model) is such that it loads all the elements of the > XML document into memory before you can do anything with it. With your file > containing millions of child nodes this will eat up as much memory as you > have. A solution to this is to use the SAX method of parsing XML documents > and working on it. SAX is such that it only reads the XML doc. a node (or a > few nodes) at a time. > > Unfortunately, the use of DOM or SAX completely depends on what kind of > processing you need to be done on the XML document. If it is editing a record > at a time (from what I've gathered from your code) it would be wise to use > SAX. I highly suggest looking into this method of processing. > > - Jonathan Curran Jonathan, Thanks for the response. I'm comfortable using SAX for parsing, but I'm unsure how it helps me with XML generation. To clarify in my example code, with the DOM document, I can call doc.toxml() or doc.toprettyxml(), and get the desired output (an xml file). AFAIK, SAX has no analog, it just does parsing. Is there a way to do XML generation with SAX that I'm unaware of? -Dan From rattan at cps.cmich.edu Wed Feb 7 20:25:17 2007 From: rattan at cps.cmich.edu (rattan at cps.cmich.edu) Date: 7 Feb 2007 17:25:17 -0800 Subject: help on packet format for tcp/ip programming Message-ID: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> I want a specific packet format for packet exchange between a client server across the network. For example frame format as a python class could be: class Frame: def __init__(self, buffer=None, count=0, offset=0): self.buffer = buffer self.count = count self.offset = offset the question is how to convert it to a byte stream so that format of count and offset also becomes a sequence of bytes. I tried the pickle module as: a = Frame() dat = pickle.dumps(a) but the size of dat is quite large almost to 4 X the size of a, which probably is an overkill for the numbers of bytes exchanged. Is there a simpler solution (similar to C language -- set aside a buffer and fill it with bytes and network byteorder values for count and offset and send it out, there is no increase in byte count in the outgoing packet)? Any pointers will be appreciated. -ishwar From kent at kentsjohnson.com Sun Feb 18 23:48:12 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 19 Feb 2007 04:48:12 GMT Subject: Is there any way to automatically create a transcript of an interactive Python session? In-Reply-To: <1171842673.363336.121080@l53g2000cwa.googlegroups.com> References: <1171842673.363336.121080@l53g2000cwa.googlegroups.com> Message-ID: Jonathan Mark wrote: > Some languages, such as Scheme, permit you to make a transcript of an > interactive console session. Is there a way to do that in Python? > Maybe IPython's logging feature is what you want? http://ipython.scipy.org/doc/manual/node6.html#SECTION00066000000000000000 Kent From ullrich at math.okstate.edu Sat Feb 24 06:17:38 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sat, 24 Feb 2007 05:17:38 -0600 Subject: CSV(???) References: <45ded3f2$0$325$e4fe514c@news.xs4all.nl> <45ded55c$0$325$e4fe514c@news.xs4all.nl> Message-ID: On 23 Feb 2007 11:51:57 GMT, nmp
wrote: >Op Fri, 23 Feb 2007 11:45:54 +0000, schreef nmp: > >> Op Fri, 23 Feb 2007 05:11:26 -0600, schreef David C. Ullrich: >> >>> Is there a csvlib out there somewhere? >> >> Hey, cool! I am just beginning with Python but I may already be able to >> help you ;) > >Oops I missed the bit where you said you were using that very old Python >version... No problem. Actually if there were a csv.py in my version I would have found it before posting, but you didn't know that. ************************ David C. Ullrich From whumeniu+anti+spam at telus.net Tue Feb 27 09:30:13 2007 From: whumeniu+anti+spam at telus.net (Wade Humeniuk) Date: Tue, 27 Feb 2007 14:30:13 GMT Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: Tech HR wrote: > In article <1172482314.598240.3440 at j27g2000cwj.googlegroups.com>, > dixkey at gmail.com wrote: > >> On Feb 26, 6:32 am, Tech HR wrote: >>> Our >>> website is currently a LAMP appication with P=Python. We are looking for >>> bright motivated people who know or are willing to learn Python and/or >>> Linux, Apache and MySQL system administration skills. (And if you want >>> to convince us that we should switch over to Postgres, we're willing to >>> listen.) >> This is more out of curiosity, but does it mean that you wouldn't be >> willing to listen about a switch from Python to Lisp? > > No, it doesn't mean that. In fact, there is a significant faction in > the technical staff (including the CTO) who would like nothing better > than to be able to use Lisp instead of Python. Who is the CTO? Wade From sjmachin at lexicon.net Mon Feb 12 06:17:08 2007 From: sjmachin at lexicon.net (John Machin) Date: 12 Feb 2007 03:17:08 -0800 Subject: Regular Expressions In-Reply-To: <1171275611.208401.212000@v33g2000cwv.googlegroups.com> References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> <1171227036.789128.188720@q2g2000cwa.googlegroups.com> <1171275611.208401.212000@v33g2000cwv.googlegroups.com> Message-ID: <1171279028.593738.38740@p10g2000cwp.googlegroups.com> On Feb 12, 9:20 pm, "deviantbunnyl... at gmail.com" wrote: > HTML: htmllib and HTMLParser (both in the Python library), > BeautifulSoup (again GIYF) > > XML: xml.* in the Python library. ElementTree (recommended) is > included in Python 2.5; use xml.etree.cElementTree. > > The source of HTMLParser and xmllib use regular expressions for > parsing out the data. htmllib calls sgmllib at the begining of it's > code--sgmllib starts off with a bunch of regular expressions used to > parse data. So the only real difference there I see is that someone > saved me the work of writing them ;0). I haven't looked at the source > for Beautiful Soup, though I have the sneaking suspicion that most > processing of html/xml is all based on regex's. That's right. Those modules use regexes. You don't. You call functions & classes in the modules. Someone has written those modules and tested them and documented them and they've had a fair old thrashing by quite a few people over the years -- it may be the only difference in your way of thinking but it's quite a large difference from you opening up the re docs and getting stuck in single-handedly :-) From michele.simionato at gmail.com Thu Feb 8 06:07:45 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Feb 2007 03:07:45 -0800 Subject: Object type check In-Reply-To: <1170932439.393593.200090@h3g2000cwc.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> <1170932439.393593.200090@h3g2000cwc.googlegroups.com> Message-ID: <1170932865.701952.99210@v33g2000cwv.googlegroups.com> On Feb 8, 12:00 pm, "king kikapu" wrote: > > def modify(list_of_x): > > for x in list_of_x: > > try: > > x.change_in_place # don't call the method, just check it exists > > XXmmmm...what exactly is going on here ? I mean, what is actually > happens if you omit the parenethesis as you just did ? I understand > that it does not call the method, but what is really doing ?? See http://users.rcn.com/python/download/Descriptor.htm for more than you ever wanted to know about attribute access in Python. Michele Simionato From hg at nospam.org Sat Feb 10 11:34:14 2007 From: hg at nospam.org (hg) Date: Sat, 10 Feb 2007 17:34:14 +0100 Subject: wxPython libraries never detected References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> <1171143155.537545.9530@j27g2000cwj.googlegroups.com> Message-ID: hg wrote: > d.lidell at gmail.com wrote: > >> On Feb 10, 1:07 pm, hg wrote: >>> By default, you need to have wx installed in the python site-package >>> path / under Mandriva, I have wx 2.8 installed >>> here: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-ansi/ >>> >>> hg >> >> Ah, now I see. But I have a new problem: >> >> "ls /usr/lib/python2.4/site-packages | grep wx-2.8" returns "wx-2.8- >> gtk2-unicode" >> >> I copied wx-2.8-gtk2-unicode to /usr/lib/python2.5/site-packages/, >> which I assume the programs I am attempting to compile and run are >> using by default, but they still do not find the libraries. How can I >> tell where the programs are searching for the libraries? >> >> Thanks. > > If you're going to try the copy technique (never tried it) , you also need > to copy wx.pth and wxversion.py. > > hg Oh, and remember that a 2.4.pyc will not run with 2.5 ... so I would also remove all .pyc that I might have copied. hg From MI5Victim at mi5.gov.uk Tue Feb 27 11:42:34 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: Tue, 27 Feb 2007 16:42:34 +0000 (UTC) Subject: MI5 Persecution: Stand up for Free Speech 14/8/95 (363) Message-ID: From: rji at cheetah.inmos.co.uk (Richard Ingram) Newsgroups: uk.misc Date: Mon Aug 14 10:08:32 1995 Some cencorship loving bore wrote : > In article gevans at mvagusta.uk.tele.nokia.fi (Gareth Evans) writes: > > His sysadmin is also next to useless, and has not replied to my request or > even acknowledged it. Maybe this person *is* a sysadmin? > > He's not. It seems the public access site he uses has got no proper > management over its users. Here's a copy of a reply I got from a > complaint I made. [After returning every one of Corley's postings to [snip a large pile of winging complaining drivel] Geez what a bunch of tossers you all are - you don't like someones postings so you try and get him evicted from the net, why not just use a kill file - you DONT have to read his posts/threads now do you ? Why is it the net is getting populated by the biggest bunch of self absorbed little Hitlers ? You don't like someones posts so you bloody complain or mail bomb them - grow up you bunch of fucking sad gits ! Richard. 363 From dieterv at optionexplicit.be Mon Feb 26 17:09:19 2007 From: dieterv at optionexplicit.be (Dieter Verfaillie) Date: Mon, 26 Feb 2007 23:09:19 +0100 Subject: Newbie in the deep - some PyGTK questions In-Reply-To: <45e349ff$0$333$e4fe514c@news.xs4all.nl> References: <45ded1a1$0$325$e4fe514c@news.xs4all.nl> <45e349ff$0$333$e4fe514c@news.xs4all.nl> Message-ID: <1172527759.26450.19.camel@PO001> On Mon, 2007-02-26 at 20:58 +0000, nmp wrote: > I did that and it works now :) Thank you, I had indeed been playing with > those options but not being entirely sure what they did I also forgot > about them... Happy it worked out :) > Yes, I found that a short time after I posted my question and this seems > to be the way to go indeed. I already copied some code from somewhere that > worked. Now, it could just be me but I *still* find the Gtk/TreeView thing > confusing. To master it will take me a bit more time than I thought, but > it seems to be one of the most important pieces of the toolkit so I see I > will pretty much have to invest that time. Thank you for mentioning it too. Yep, it can be confusing at first, but once you get your head wrapped around it, it's a really powerful system. I've dug up some bookmarks about the GtkTree(View|Model|Store) and its Model/View/Controller approach. They might help you understand the big picture - a short overview: http://liw.iki.fi/liw/texts/gtktreeview-tutorial.html - and as noted on that page, Tim M?ller's tutorial: http://scentric.net/tutorial/ This one uses C, but is still very informative, even for a python programmer. There's also a lot of information in section 13 of the pygtk faq: http://www.async.com.br/faq/pygtk/index.py?req=index hth, Dieter From paddy3118 at netscape.net Wed Feb 7 01:48:47 2007 From: paddy3118 at netscape.net (Paddy) Date: 6 Feb 2007 22:48:47 -0800 Subject: multithreading concept In-Reply-To: References: Message-ID: <1170830927.625055.49430@p10g2000cwp.googlegroups.com> On Feb 7, 1:53 am, "S.Mohideen" wrote: > Hi Folks, > > Python is praised about - me too. But at one instance it fails. It fails to > behave as a true multi-threaded application. That means utilizing all the > CPUs parallely in the SMP efficiently stays as a dream for a Python > Programmer. > > Discussion threads say its due to GIL - global interpreter lock. But nobody > has mentioned any alternative to that apart from suggestions like "Code it > in C" and POSH (http://poshmodule.sf.net). Is there any other way we can > make Python programs really multithreaded in real sense. > > Moin Actually their are a *lot* more suggestions & discussions to be found. I myself move towards the "parallel processing is difficult. If you think it's easy then your either lucky or theorising. Whilst it would be nice to have threads==native threads for completeness sake, I'm quit happy to run concurrent communicating processes, as on my machines the OS helps me to see what's happening to the processes, and stops processes trampling over shared data". -Paddy. From robert.kern at gmail.com Mon Feb 19 22:34:23 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 19 Feb 2007 21:34:23 -0600 Subject: pylab, integral of sinc function In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > Hello, > > In [19]: def simple_integral(func,a,b,dx = 0.001): > ....: return sum(map(lambda x:dx*x, func(arange(a,b,dx)))) > ....: > > In [20]: simple_integral(sin, 0, 2*pi) > Out[20]: -7.5484213527594133e-08 > > ok, can be thought as zero > > In [21]: simple_integral(sinc, -1000, 1000) > Out[21]: 0.99979735786416357 > > hmm, it should be something around pi > it is a way too far from it, even with a=-10000,b=10000 > > In [22]: def ppp(x): > ....: return sin(x)/x > ....: > > In [23]: simple_integral(ppp, -1000, 1000) > Out[23]: 3.1404662440661117 > > nice > > is my sinc function in pylab broken? A couple things: 1) The function is not from pylab, it is from numpy. 2) Look at the docstring of the function, and you will notice that the convention that sinc() uses is different than what you think it is. In [3]: numpy.sinc? Type: function Base Class: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.2.dev3521-py2.5-macosx-10.3-fat.egg/numpy/lib/function_base.py Definition: numpy.sinc(x) Docstring: sinc(x) returns sin(pi*x)/(pi*x) at all points of array x. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From donn at drizzle.com Sat Feb 17 14:00:55 2007 From: donn at drizzle.com (Donn Cave) Date: 17 Feb 2007 19:00:55 GMT Subject: Approaches of interprocess communication References: <1171620696.577982.283740@m58g2000cwm.googlegroups.com> <87fy965plq.fsf@benfinney.id.au> Message-ID: <1171738855.785792@bubbleator.drizzle.com> Quoth Steve Holden : | Ben Finney wrote: ... | > If a programmer decides on behalf of the user that "localhost" should | > be treated specially, that programmer is making an error. | | Inter-process TCP/IP communication between two processes on the same | host invariably uses the loopback interface (network 127.0.0.0). | According to standards, all addresses in that network space refer to the | local host, though 127.0.0.1 is conventionally used. | | The transmit driver for the loopback interface receives a datagram from | the local network layer and immediately announces its reception back to | the local network layer. Are you saying, in that first paragraph, that if for example I telnet to my local host's external IP address, to a service that bound explicitly to the external interface -- I'll actually be going through the loopback interface anyway, invariably regardless of host network implementation? Donn Cave, donn at drizzle.com From nagle at animats.com Sat Feb 10 12:22:12 2007 From: nagle at animats.com (John Nagle) Date: Sat, 10 Feb 2007 17:22:12 GMT Subject: What does "del" actually do? Message-ID: <8bnzh.74754$qO4.52439@newssvr13.news.prodigy.net> The Python "reference manual" says, for "del", "Rather that spelling it out in full details, here are some hints." That's not too helpful. In particular, when "del" is applied to a class object, what happens? Are all the instance attributes deleted from the object? Is behavior the same for both old and new classes? I'm trying to break cycles to fix some memory usage problems. John Nagle From ian.inglis at gmail.com Fri Feb 2 04:34:42 2007 From: ian.inglis at gmail.com (Cruelemort) Date: 2 Feb 2007 01:34:42 -0800 Subject: LDAP/LDIF Parsing In-Reply-To: <1170371281.543905.261440@m58g2000cwm.googlegroups.com> References: <1170350547.740204.262410@k78g2000cwa.googlegroups.com> <1170371281.543905.261440@m58g2000cwm.googlegroups.com> Message-ID: <1170408882.195930.42260@a34g2000cwb.googlegroups.com> On Feb 1, 11:08 pm, "aspineux" wrote: > The tree hierarchy is defined by the DN of each object, the types of > the object is specified by its objectClass. > Just collect all items (or do it dynamically by tunning the scope and > the base of your search request) > > On 1 f?v, 18:22, "Cruelemort" wrote: > > > > > All, > > > I am hoping someone would be able to help me with a problem. I have an > > LDAP server running on a linux box, this LDAP server contains a > > telephone list in various groupings, the ldif file of which is - > > > dn: dc=example,dc=com > > objectClass: top > > objectClass: dcObject > > objectClass: organization > > dc: example > > o: Example Organisation > > > dn: ou=groupa,dc=example,dc=com > > ou: groupa > > objectClass: top > > objectClass: organizationalUnit > > description: Group A > > > dn: cn=johnsmith,ou=groupa,dc=example,dc=com > > cn: johnsmith > > objectClass: top > > objectClass: person > > sn: Smith > > telephoneNumber: 112 > > > dn: cn=davesteel,ou=groupa,dc=example,dc=com > > cn: davesteel > > objectClass: top > > objectClass: person > > sn: Steel > > telephoneNumber: 113 > > > dn: ou=groupb,dc=example,dc=com > > ou: groupb > > objectClass: top > > objectClass: organizationalUnit > > description: Group B > > > dn: cn=williamdavis,ou=groupb,dc=example,dc=com > > cn: williamdavis > > objectClass: top > > objectClass: person > > sn: Davis > > telephoneNumber: 122 > > > dn: cn=jamesjarvis,ou=groupb,dc=example,dc=com > > cn: jamesjarvis > > objectClass: top > > objectClass: person > > sn: Jarvis > > telephoneNumber: 123 > > > I am creating a python client program that will display the telephone > > list in the same directory structure as is on the LDAP server (i.e. it > > starts with buttons of all the groups, when you click on a group it > > comes up with buttons of all the numbers or groups available, and you > > can continually drill down). > > > I was wondering the best way to do this? I have installed and used the > > python-ldap libraries and these allow me to access and search the > > server, but the searches always return a horrible nesting of lists, > > tuples and dictionaries, below is an example of returning just one > > record - > > > ('dc=example,dc=com', {'objectClass': ['top', 'dcObject', > > 'organization'], 'dc': ['example'], 'o': ['Example Organisation']}) > > > Basically i think i need to parse the search results to create objects > > and build the python buttons around this, but i was hoping someone > > would be able to point me in the correct direction of how to do this? > > Is there a parser available? (there is an ldif library available but > > it is not obvious how this works, i cannot see much documentation, and > > it seems to be deprecated...). > > > Many thanks. > > > Ian- Hide quoted text - > > - Show quoted text - Thanks for the replies all - it was a higher level wrapper like Bruno mentioned that i was looking for (with objects and attributes based on each objectClass), but the code posted above will work fine. Many thanks all. Ian From hg at nospam.org Fri Feb 2 08:46:43 2007 From: hg at nospam.org (hg) Date: Fri, 02 Feb 2007 14:46:43 +0100 Subject: Where Does One Begin? References: Message-ID: Mister Newbie wrote: > I have no programming experience. I want to learn Python so I can make > simple, 2D games. Where should I start? Can you recommend a good book? > > Thank you. http://www.diveintopython.org/ From steven.bethard at gmail.com Tue Feb 20 22:02:06 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 20 Feb 2007 20:02:06 -0700 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <1172004973.139495.311980@h3g2000cwc.googlegroups.com> <1172008387.851412.181530@p10g2000cwp.googlegroups.com> Message-ID: Steven Bethard wrote: > So as a Python programmer, the path is clear. As soon as possible, you > should make your code compatible with Python 3.0. John Nagle wrote: > There's always the possiblity that Python 3 won't happen. That's not really a possibility. Unlike Perl 6, Python 3 is not a new language. And you can see Guido's release plan here: http://www.python.org/dev/peps/pep-3000/ In brief: * An alpha in the first half of 2007 * First real release in the first half of 2008 STeVe From 3dbernard at gmail.com Wed Feb 14 15:41:23 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 14 Feb 2007 15:41:23 -0500 Subject: How much memory used by a name In-Reply-To: <45d36eea$0$24957$426a74cc@news.free.fr> References: <45d36eea$0$24957$426a74cc@news.free.fr> Message-ID: <61d0e2b40702141241o188b710bg408b1a4c703183a0@mail.gmail.com> Diez: thanks, I will try that. However isn't sum() returning an integer that here would represent the number of elements? Bruno: good question. We're talking about text files that can have 300,000 lines, if not more. Currently, the way I have coded the file writing, every line calls for a write() to the file object, which in turns write to the text file. The file is on the network. This is taking a long time, and I'm looking for ways to speed up this process. I though that keeping the list in memory and dropping to the file at the very end could be a possible approach. Bernard On 2/14/07, Bruno Desthuilliers wrote: > Bernard Lebel a ?crit : > > Hello, > > > > I would like to know if there is a way to know how much memory (bytes, > > kilobytes, megabytes, etc) a name is using. > > > > More specifically, I have this list of strings that I want to write to > > a file as lines. > > This list grows througout the script execution, and toward the end, > > the file is written. > > Do you really need to first grow the list then write it ? > > -- > http://mail.python.org/mailman/listinfo/python-list > From fperez.net at gmail.com Sun Feb 25 18:09:47 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Sun, 25 Feb 2007 16:09:47 -0700 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> <1172432910.457442.232480@s48g2000cws.googlegroups.com> Message-ID: aleaxit at gmail.com wrote: > gmpy itself is or should be pretty trivial to build on any platform > (and I'll always happily accept any fixes that make it better on any > specific platform, since it's easy to make them conditional so they'll > apply to that platform only), but the underlying GMP is anything but:- > (. Alex, have you had a look at SAGE? http://modular.math.washington.edu/sage/ it uses GMP extensively, so they've had to patch it to work around these issues. You can look at the SAGE release (they package everything as the original tarball + patches) for the GMP-specific stuff you need, though I suspect you'll still want to play with SAGE a little bit :). It's a mighty impressive system. Cheers, f From bg_ie at yahoo.com Fri Feb 23 09:38:41 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 23 Feb 2007 06:38:41 -0800 Subject: Finding non ascii characters in a set of files Message-ID: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> Hi, I'm updating my program to Python 2.5, but I keep running into encoding problems. I have no ecodings defined at the start of any of my scripts. What I'd like to do is scan a directory and list all the files in it that contain a non ascii character. How would I go about doing this? Thanks, Barry. From aspineux at gmail.com Fri Feb 2 15:06:36 2007 From: aspineux at gmail.com (aspineux) Date: 2 Feb 2007 12:06:36 -0800 Subject: result of os.times() is different with 'time' command In-Reply-To: <1170441001.097986.294510@h3g2000cwc.googlegroups.com> References: <1170441001.097986.294510@h3g2000cwc.googlegroups.com> Message-ID: <1170446796.156141.201960@v33g2000cwv.googlegroups.com> I dont see anything wrong ! Did you try to measure time with your watch ? Did you try a simple python test.py without the time command ? Maybe python is 'disturbed' by the intel core Here my result on a linux dual AMD, python 2.4.3 # time python test.py n=35, v=14930352 utime=22.54, stime=0.02 real 0m22.755s user 0m22.564s sys 0m0.022s can you try this ? # strace python test.py 2>&1 | grep time times({tms_utime=1, tms_stime=1, tms_cutime=0, tms_cstime=0}) = 430217777 times({tms_utime=2238, tms_stime=2, tms_cutime=0, tms_cstime=0}) = 430220049 write(1, "n=35, v=14930352\nutime=22.37, st"..., 41n=35, v=14930352 utime=22.37, stime=0.01 now you can compare what your system replied and what python returned ! On 2 f?v, 19:30, kwa... at gmail.com wrote: > Hi, > > I have a question about os.times(). > os.times() returns a tuple containing user time and system time, > but it is not matched to the result of 'time' command. > For example, os.times() reports that user time is 39.85 sec, > but 'time' command reports that user time is 28.55sec. > (machine: Python2.5, MacOS X 10.4 Tiger, MacBook 1.83GHz intel core > duo) > > file: ostimetest.py > -------------------- > import os > > ## benchmark function > def f(x): > if x <= 1: > return 1 > else: > return f(x-1) + f(x-2) > > ## do benchmark > n = 35 > t1 = os.times() # start time > v = f(n) # end time > print "n=%d, v=%d" % (n, v) > t2 = os.times() > > ## print result > utime = t2[0] - t1[0] # user time > stime = t2[1] - t1[1] # system time > print "utime=%s, stime=%s" % (utime, stime) > -------------------- > > Result: > ==================== > $ python -V > Python 2.5 > $ time python ostimetest.py > n=35, v=14930352 > utime=39.85, stime=0.216666666667 > real 0m28.554suser 0m23.938ssys 0m0.177s > ==================== > > This shows that os.times() reports that user time is 39.85sec, > but time command shows that user time is 23.938sec. > Why os.times() reports wrong result? Do I have any mistake? > > -- > kwatch From steve at REMOVE.THIS.cybersource.com.au Mon Feb 26 17:21:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Feb 2007 09:21:51 +1100 Subject: modifying a list while iterating through References: <1172452339.035263.182250@q2g2000cwa.googlegroups.com> <1172456132.151803.75800@p10g2000cwp.googlegroups.com> <1172526336.150880.291720@z35g2000cwz.googlegroups.com> Message-ID: On Mon, 26 Feb 2007 13:45:36 -0800, dustin.getz wrote: > My original question still stands, though, in situations where a > simple string replacement might not be sufficient. Is there a way to > insert into a list whilst iterating through it? Inserting/deleting from a list while you're walking through it is *always* tricky, by its very nature. Deletions are easy to deal with: iterate over the list backwards. When you delete the current item, the only items that are re-numbered are items you've already looked at. Similarly, if you iterate backwards over the list and make sure you only insert after the current item, never before, you can avoid re-numbering items you haven't looked at yet. Another solution is to iterate over the list, creating a new list as you go: new = [] for item in some_list: if condition: # delete the item pass elif other_condition: # insert something new.extend(['something', item]) else: new.append(item) > for example, consider a list of binary values. > > for index in range(len(iterable)): > item=iterable[index] The Pythonic way to write that is for index,item in enumerate(iterable): pass > if item==1: > iterable.insert(index,0) "Iterables" are sequences and iterators -- anything you can iterate over. In general, only sequences can be inserted into (and not even all sequences). > obv this wouldn't work because now all future indexes will be off by the > number of previously inserted items. > > using a while loop to fix this ugly and counterintuitive. Well, if you insist on doing a tricky job, you're always going to have tricky code. Here's one solution: # inserting into a mutable sequence sequence.reverse() for index in range(len(sequence)-1, -1, -1): item = sequence[index] if item == 1: sequence.insert(index+1, 0) sequence.reverse() Here's a solution that should work for any iterable, provided you have sufficient memory: # inserting into a copy of iterable copy = [] for item in iterable: if item == 1: copy.append(0) copy.append(item) Hope this helps. -- Steven. From silverbeach06 at gmail.com Sun Feb 11 23:53:21 2007 From: silverbeach06 at gmail.com (susan) Date: 11 Feb 2007 20:53:21 -0800 Subject: No module named pyExcelerator Error In-Reply-To: References: <1171241735.081533.322510@a34g2000cwb.googlegroups.com> Message-ID: <1171256001.216845.195760@q2g2000cwa.googlegroups.com> On Feb 11, 11:22 pm, Samuel Karl Peterson wrote: > "susan" on 11 Feb 2007 16:55:35 -0800 didst > step forth and proclaim thus: > > > Hi, > > I'm new of Python, and this problem stucked me whole day but can't be > > solved. > > [snip] > > > anybody can tell me where's wrong please? Thanks in advance! > > What are the contents of sys.path from an interactive prompt? Have > you tried the official windows Python? Is there a reason you need to > use the cygwin Python? > > -- > Sam Peterson > skpeterson At nospam ucdavis.edu > "if programmers were paid to remove code instead of adding it, > software would be much better" -- unknown Hi Sam, There's no any special reason I use cygwin python, I just feel it's easy and convinent to download and install. Do you have any better suggestion? From http Wed Feb 14 21:03:19 2007 From: http (Paul Rubin) Date: 14 Feb 2007 18:03:19 -0800 Subject: try...except...finally problem in Python 2.5 References: <1171482088.993720.69620@l53g2000cwa.googlegroups.com> <7x3b58jybl.fsf@ruckus.brouhaha.com> Message-ID: <7xr6ssqis8.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > self.isDataLoaded = False > try: > f = open(self.filename, 'rb') > f.seek(DATA_OFFSET) > self.__data = f.read(DATA_SIZE) > self.isDataLoaded = True > except: > pass > else: > pass > > (apart from being four lines shorter) Your version never closes the file. From rw at smsnet.pl Mon Feb 19 08:17:03 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 19 Feb 2007 05:17:03 -0800 Subject: How do I create an array of functions? In-Reply-To: References: <1171872999.751809.256880@p10g2000cwp.googlegroups.com> Message-ID: <1171891023.613866.312260@s48g2000cws.googlegroups.com> Steven D'Aprano wrote: > On Mon, 19 Feb 2007 00:16:39 -0800, Rob Wolfe wrote: > > > > > Steven W. Orr wrote: > >> I have a table of integers and each time I look up a value from the table > >> I want to call a function using the table entry as an index into an array > >> whose values are the different functions. I haven't seen anything on how > >> to do this in python. > > > > Do you mean something like that? > > > > # test.py > > > > def fun1(): return "fun1" > > def fun2(): return "fun2" > > def fun3(): return "fun3" > > > > # list of functions > > dsp = [f for fname, f in sorted(globals().items()) if callable(f)] > > Hmmm... when I try that, I get dozens of other functions, not just fun1, > fun2 and fun3. And not just functions either; I also get classes. Oh, really? Where are these _other_ functions and classes in *MY* example? > Does Python have a function that will read my mind and only return the > objects I'm thinking of? Your sarcasm is unnecessary. Using of `globals` function was easier to write this example. That's all. -- Rob From mike.klaas at gmail.com Fri Feb 9 17:30:43 2007 From: mike.klaas at gmail.com (Klaas) Date: 9 Feb 2007 14:30:43 -0800 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: <1170988670.576168.205640@v33g2000cwv.googlegroups.com> References: <1170988167.356729.187920@v33g2000cwv.googlegroups.com> <1170988670.576168.205640@v33g2000cwv.googlegroups.com> Message-ID: <1171060243.501374.249430@a75g2000cwd.googlegroups.com> On Feb 8, 6:37 pm, "kernel1983" wrote: > On Feb 9, 10:29 am, "Klaas" wrote: > > The changes listed dont' seem particularly huge considering the size, > > complexity, and boundary-pushingness of Twisted, coupled with the > > magnitude of the 2.5 release. > > Just keep using python2.4 I have converted our 100 kloc from 2.4 to 2.5. It was relatively painless, and 2.5 has features we couldn't live without. -Mike From jstroud at mbi.ucla.edu Sun Feb 11 07:02:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 11 Feb 2007 12:02:31 GMT Subject: Regular Expressions In-Reply-To: <1171162731.488726.160400@a75g2000cwd.googlegroups.com> References: <1171162731.488726.160400@a75g2000cwd.googlegroups.com> Message-ID: gregarican wrote: > On Feb 10, 6:26 pm, "Geoff Hill" wrote: >> What's the way to go about learning Python's regular expressions? I feel >> like such an idiot - being so strong in a programming language but knowing >> nothing about RE. > > I highly recommend reading the book "Mastering Regular Expressions," > which I believe is published by O'Reilly. It's a great reference and > helps peel the onion in terms of working through RE. They are a > language unto themselves. A fun brain exercise. > There is no real mention of python in this book, but the first edition is probably the best programming book I've ever read (excepting, perhaps Text Processing in Python by Mertz.) Well, come to think of it, check the latter book out. It has a great chapter on Python Regex. And its free to download. James From mensanator at aol.com Sun Feb 11 12:08:06 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 11 Feb 2007 09:08:06 -0800 Subject: pygame and python 2.5 In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> <1171184901.012350.40140@q2g2000cwa.googlegroups.com> Message-ID: <1171213686.383076.280390@j27g2000cwj.googlegroups.com> On Feb 11, 4:24 am, Steve Holden wrote: > mensana... at aol.com wrote: > > On Feb 11, 1:35?am, Steve Holden wrote: > [...] > >>>> After all, they have already given freely and generously, and if they choose > >>>> not to give more on top of that, it's really up to them. > >>> Right. Get people to commit and then abandon them. Nice. > >> Anyone who committed to Python did so without being battered by a > >> multi-million dollar advertising campaign. > > > Multi-million dollar ad campaigns mean nothing to me. > > I committed to Python because it's a great language. > > I've dabbled in perl, Visual BASIC, UBASIC, REXX, Java, > > Scheme, C and C++ but Python is the one I use. > > Yes, but your decision must surely have been an informed one, and there > must surely be reasons why Python remains your choice. > > > > > > >> The Python Software > >> Foundation has only recently dipped its toes in the advocacy waters, > >> with results that are still under evaluation. And the use of the > >> Microsoft "free" VC6 SDK was never a part of the "official" means of > >> producing Python or its extensions, it was a community-developed > >> solution to the lack of availability of a free VS-compatible compilation > >> system for extension modules. > > >> I agree that there are frustrations involved with maintaining extension > >> modules on the Windows platform without having a copy of Visual Studio > >> (of the correct version) available. One of the reasons Python still uses > >> an outdated version of VS is to avoid forcing people to upgrade. Any > >> such decision will have fallout. > > > Such as anyone who tries to get in the game late. > > I'm afraid it does seem to work out like that, yes. > > >> An update is in the works for those > >> using more recent releases, > > > That's good news, although the responsible thing > > to do was not relaease version 2.5 until such issues > > are resolved. > > Well that would be an issue for the release team. I'm not sure what > Anthony Baxter (the release manager) would have to say in response to > this point. Possibly something like: "I realize you're a Windows user, and a Windows user with an AOL email address at that, so it may come as a shock to learn that the computer industry doesn't start and finish on Windows. I don't see why the needs of Windows users like yourself should come ahead of the needs of users on Mac OS, Linux, Solaris, etc." - Steven D'Arpano I would hope that it would instead be that the needs of all users are equal. > > >> but that won't help users who don't have > >> access to Visual Studio. > > > That can be solved by throwing money at the problem. > > But money doesn't help when the solution is on the > > far side of the moon. > > I see your problem, but I don't know what I can do to help you. Well, that was the point of this, to get people to see the problem. > There > were also, as I remember it, issues with the updated version of Visual > Studio being non-conformant with standards in some significant way, but > I never took part in the discussions on those issues. > > >>>> Yes, it's > >>>> occasionally very frustrating to the rest of us, but that's life. > >>> As the Kurds are well aware. > >> I really don't think you help your argument by trying to draw parallels > >> between the problems of compiler non-availability and those of a > >> population subject to random genocide. > > > You missed the point of the analogy. > > Perhaps because it wasn't a very good one? > > > > > > > The US government suggested to the oppressed tribes > > in Iraq that they should rise up and overthrow > > Saddam Hussein at the end of the first Gulf War. > > And what did the US government do when they rose up? > > Nothing. They were left to twist in the wind. > > >> Try to keep things in perspective, please. > > > See if you can see the similarity. > > > I buy into Python. I spend a lot of effort > > developing a math library based on GMPY to use > > in my research. I discover a bug in GMPY and > > actually go to a lot of effort and solve it. > > But _I_ can't even use it because I've been > > left to twist in the wind by the fact that > > Python 2.5 for Windows was built with an > > obsolete compiler that's not even available. > > > Luckily, unlike the Kurds, my situation had > > a happy ending, someone else compiled the fixed > > GMPY source and made a 2.5 Windows version > > available. But can anyone say what will happen > > the next time? > > Presumably not. I presume you have been reporting your bugs through the > Sourceforge project to keep the developers in touch with the issues you > have found? Last time I tried, it didn't work and e-mail to the maintainer didn't get any response. > Normally a package's maintainers will produce updated > installers, Unless they have stopped doing Windows developement as part of their job as is the case with GMPY. Luckily, there's someone out there who does create Windows binaries. > but this behaviour is unreliable and (no pun intended) > patchy sometimes. > > > > > > >>>> The best I feel I can do is raise these things on occasion, > >>>> on the off-chance that I manage to catch the attention of > >>>> someone who is > >>>> altruistic, knowledgeable, and who has some spare time on > >>>> their hands! > >>> Someone who, say, solved the memory leak in the GMPY > >>> divm() function even though he had no way of compiling > >>> the source code? > >>> Just think of what such an altruistic, knowedgeable > >>> person could do if he could use the current VC compiler > >>> or some other legally available compiler. > >> Your efforts would probably be far better spent trying to build a > >> back-end for mingw or some similar system into Python's development > >> system, to allow Python for Windows to be built on a regular rather than > >> a one-off basis using a completely open source tool chain. > > > No, as I said elsewhere, I'm not a software developer, > > I'm an amateur math researcher. My efforts are best spent > > as an actual end user to find and report bugs that the > > developers never see. Remember, a programmer, because he > > wrote it, only _thinks_ he knows how the program works. > > Whereas I, the user, _know_ how it works. > > >> The fact that the current maintainers of the Windows side of Python > >> choose to use a commercial tool to help them isn't something I am going > >> to try and second-guess. To do so would be to belittle efforts I would > >> have no way of duplicating myself, and I have far too much respect for > >> those efforts to do so. > > > And I respect those efforts too. What I don't respect > > is irresponsible behaviour. > > >> There are published ways to build extension modules for Windows using > >> mingw, by the way - have you tried any of them? > > > Yeah, and got nowhere. > > >> It's much harder than sniping on a newsgroup, > > > That figures. You try and contribute and you get > > accused of being a troll. > > I wasn't accusing you of being a troll, rather bemoaning your (in my > opinion) less-than-constructive tone. The squeaky wheel gets the grease. > The points you raise are > important, and I do feel that there ought to be easier solutions for > people in your position. That's all I'm asking for is for others to appreciate the situation. > > >> but you earn rather more kudos. > > > Guess what kudos I got for solving the GMPY divm() > > problem? None. How much effort would it have been > > to mention my contribution in the source code > > comments (as was the case for other contributers)? > > Not that I'm bitter, after all, I'm altruistic. > > I'm sure if you've made a contribution to the code you only have to ask > for your name to be added as a contributor to be mentioned in the source. That wasn't important, I'm not that petty. It was simply a real-world example. > > > By the way, on the sci.math newsgroup I promote > > Python every chance I get. One fellow thanked me > > profusely for recommending Python & GMPY and asked > > for some help with a program he was having problems > > with. We worked it out fine but his problem made me > > suspect there may be more bugs in GMPY. What's my > > motivation for tracking them down? > > The satisfaction of a job well done? What's my motivation for acting as > a director of the Python Software Foundation when I get accusations of > irresponsibility? I apologize. But I hope you see how this appears from the outside, that the PSF doesn't give a rat's ass about Windows users with AOL addresses. Sure, that's wrong, but calling people who bring up these points whiny leeches doesn't do anything to dispell that notion. > Anyway, thanks for taking the time to help maintain gmpy. Thanks, I try to help as much as I can. I'm a little sensitive about gmpy because without it, I would have to abandon Python and I don't want to abandon Python. > > This thread is starting to make me think that there's a case to be made > for somehow providing supported build facilities for third-party > extension modules. And the untouchables would greatly appreciate it. > > This wouldn't be a simple project, but since there's a Windows buildbot > for Python there's no reason why the same couldn't be done for > extensions. I'll raise this with the PSF and see what the response is: > then your carping will at least have had some positive effect ;-) > > Stick with it, and let's try to make things better. Ok. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > See you at PyCon? http://us.pycon.org/TX2007 From rrr at ronadam.com Fri Feb 2 11:07:25 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 02 Feb 2007 10:07:25 -0600 Subject: from __future__ import absolute_import ? Message-ID: from __future__ import absolute_import Is there a way to check if this is working? I get the same results with or without it. Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 _Ron From kylotan at gmail.com Sat Feb 10 17:07:57 2007 From: kylotan at gmail.com (Ben Sizer) Date: 10 Feb 2007 14:07:57 -0800 Subject: pygame and python 2.5 In-Reply-To: <1171089103.528193.157800@v33g2000cwv.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> Message-ID: <1171145277.777740.179060@h3g2000cwc.googlegroups.com> On Feb 10, 6:31 am, "mensana... at aol.com" wrote: > On Feb 9, 11:39?am, "Ben Sizer" wrote: > > > Hopefully in the future, some of those convoluted steps will be fixed, > > but that requires someone putting in the effort to do so. As is often > > the case with Python, and indeed many open source projects, the people > > who are knowledgeable enough to do such things usually don't need to > > do them, as their setup already works just fine. > > So you're saying the knowledgeable people's attitude > is "fuck everyone else as lomg as it's not MY problem"? > > And you people complain about Microsoft. Am I one of "those people"? You don't exactly make it clear. But yes, there is a lot of "well, it works for me" going around. If you do that long enough, people stop complaining, so people wrongly assume there's no longer a problem. This is partly why Python has various warts on Windows and why the standard libraries are oddly biased, why configuring Linux almost always ends up involving hand- editing a .conf file, why the leading cross-platform multimedia library SDL still doesn't do hardware graphics acceleration a decade after such hardware became mainstream, and so on. However, the difference between the open-source people and Microsoft is the the open-source people aren't being paid by you for the use of their product, so they're not obligated in any way to help you. After all, they have already given freely and generously, and if they choose not to give more on top of that, it's really up to them. Yes, it's occasionally very frustrating to the rest of us, but that's life. The best I feel I can do is raise these things on occasion, on the off- chance that I manage to catch the attention of someone who is altruistic, knowledgeable, and who has some spare time on their hands! -- Ben Sizer From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 15:58:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 21:58:31 +0100 Subject: Sorting a list In-Reply-To: <45c24563$0$31965$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c24563$0$31965$c3e8da3@news.astraweb.com> Message-ID: <45c24d7f$0$29592$426a74cc@news.free.fr> John Salerno a ?crit : > Bruno Desthuilliers wrote: > >> You don't tell how these lines are formatted, but it's possible that >> you don't even need a regexp here. But wrt/ sorting, the list of >> tuples with the sort key as first element is one of the best solutions. > > > Ah, so simply using sort() will default to the first element of each tuple? Yes. Then on the second value if the first compares equal, etc... > The citations are like this: > > lastname, firstname. (year). title. other stuff. Then you theoretically don't even need regexps: >>> line = "lastname, firstname. (year). title. other stuff." >>> line.split('.')[1].strip().strip('()') 'year' But since you may have a dot in the "lastname, firstname" part, I'd still go for a regexp here just to make sure. From inq1ltd at verizon.net Tue Feb 13 23:04:58 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Tue, 13 Feb 2007 23:04:58 -0500 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: Message-ID: <200702132304.58598.inq1ltd@verizon.net> For those who care, the file below should run on a unix/ linux style system. And "xpdf", amoung others, will run a pdf file. import os def Printpdf(): os.system( 'xpdf form.pdf' ) if __name__ == '__main__' : Printpdf() jim-on-linux > On Tue, 13 Feb 2007 08:44:18 GMT, Jussi Salmela > > declaimed the following in comp.lang.python: > > On Windows, this (where fileName is xyz.PDF, > > for example): webbrowser.open(r'file://' + > > fileName) starts Acrobat Reader with the > > document read in. I have no idea why, because > > Acrobat Reader sure ain't my browser;) > > Most likely Adobe installed the Acrobat > plug-in for the browser... The browser > identifies the file as PDF and passes it to the > plug-in for rendering. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support > Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From steveo at syslang.net Fri Feb 9 16:04:16 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 9 Feb 2007 16:04:16 -0500 (EST) Subject: Retry:Question about optparse/OptionParser callback. Message-ID: I decided I could be more articulate. I hope this helps. I'm writing a program that needs to process options. Due to the nature of the program with its large number of commandline options, I would like to write a callback to be set inside add_option. Something like this: parser.add_option("-b", action="callback", callback=optionhandlr, dest='b') The Cookbook almost takes me there with a callback function that only works for an option called b that takes no argument: def optionhndlr(option, opt_str, value, parser): if parser.values.b: raise OptionValueError("can't use %s after -b" % opt_str) setattr(parser.values, option.dest, 1) but warns that "it needs a bit of work: the error message and the flag that it sets must be generalized". I do need to do my option processing in an option processor with many options and I'd both like to do it in one method (if possible) and learn a trick or two while I'm at it. Is it possible to have a single callback that could be used in the general case? All I need is to be taught how to fish... TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From limodou at gmail.com Wed Feb 7 19:04:06 2007 From: limodou at gmail.com (limodou) Date: Thu, 8 Feb 2007 08:04:06 +0800 Subject: Python editor In-Reply-To: <800d8$45ca30ae$d443bb3a$20806@news.speedlinq.nl> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> <1170851197.656670.179590@a75g2000cwd.googlegroups.com> <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> <800d8$45ca30ae$d443bb3a$20806@news.speedlinq.nl> Message-ID: <505f13c0702071604t67232a93jb71712004095a4e8@mail.gmail.com> On 2/8/07, Stef Mientki wrote: > limodou wrote: > > Maybe you can try ulipad. > > > thanks, > although it doesn't look bad, > and it certainly must have been a huge job doing this with Tcl/Tk, You are wrong, UliPad is based on wxPython, but not Tcl/Tk. > I don't think it can compete with PyScripter, > except on Linux ;-) > Have you try it? It has many features. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From rune.strand at gmail.com Wed Feb 14 10:40:10 2007 From: rune.strand at gmail.com (Rune Strand) Date: 14 Feb 2007 07:40:10 -0800 Subject: rot13 in a more Pythonic style? In-Reply-To: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: <1171467609.311984.62030@p10g2000cwp.googlegroups.com> You could try "some_string".encode('rot_13') From jonc at icicled.net Mon Feb 12 00:30:24 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sun, 11 Feb 2007 23:30:24 -0600 Subject: message processing/threads Message-ID: <200702112330.24391.jonc@icicled.net> I've been thinking about this for a bit and wanted some input as to the design of it. The problem is as such: I need a program running in the background to process messages (FIFO order) which I would send using soap/xmlrpc/pyro (haven't decided yet). According to my thinking I would need to make this a threaded application. One thread to process the messages and the other thread(s) would be used to listen for messages and insert it into the message queue. Is my thinking correct? Is there a better way to do such a thing? Thanks for any input, - Jonathan From tech-hr at smartcharter.com Tue Feb 27 01:46:55 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Mon, 26 Feb 2007 22:46:55 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: In article , Dan Bensen wrote: > Tech HR wrote: > > easier to train a Java programmer or a Perler on Python than Lisp. > > Are your technical problems simple enough to be solved by Python trainees? Some are. Some aren't. That's why we're using Lisp too :-) From gisdudester at gmail.com Mon Feb 19 10:21:27 2007 From: gisdudester at gmail.com (GISDude) Date: 19 Feb 2007 07:21:27 -0800 Subject: search cursor in pythonwin 2.1 In-Reply-To: References: <1171815140.829723.87940@a75g2000cwd.googlegroups.com> Message-ID: <1171898487.585051.125470@q2g2000cwa.googlegroups.com> On Feb 18, 2:19 pm, "Gabriel Genellina" wrote: > En Sun, 18 Feb 2007 13:12:20 -0300, GISDude > escribi?: > > > I am a GIS(geographic information systems) Analyst and in our > > software(ESRI ARCGIS 9.1) ESRI has implemented Python 2.1 as the > > scripting language of choice. > > > In my script I'm going thru a dbf file and extracting NON-NULL values > > in a field. What I need to do with that is create a new dbf table with > > the values I found in it. > > I think you should either read the ArcGis documentation, or post your > question in a specilized forum. > Your problem is not about Python itself, but on how to use the > esriGeoprocessing object. > > > GP.Select_Analysis("neighborhoods.shp", "neighborhoods_names.shp", ' > > "Names" <> \ "null\" ') > > > #at this point I'm stuck. how do I query out a NON- > > NULL value? > > #or a value in the Names field? > > As a side note, on a standard SQL database, the condition would read > "Names IS NOT NULL", but I don't know if this is applicable or not. > > -- > Gabriel Genellina Gabriel, Thanks for the reply. After looking at the docs again, you are correct "NAMES" IS NOT NULL would be the correct syntax. I thought it was "NAMES" <> NULL Thanks again From harlinseritt at yahoo.com Wed Feb 21 18:50:53 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 21 Feb 2007 15:50:53 -0800 Subject: Convert to binary and convert back to strings Message-ID: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> Hi... I would like to take a string like 'supercalifragilisticexpialidocius' and write it to a file in binary forms -- this way a user cannot read the string in case they were try to open in something like ascii text editor. I'd also like to be able to read the binary formed data back into string format so that it shows the original value. Is there any way to do this in Python? Thanks! Harlin From marcel.vandendungen at gmail.com Tue Feb 13 16:18:35 2007 From: marcel.vandendungen at gmail.com (Marcel) Date: 13 Feb 2007 13:18:35 -0800 Subject: Scripting Visio using Python In-Reply-To: <53ec6aF1rdistU1@mid.individual.net> References: <53ec6aF1rdistU1@mid.individual.net> Message-ID: <1171401515.187070.104510@a75g2000cwd.googlegroups.com> On Feb 13, 6:52 pm, Paul Watson wrote: > I would like to create some additional shapes in Microsoft Visio using > the Python language. It would appear that Visio can use any CLR > language. Has anyone done this? Can I use the Python package from > python.org, or must I use IronPython? Don't know how to do that, but I suggest you post your question on the IronPython list: http://groups.google.com/group/ironpy?lnk=li Python is not a .NET language, IronPython is. HTH, -- Marcel From mail at timgolden.me.uk Fri Feb 16 16:28:14 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 16 Feb 2007 21:28:14 +0000 Subject: Group Membership in Active Directory Query In-Reply-To: <1171657057.416791.108970@v33g2000cwv.googlegroups.com> References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> <1170859017.416570.247920@v33g2000cwv.googlegroups.com> <1170872824.710879.272830@v45g2000cwv.googlegroups.com> <1170895960.022698.299500@h3g2000cwc.googlegroups.com> <1170942292.620399.102000@m58g2000cwm.googlegroups.com> <1171657057.416791.108970@v33g2000cwv.googlegroups.com> Message-ID: <45D621EE.5000808@timgolden.me.uk> Kooch54 wrote: >> Thanks for your response and Uwe I apologize if I misunderstood >> and misinterpreted your comments. I am sorry. >> I have tried Tim's module called active_directory and it works really >> well. But I can't figure out how to connect to a specific group is I >> know the common name for it but not the DN and then return it's >> members. For the simple "group in my domain" situation, as far as I can see you can do something like this: import active_directory for group in active_directory.search ( "sAMAccountName='sharedaccess'", "objectClass='group'" ): print group for member in group.members: print member (I'm not on an AD-connected machine just now, but I think that'll do it). As to finding it another domain, I'm not sure. I suspect that if you simply issue the above query, you'll get the groups back from all domains in the forest. But I'm not sure about that. In essence this isn't a Python question as such. If you can find out from any source how to formulate the query in an AD way, I'm quite sure we can translate that easily into Python. I'm afraid that my AD module is a very lightweight wrapper over the LDAP:// object system and offers very little support (and gets very little attention from me). Hopefully I can have a boost of energy & time and give it some help. TJG From timothy.kellogg at gmail.com Sun Feb 4 12:32:42 2007 From: timothy.kellogg at gmail.com (timothy.kellogg at gmail.com) Date: 4 Feb 2007 09:32:42 -0800 Subject: HELP NEEDED ... Regd. Regular expressions PyQt In-Reply-To: References: Message-ID: <1170610362.021672.71750@v33g2000cwv.googlegroups.com> On Feb 3, 11:40 am, Marc 'BlackJack' Rintsch wrote: > In , vishal wrote: > > I am trying to work out a regular expression in a PyQt environment for > > time in hh:mm:ss format. Any suggestions? > > Maybe don't use a re for something that simple. Splitting at ``:`` > characters, converting to `int` and checking the value ranges isn't that > hard without a regular expression. > > Ciao, > Marc 'BlackJack' Rintsch Except that if a full regex is used, the pattern can be matched or denied and pull out the important information simultaneously. Here's a simple regex that would work: (\d{1,2}):(\d{1,2}):(\d{1,2}) but here's one that works only for the 12 hour clock: ((1[012])|(0?\d)):([0-5]?\d):([0-5]?\d) and one for the 24 hour clock: ((2[0-4])|([01]?\d)):([0-5]?\d):([0-5]?\d) I hope this helps --Tim From skip at pobox.com Sun Feb 25 06:22:42 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 25 Feb 2007 05:22:42 -0600 Subject: Is there any way to automatically create a transcript of an interactive Python session? In-Reply-To: <1171842673.363336.121080@l53g2000cwa.googlegroups.com> References: <1171842673.363336.121080@l53g2000cwa.googlegroups.com> Message-ID: <17889.29058.112024.695378@montanaro.dyndns.org> Jonathan> Some languages, such as Scheme, permit you to make a Jonathan> transcript of an interactive console session. Is there a way Jonathan> to do that in Python? If you decide not to use IPython for some reason, you should be able to easily whip something up based on the command history features of the readline module or one of the interpreter classes in the code module. Skip From sjmachin at lexicon.net Wed Feb 28 16:29:59 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2007 13:29:59 -0800 Subject: finding out the precision of floats In-Reply-To: <1172683149.885750.323640@j27g2000cwj.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172674419.411077.4210@t69g2000cwt.googlegroups.com> <1172683149.885750.323640@j27g2000cwj.googlegroups.com> Message-ID: <1172698199.219016.57710@v33g2000cwv.googlegroups.com> On Mar 1, 4:19 am, "Bart Ogryczak" wrote: > On Feb 28, 3:53 pm, "John Machin" wrote: > > > On Feb 28, 10:38 pm, "BartOgryczak" wrote: > > > > [1] eg. consider calculating interests rate, which often is defined as > > > math.pow(anualRate,days/365.0). > > > > More importantly, the formula you give is dead wrong. The correct > > formula for converting an annual rate of interest to the rate of > > interest to be used for n days (on the basis of 365 days per year) is: > > > (1 + annual_rate) ** (n / 365.0) - 1.0 > > or > > math.pow(1 + annual_rate, n / 365.0) - 1.0 > > if you prefer. > > YPB? Anyone with half a brain knows, that you can either express rate > as 0.07 and do all those ridiculous conversions above, or express it > as 1.07 and apply it directly. > A conversion involving an exponentiation is necessary. "All those"?? I see only two. Please re-read your original post, and note that there are *TWO* plus- or-minus 1.0 differences between your formula and mine. For an annual rate of 10%, yours would calculate the rate for 6 months (expressed as 182.5 days) as: math.pow(0.10, 0.5) = 0.316... i.e. 31.6% My formula produces: math.pow(1.10, 0.5) - 1.0 = 0.0488... i.e. 4.88%. Which answer is ridiculous? From michele.simionato at gmail.com Thu Feb 8 10:38:10 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Feb 2007 07:38:10 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: References: <45C9A137.8090009@v.loewis.de> <52vtc4F1pngrdU1@mid.individual.net> <1170939556.975052.128930@a34g2000cwb.googlegroups.com> Message-ID: <1170949090.852352.237740@a34g2000cwb.googlegroups.com> On Feb 8, 4:05 pm, s... at pobox.com wrote:> > Composition is great when you know how largish classes are going to be > composed ahead of time and/or already have the pieces available in the form > of other classes you want to reuse. I use this fragment-by-multiple- > inheritance (I hesitate to call it a) pattern when I realize after a long > period of organic growth that a single-inheritance class has gotten too big. > It's often relatively easy to carve the class up into multiple related base > classes. The next step after that might be to morph those independent base > classes back into delegated attributes. > > Skip I know, I just try to avoid the multiple inheritance transitional state and switch directly to the last step ;) M. Simionato From rrr at ronadam.com Fri Feb 9 14:03:17 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 09 Feb 2007 13:03:17 -0600 Subject: from __future__ import absolute_import ? In-Reply-To: References: Message-ID: Peter Otten wrote: > Ron Adam wrote: > >> Peter Otten wrote: >>> Ron Adam wrote: >>> >>>> work >>>> | >>>> |- foo.py # print "foo not in bar" >>>> | >>>> `- bar >>>> | >>>> |- __init__.py >>>> | >>>> |- foo.py # print "foo in bar" >>>> | >>>> |- absolute.py # from __futer__ import absolute_import >>>> | # import foo >>>> | >>>> `- relative.py # import foo >>>> (4) >>>> C:\work\bar>python -c "import bar.absolute" >>>> foo in bar >>>> (5) >>>> >>> import bar.absolute >>>> foo in bar > (4) and (5) are misconfigurations, IMHO. But it's a very common configuration. So it will most likely cause problems for someone. From what I understand these will probably do what I want in python 2.6, which is either import the foo not in bar, or give an error if foo not in bar doesn't exist instead of importing foo in bar. >>> in an absolute-import-as-default environment; >>> >>> import foo >>> >>> would always be an absolute import. >> But what is the precise meaning of "absolute import" in this un-dotted >> case? >> >> Currently it is: >> >> "A module or package that is located in sys.path or the current >> directory". >> >> But maybe a narrower interpretation may be better?: >> >> "A module or package found in sys.path, or the current directory >> and is *not* in a package." > > You'd have to add a not-in-package test to every import - I don't think it's > worth the effort. No, you only need to test the (first) module you explicitly run is in a package. For any imports after that, the absolute import code can exclude any of the package directories for un-dotted top level absolute imports. It may be a performance net gain because there is less disk searching. >> All in all, what I'm suggesting is that the concept of a package (type) be >> much >> stronger than that of a search path or current directory. And that this >> would add a fair amount of reliability to the language. > > I think if you go that way, ultimately you will need some kind of package > registry. I expect that the new import behaviour will get you 99 percent > there with one percent of the hassle. But we will see... It won't need a registry. Check the python-ideas list for further discussion on this. Cheers, Ron From liuwensui at gmail.com Wed Feb 14 15:26:26 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Wed, 14 Feb 2007 15:26:26 -0500 Subject: reference data in a dictionary Message-ID: <1115a2b00702141226i4f23dc17x1360d87ed253dd3e@mail.gmail.com> dear all, i am new to python and have a question about referencing data in a dict. is there anyway that allows me to do something like: dict[['row1', 'row2', .....'row100']] thanks much. -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From wuwei23 at gmail.com Wed Feb 7 20:12:19 2007 From: wuwei23 at gmail.com (alex23) Date: 7 Feb 2007 17:12:19 -0800 Subject: Threading in Python In-Reply-To: <1170815802.600716.295960@l53g2000cwa.googlegroups.com> References: <1170815802.600716.295960@l53g2000cwa.googlegroups.com> Message-ID: <1170897139.167289.239010@v45g2000cwv.googlegroups.com> On Feb 7, 12:36 pm, "tleeuwenb... at gmail.com" wrote: > There are two ways. You can use processes, or you can use IronPython. Or you could try Parallel Python: http://www.parallelpython.com/ "a python module which provides mechanism for parallel execution of python code on SMP and clusters" - alex23 From gigs at hi.t-com.hr Wed Feb 28 07:58:32 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 28 Feb 2007 13:58:32 +0100 Subject: pyopengl vs directpython Message-ID: can someone tell me which is better for making 3d game in python. something like tennis simulation thx From ptmcg at austin.rr.com Sun Feb 4 21:55:22 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 4 Feb 2007 18:55:22 -0800 Subject: Missing member In-Reply-To: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> References: <1170629129.451171.148970@a75g2000cwd.googlegroups.com> Message-ID: <1170644122.385780.299920@v33g2000cwv.googlegroups.com> On Feb 4, 4:45 pm, "Mizipzor" wrote: > I have some troubles with a member variable that seems to be missing > in a class. In short, heres what I do; class A is the parent class, B > inherits from A and C inherits from B (hope I used the right words > there). Now, I create an instance of C, which calls A's __init__ which > in turn creates all the member variables. Then I call C.move() (a > function defined in A), but then, one of the variables seems to have > become 'NoneType'. > > The code can be found here (Ive taken away unnecessery stuff):http://pastebin.com/875394 > > The exact error is (which occur on line 15 in the pasted code): > TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' > > Any comments are welcome. :) Here's a suggestion: use new-style classes. Have _BaseEntity inherit from object, allows you to use super for invoking methods on super classes. Instead of: class Entity(_BaseEntity): def __init__(self, type, x = 0, y = 0): _BaseEntity.__init__(self, type, x, y) You enter: class Entity(_BaseEntity): def __init__(self, type, x = 0, y = 0): super(Entity,self).__init__(type, x, y) This makes it easier to update your inheritance hierarchy later. New- style classes have other benefits too. As for your NoneType problem, try adding "print self._direction" to the end of _BaseElement.__init__. -- Paul From gosinn at gmail.com Mon Feb 5 11:27:32 2007 From: gosinn at gmail.com (Gosi) Date: 5 Feb 2007 08:27:32 -0800 Subject: Calling J from Python In-Reply-To: <52ov20F1of7ecU1@mid.uni-berlin.de> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> Message-ID: <1170692852.549730.81030@v33g2000cwv.googlegroups.com> On Feb 5, 2:59 pm, "Diez B. Roggisch" wrote: > Gosi wrote: > > It is quite easy to call J from Python > > http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... > > What is J, and why should we care? > > Diez J is in many ways similar to Python. J has very many advanced operations. http://www.jsoftware.com/ From devicerandom at gmail.com Mon Feb 12 19:26:43 2007 From: devicerandom at gmail.com (devicerandom at gmail.com) Date: 12 Feb 2007 16:26:43 -0800 Subject: multiple inheritance of a dynamic list of classes? In-Reply-To: References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> Message-ID: <1171326403.786021.203490@k78g2000cwa.googlegroups.com> Thanks both for suggestions. I still think that using inheritance is somehow cleanest in this case (I always hear the mantra "avoid multiple inheritance!", but this is one of the cases it seems to make a lot of sense to me), but it's nice food for thought/code anyway. Other suggestions are always welcome, if there are! Massimo From __peter__ at web.de Tue Feb 27 03:31:41 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Feb 2007 09:31:41 +0100 Subject: Interactive os.environ vs. os.environ in script References: <1172502528.583879.138230@z35g2000cwz.googlegroups.com> <1172504983.452208.182490@p10g2000cwp.googlegroups.com> <1172562212.691747.150310@m58g2000cwm.googlegroups.com> Message-ID: boris.smirnov at gmail.com wrote: > Is there another possibility of how to solve it just by adding some > lines in script? I think you have to wrap your script in a shell script #!/bin/sh export LD_LIBRARY_PATH=/path/Linux/rh_linux python shrink_bs_070226.py To avoid that you can have the python script invoke itself, e. g.: #!/usr/bin/env python import os if os.environ.get("YADDA") != "whatever": print "fix environment" os.environ["YADDA"] = "whatever" os.system("yadda.py") raise SystemExit print "YADDA is now %r" % os.environ["YADDA"] print "do your real stuff" Peter From xbello at gmail.com Tue Feb 13 09:41:59 2007 From: xbello at gmail.com (XBello) Date: 13 Feb 2007 06:41:59 -0800 Subject: can't find a way to display and print pdf through python. In-Reply-To: References: Message-ID: <1171377719.777256.25610@l53g2000cwa.googlegroups.com> On Feb 12, 4:56 pm, Larry Bates wrote: > krishnakant Mane wrote: > > hello all, > > I am stuck with a strange requirement. > > I need a library that can help me display a pdf file as a report and > > also want a way to print the same pdf file in a platform independent > > way. > > if that's not possible then I at least need the code for useing some > > library for connecting to acrobat reader and giving the print command > > on windows and some thing similar on ubuntu linux. > > the problem is that I want to display reports in my application. the > > user should be able to view the formatted report on screen and at his > > choice click the print button on the screen to send it to the printer. > > I have reportlab installed and that is sufficient to generate pdf reports. > > but I still can't fine the way to display it directly and print it > > directly. > > Please help me. > > Krishnakant. > > Just let the registered .PDF viewer do it for you. > > os.start('myfile.pdf') > > Launches whatever is registered as .PDF viewer and user > can then print, save, zoom, etc. on their own. > > -Larry os.startfile('pathToTheFile') should work. Under Library Reference- > os -> Process Management From mbm at mediamonger.ch Thu Feb 8 08:27:49 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Thu, 08 Feb 2007 14:27:49 +0100 Subject: postgres backup script and popen2 In-Reply-To: References: Message-ID: <45CB2555.70006@mediamonger.ch> Use pexpect: http://pexpect.sourceforge.net/ flupke schrieb: > Hi, > > i made a backup script to backup my postgres database. > Problem is that it prompts for a password. It thought i > could solve this by using popen2. > I tested popen2 with dir (i'm on windows 2000, python 2.4.3) > and it works. > However when i try popen2 and my pg_dump command, it prompts > for a password and I was under the impression that i was > going to be able to dynamically communicate with the process. > > sin, sout = popen2(backup_command) > sin.readline() # the password prompt > sout.write("password") > sin.readlines() > > How can i catch the password prompt and feed the password > from my code? > > Thanks, > Benedict From garrickp at gmail.com Tue Feb 6 19:05:24 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 6 Feb 2007 16:05:24 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170806044.201254.289080@l53g2000cwa.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> <1170775779.707583.131420@k78g2000cwa.googlegroups.com> <1170806044.201254.289080@l53g2000cwa.googlegroups.com> Message-ID: <1170806724.447542.206120@m58g2000cwm.googlegroups.com> On Feb 6, 4:54 pm, "John Machin" wrote: > Recursive? Bzzzt! I woudl be happy to hear your alternative, which doesn't depend on language specific tricks. Thus far, all you have suggested is using an alternative form of the division function, which I would consider to be outside the spirit of the question (though I have been wrong many times before). > Might it not be better to halve the interval at each iteration instead > of calling a random number function? mid = (lo + hi) >> 1 looks > permitted and cheap to me. Also you don't run the risk of it taking a > very high number of iterations to get a result. I had considered this, but to halve, you need to divide by 2. Using random, while potentially increasing the number of iterations, removes the dependency of language tricks and division. > Did you notice the important word *efficiently* in line 1 of the spec? > Even after ripping out recursion and random numbers, your proposed > solution is still way off the pace. Again, I look forward to reading your solution. Respectfully, G. From bearophileHUGS at lycos.com Thu Feb 1 08:26:52 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Feb 2007 05:26:52 -0800 Subject: Inconsistent list/pointer problem In-Reply-To: References: Message-ID: <1170336412.696129.286590@m58g2000cwm.googlegroups.com> Doug Stell: The standard module copy has deepcopy, it's slow but it may be a simple solution to your problem. A better solution is to look where data is changed and fix that. Bye, bearophile From sickcodemonkey at gmail.com Thu Feb 22 21:58:46 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 22 Feb 2007 21:58:46 -0500 Subject: Python Threads In-Reply-To: References: <2adc542f0702181516g7bbfb08ga721b568cb528404@mail.gmail.com> <2adc542f0702181837g3c433742ha0fedd775d8cc0fa@mail.gmail.com> Message-ID: <2adc542f0702221858j1db9a325q5dff9828783f5230@mail.gmail.com> I think that I found a solution to my thread issues, however I know it is not the most efficient method possible. Just to give you a little information on what this project is all about.... I have 3 lists of email addresses. (1) "host email address" = contains a list of all of my emails address (around 150,000 users) (2) "email addresses" = contains a list of email addresses that I have to match with the file "host email address". If there are any matches, then I have to print them out to a file. (this could be up to 8 million users) (3) "domain addresses" = contains a list of email domains that I have to match with the "host email address" file. If there are any matched, then I have to print them out to a file. (could be 2000 or more domains) When running the application, you will have the "host email address" and can have either one or both of the other files running at the same time. My problem was that when the application ran, it appeared to stall. I decided to use threads for (1) the processing of data and (2) the progress bar. The solution I found that enabled the two threads to communicate was the use of global variables. I know this is this is not the most efficient method but, using this solution, I do not see the stalling issue that I found before (which is a good thing). I am still not happy with it, because I know it is not efficient, but I found this to be the best solution for my needs. Thoughts? The code is below. Before you see the code, I must thank everyone who helped me with this project (including the open source coders). =================== #! /usr/bin/env python import difflib, sys, thread, re, os, time import Tkinter from Tkinter import * from sets import Set import tkFileDialog, tkMessageBox from tkFileDialog import * listName = ['','',''] threadStat = 0 mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') domsrch = re.compile(r"@(\S+)") statusVar = 0.0 # for the progress bar startProgress = 0 ################################################################ class Meter(Tkinter.Frame): def __init__(self, master, width=300, height=20, bg='black', fillcolor='cyan',\ value=0.0, text=None, font=None, textcolor='white', *args, **kw): Tkinter.Frame.__init__(self, master, bg=bg, width=width, height=height, *args, **kw) self._value = value self._canv = Tkinter.Canvas(self, bg=self['bg'], width=self['width'], height=self['height'],\ highlightthickness=0, relief='flat', bd=0) self._canv.pack(fill='both', expand=1) self._rect = self._canv.create_rectangle(0, 0, 0, self._canv.winfo_reqheight(), fill=fillcolor,\ width=0) self._text = self._canv.create_text(self._canv.winfo_reqwidth()/2, self._canv.winfo_reqheight()/2,\ text='', fill=textcolor) if font: self._canv.itemconfigure(self._text, font=font) self.set(value, text) self.bind('', self._update_coords) def _update_coords(self, event): '''Updates the position of the text and rectangle inside the canvas when the size of the widget gets changed.''' self._canv.update_idletasks() self._canv.coords(self._text, self._canv.winfo_width()/2, self._canv.winfo_height()/2) self._canv.coords(self._rect, 0, 0, self._canv.winfo_width()*self._value, self._canv.winfo_height()) self._canv.update_idletasks() def get(self): return self._value, self._canv.itemcget(self._text, 'text') def set(self, value=0.0, text=None): #make the value failsafe: if value < 0.0: value = 0.0 elif value > 1.0: value = 1.0 self._value = value if text == None: #if no text is specified use the default percentage string: text = str(int(round(100 * value))) + ' %' self._canv.coords(self._rect, 0, 0, self._canv.winfo_width()*value, self._canv.winfo_height()) self._canv.itemconfigure(self._text, text=text) self._canv.update_idletasks() ########################################################## def fail(msg): out = sys.stderr.write out(msg + "\n\n") out(__doc__) return 0 ################################################################ def fopen(fname): try: return open(fname, 'U') except IOError, detail: return fail("couldn't open " + fname + ": " + str(detail)) ################################################################ def fetchFiles(file1,file2,file3): #file1: host list file2 = email list; file3=domain; method= method = '' print file1 print file2 print file3 f1 = fopen(file1) a = f1.readlines(); f1.close() d1 = {} for c in a: for m in mailsrch.findall(c): d1[m.lower()] = None print "starting list 2" thread.start_new_thread(showProcessing, ()) #DOMAIN COMPARISON if file2 == '': domain(d1,file3) #EMAIL COMPARISON elif file3 == '': email(d1,file2) #BOTH else: both(d1,file2,file3) ############################################################### def domain (d1,file3): f3 = fopen(file3) domains = f3.readlines(); f3.close() print len(domains) totalLen = len(domains) print totalLen try: progressInc = abs(1.0/totalLen) except: tkMessageBox.showerror ( "What are you doing?", "One of your files had no information. I cannot process this, I QUIT." ) global threadStat threadStat = 1 progressInc = 1 print progressInc global statusVar utp = open("data/emailMatch.txt","w") domainList = [] for domain in domains: domainList.extend(domsrch.findall(domain.lower())) domainsSet = set(domainList) for key in d1: name, domain = key.split("@",1) if domain.lower() in domainsSet: utp.write(key + '\n') statusVar += progressInc utp.close() endProc() ############################################################### def email (d1, file2): f2 = fopen(file2) method = 'email' emails = f2.readlines(); f2.close() totalLen = len(emails) print totalLen try: progressInc = abs(1.0/totalLen) except: tkMessageBox.showerror ( "What are you doing?", "One of your files had no information. I cannot process this, I QUIT." ) global threadStat threadStat = 1 progressInc = 1 print progressInc global statusVar utp = open("data/emailMatch.txt","w") for email in emails: for n in mailsrch.findall(email.lower()): if d1.has_key( n ): utp.write(n + '\n') statusVar += progressInc utp.close() print "I am done with email comparison" endProc() ############################################################### def both (d1, file2, file3): #doing the Domains first f3 = fopen(file3) domains = f3.readlines(); f3.close() f2 = fopen(file2) method = 'email' emails = f2.readlines(); f2.close() totalLen = len(domains) + len(emails) print totalLen try: progressInc = abs(1.0/totalLen) except: tkMessageBox.showerror ( "What are you doing?", "One of your files had no information. I cannot process this, I QUIT." ) global threadStat threadStat = 1 progressInc = 1 print progressInc global statusVar finList = [] domainList = [] for domain in domains: domainList.extend(domsrch.findall(domain.lower())) domainsSet = set(domainList) for key in d1: name, domain = key.split("@",1) if domain.lower() in domainsSet: finList.append(key) statusVar += progressInc print "I am done with domain comparison" #Next do email addresses for email in emails: for n in mailsrch.findall(email.lower()): if d1.has_key( n ): finList.append(n) statusVar += progressInc print "I am done with email comparison" print "removing duplication" #removeDups(finList) dupFreeList = removeDups(finList) dupFreeList.sort() utp = open("data/emailMatch.txt","w") for emails in dupFreeList: utp.write(emails + '\n') utp.close() print "i am done doing both" endProc() ############################################################### def removeDups(s): n = len(s) if n == 0: return [] u = {} try: for x in s: u[x] = 1 except TypeError: del u # move on to the next method else: return u.keys() try: t = list(s) t.sort() except TypeError: del t # move on to the next method else: assert n > 0 last = t[0] lasti = i = 1 while i < n: if t[i] != last: t[lasti] = last = t[i] lasti += 1 i += 1 return t[:lasti] # Brute force is all that's left. u = [] for x in s: if x not in u: u.append(x) return u ############################################################### def endProc(): global threadStat threadStat = 1 thread.exit() ############################################################### def showProcessing(): mroot = Tkinter.Tk(className='Worker Bee') metric = Meter(mroot, relief='ridge', bd=3) metric.pack(fill='x') setInc = 0.1 global statusVar global threadStat while threadStat == 0: if statusVar < 0.3: message = "YAWN. Have any coffee" elif statusVar < 0.5 and statusVar > 0.3: message = "Im working, so you dont have to." elif statusVar < 0.7 and statusVar > 0.5: message = "I hope you sold something, to pay me off" else: message = "Almost there chief." metric.set(statusVar, message) time.sleep(10) metric.set(1.0, 'WOOT WOOT WOOT. DONE') print threadStat ############################################################### def startProc(): noisy = 1 qseen = rseen = 0 #print listName f1name = listName[0] f2name = listName[1] f3name = listName[2] if f1name == '': tkMessageBox.showerror ( "Open file", "You must upload host email list." ) method = 'failed' print "ERROR! You need to upload host email address" elif f2name =='' and f3name == '': tkMessageBox.showerror ( "Open file", "You must upload another document to compare host list." ) method = 'failed' print "ERROR! You need to upload another file" else: thread.start_new_thread(fetchFiles, (f1name,f2name,f3name,)) global threadStat while threadStat == 0: pass ############################################################### def openMax(): a = tkFileDialog.askopenfilename() listName[0] = a def openEmail(): b = tkFileDialog.askopenfilename() listName[1] = b def openDomain(): c = tkFileDialog.askopenfilename() listName[2] = c ############################################################### main = Tk() bframe = Frame(main) main.title("Suppression Utility") b1 = Button(bframe,text='Host Email List',command=openMax) b2 = Button(bframe,text='Email List',command=openEmail) b3 = Button(bframe,text='Domain List',command=openDomain) b4 = Button(text='Start Processing',command=startProc) bframe.pack(side=TOP) b1.pack(side=LEFT) b3.pack(side=RIGHT) b2.pack(side=RIGHT) b4.pack(side=BOTTOM) main.mainloop() ####################################### ======================== Dave Huggins On 2/18/07, Gabriel Genellina wrote: > > En Sun, 18 Feb 2007 23:37:02 -0300, Sick Monkey > escribi?: > > > Well if this cannot be done, can a thread call a function in the main > > method? > > I have been trying and have not been successive. Perhaps I am using > > thread > > incorrectly. > > The safe way to pass information between threads is to use Queue. From > inside the working thread, you put() an item with enough state > information. On the main (GUI) thread, you use after() to check for any > data in the queue, and then update the interfase accordingly. > I think there is a recipe in the Python Cookbook > http://aspn.activestate.com/ASPN/Cookbook/Python > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nszabolcs at gmail.com Fri Feb 23 09:55:28 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 23 Feb 2007 06:55:28 -0800 Subject: What is the best queue implemetation in Python? In-Reply-To: <1172212499.165842.249360@t69g2000cwt.googlegroups.com> References: <1172212499.165842.249360@t69g2000cwt.googlegroups.com> Message-ID: <1172242528.434154.226680@j27g2000cwj.googlegroups.com> > For that purpose I have used the good deque that you can find in > collections in the standard library. It's very good for queues, and > it's a bit faster than regular lists for stacks too. you mean *much* faster (since a list is a reference array so pop(0) is O(n) operation) never use a list as queue if len(queue) > 10000 === benchmark $ time ./deque_queue.py 34359607296 real 0m0.286s user 0m0.264s sys 0m0.016s $ time ./list_queue.py 34359607296 real 1m20.915s user 1m18.649s sys 0m0.396s === the sources --- deque_queue.py: #!/usr/bin/python2.5 from collections import deque def f(n): sum = 0 queue = deque() for i in range(n): queue.append(i) while queue: sum += queue.popleft() print sum if __name__=='__main__': f(1<<18) --- list_queue.py: #!/usr/bin/python2.5 def f(n): sum = 0 queue = list() for i in range(n): queue.append(i) while queue: sum += queue.pop(0) print sum if __name__=='__main__': f(1<<18) From rkmr.em at gmail.com Tue Feb 13 21:52:37 2007 From: rkmr.em at gmail.com (mark) Date: Tue, 13 Feb 2007 18:52:37 -0800 Subject: calling php function from python Message-ID: is it possible to call a php function from python and use a class from php in python? i want to use mmslib which creates mms messages and the only implementation is a php mmslib implementation. thanks a lot! mark From jan.m.danielsson at gmail.com Thu Feb 1 03:33:36 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Thu, 01 Feb 2007 09:33:36 +0100 Subject: Any python scripts to do parallel downloading? In-Reply-To: References: Message-ID: <45c1a4c5$1@griseus.its.uu.se> Jean-Paul Calderone wrote: [---] >> Software is hard. > > But I absolutely agree with this point, anyway :) Software is _crazy_ > hard. I merely dispute the claim that threads are somehow _easier_. :) Threads aren't easier. Nor are they harder. They are just different. I used to be heavily into OS/2 programming. In OS/2, you use threads heavily - almost by tradition. Its relatively low context switch latency and its nice set of IPC routines (almost all API's are thread safe and reentrant), make developing multithreaded applications quite natural. Guess what happened when I started programming on NetBSD and Windows. I struggled to write singlethreaded applications(!). I was so used to kicking off a worker thread as soon as I needed to do something that I knew could just as well be done in the background. An I *constantly* thought in terms of "How could I make full use of an SMP system?". I would never claim that multithreading is *easier* than singlethreaded. It's mererly a different way of thinking. OTOH, multithreaded does have a steeper learning curve. But once you get past that, there's really not a lot of difference, IMHO. YMMV. -- Kind regards, Jan Danielsson From exarkun at divmod.com Tue Feb 6 14:07:55 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 6 Feb 2007 14:07:55 -0500 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: Message-ID: <20070206190755.25807.613588197.divmod.quotient.12069@ohm> On Tue, 06 Feb 2007 08:40:40 -0700, Steven Bethard wrote: >Jean-Paul Calderone wrote: > > Huge amounts of my pure Python code was broken by Python 2.5. > >Interesting. Could you give a few illustrations of this? (I didn't run >into the same problem at all, so I'm curious.) > There are about half a dozen examples linked from here: http://twistedmatrix.com/trac/ticket/1867 Check out the closed ticket linked from there or the changesets for more detail. Jean-Paul From vithi99 at hotmail.com Fri Feb 16 21:35:47 2007 From: vithi99 at hotmail.com (vithi) Date: 16 Feb 2007 18:35:47 -0800 Subject: how to use Dispatch to open an application in win32com.client Message-ID: <1171679747.670443.306610@t69g2000cwt.googlegroups.com> Hi' I am trying to launch an application. When I try like that When I try like that Excel is opening import win32com.client object = win32com.client.Dispatch("Excel.Application") object.Visible = 1 But when I try my application which is QeepIt.exe which is in the c:\ drive it is not running Any body tell me how to give path to open an exectable application in Dispatch modules I try like that object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") It give an error. From larry.bates at websafe.com Mon Feb 12 13:04:57 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Feb 2007 12:04:57 -0600 Subject: can't find a way to display and print pdf through python. In-Reply-To: <12t17gsjh6vgh94@corp.supernews.com> References: <12t17gsjh6vgh94@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-02-12, Larry Bates wrote: > >>> I at least need the code for useing some library for >>> connecting to acrobat reader and giving the print command on >>> windows and some thing similar on ubuntu linux. > >> Just let the registered .PDF viewer do it for you. >> >> os.start('myfile.pdf') > > Eh? I don't see os.start() it either 2.5 or 2.44 > documentation, and it's sure not there in 2.4.3: > > $ python > Python 2.4.3 (#1, Dec 10 2006, 22:09:09) > [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import os > >>> print os.start > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'start' > > I did find os.startfile() in the docs, but it's shown as > windows-only (it's not present under Linux). > >> Launches whatever is registered as .PDF viewer and user >> can then print, save, zoom, etc. on their own. > > Really? > My bad. os.system() -Larry From gagsl-py at yahoo.com.ar Thu Feb 8 21:12:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Feb 2007 23:12:55 -0300 Subject: [Windows] Sending CTRL-C event to console application References: <1170960845.457806.27260@p10g2000cwp.googlegroups.com> Message-ID: En Thu, 08 Feb 2007 15:54:05 -0300, Daniel Clark escribi?: > I have a Windows command line based application that only shuts down > cleanly if it sees "CTRL-C" on the console. I need to automate the > running of this application, but still allow the user sitting at the > machine to cancel the process cleanly if he/she needs to. In Unix this > would be a tiny shell script that used "kill -15", but under Windows > there does not seem to be an easy way to do this, at least that I can > find. > > Below is a test program, based on CreateProcess.py from "Python > Programming on Win32". The > win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid) lines > don't seem to do anything. What they should do is nothing in the case > of notepad, and exit out of the dir builtin process in the case of the > cmd.exe process. > > Any ideas on how to make this work? From your process creation code: > CreationFlags = win32process.CREATE_NEW_CONSOLE | \ > win32process.CREATE_NEW_PROCESS_GROUP | \ > win32process.NORMAL_PRIORITY_CLASS From http://msdn2.microsoft.com/en-us/library/ms683155.aspx "Only those processes in the group that share the same console as the calling process receive the signal. In other words, if a process in the group creates a new console, that process does not receive the signal, nor do its descendants." Maybe you have better luck on a Windows programming group, asking how to send a Ctrl-C event (or a SIGINT signal) to another process attached to a different console. -- Gabriel Genellina From tech-hr at smartcharter.com Mon Feb 26 10:23:29 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Mon, 26 Feb 2007 07:23:29 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: In article <1172482314.598240.3440 at j27g2000cwj.googlegroups.com>, dixkey at gmail.com wrote: > On Feb 26, 6:32 am, Tech HR wrote: > > Our > > website is currently a LAMP appication with P=Python. We are looking for > > bright motivated people who know or are willing to learn Python and/or > > Linux, Apache and MySQL system administration skills. (And if you want > > to convince us that we should switch over to Postgres, we're willing to > > listen.) > This is more out of curiosity, but does it mean that you wouldn't be > willing to listen about a switch from Python to Lisp? No, it doesn't mean that. In fact, there is a significant faction in the technical staff (including the CTO) who would like nothing better than to be able to use Lisp instead of Python. But we have some pretty compelling reasons to stick with Python, not least of which is that it is turning out to be very hard to find Lisp programmers. (Actually, it's turning out to be hard to find Python programmers too, but it's easier to train a Java programmer or a Perler on Python than Lisp. We also have fair bit of infrastructure built up in Python at this point.) But we're a very young company (barely six months old at this point) so we're willing to listen to most anything at this point. (We're using Darcs for revision control. Haskell, anyone?) From sable at users.sourceforge.net Fri Feb 2 11:47:36 2007 From: sable at users.sourceforge.net (=?ISO-8859-1?Q?S=E9bastien_Sabl=E9?=) Date: Fri, 02 Feb 2007 17:47:36 +0100 Subject: Sybase module 0.38pre2 released Message-ID: <45C36B28.1020608@users.sourceforge.net> 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. The module is available here: http://downloads.sourceforge.net/python-sybase/python-sybase-0.38pre2.tar.gz The module home page is here: http://python-sybase.sourceforge.net/ CHANGES SINCE 0.38pre1: * Add structured error information to Sybase.DatabaseError thanks to patch provided by Gregory Bond (close tracker 1631902) * Resurrected Sybase.Bulkcopy functionality thanks to patch provided by Gregory Bond (close tracker 1632916) * Corrected AttributeError when locking is off (close tracker 1637942 reported by Jim Nusbaum) * Corrected incorrect type mx.DateTime.DateTime returned by Sybase.Date() in "mx" datetime mode. This type is not supported by DataBuf. * Corrected crash on a BLK object when debug is enabled (close tracker 1630941 reported by Gregory Bond) * rowcount is now propagated to Cursor (corrects tracker 1621003) * Added support for python datetime type in DataBuf and as parameter of Cursor.execute() * Corrected Date, Time and Timestamp functions when using mx.DateTime or native python datetime types * Corrected DATETIME as cursor.description still returns native Sybase datetime types * Corrected blk_describe always returns (status, None) thanks to patch by Phil Porter * Patch to handle CS_LONG type based on patch by Paul Rensing MAJOR CHANGES SINCE 0.37: * This release works with python 2.5 * It also works with sybase 15 * It works with 64bits clients * It can be configured to return native python datetime objects * The bug "This routine cannot be called because another command structure has results pending." which appears in various cases has been corrected * It includes a unitary test suite based on the dbapi2.0 compliance test suite From miki.tebeka at gmail.com Fri Feb 2 09:10:25 2007 From: miki.tebeka at gmail.com (Miki) Date: 2 Feb 2007 06:10:25 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: <1170425425.799883.167170@k78g2000cwa.googlegroups.com> Hello, > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] I'd use a dictionary to store value for a given key: >>> def aggregate(lst): items = {} # key -> values for key, value in lst: values = items.get(key) if values: if type(values) == list: values.append(value) else: items[key] = [values, value] else: items[key] = value return [list(pair) for pair in items.items()] >>> aggregate(lst) [['a', ['13', '3']], ['c', ['12', '15', '4']], ['b', '6'], ['e', ['11', '5', '16', '7']], ['d', '2']] >>> HTH, -- Miki http://pythonwise.blogspot.com From sjmachin at lexicon.net Tue Feb 20 16:13:55 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 13:13:55 -0800 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: <12tm9c78p2mea0f@corp.supernews.com> References: <12tm3hpom0tkqc7@corp.supernews.com> <1171984944.698061.248220@j27g2000cwj.googlegroups.com> <12tm9c78p2mea0f@corp.supernews.com> Message-ID: <1172006035.896448.72780@l53g2000cwa.googlegroups.com> On Feb 21, 3:44 am, Grant Edwards wrote: > On 2007-02-20, John Machin wrote: > > > On Feb 21, 2:05 am, Grant Edwards wrote: > >> On 2007-02-20, joanne matthews (RRes-Roth) wrote: > > >> Don't use floating point if you expect exact results. > > > > Another take: Don't expect exact results. > > Which is what I said. :) It may well be what you said. I didn't hear that. What you wrote was "Don't use floating point if you expect exact results." That is *not* the same as "Don't expect exact results". From exarkun at divmod.com Mon Feb 5 09:23:16 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 Feb 2007 09:23:16 -0500 Subject: Python 3.0 (Was: when will python 2.5 take in mainstream?) In-Reply-To: Message-ID: <20070205142316.25807.552685546.divmod.quotient.10793@ohm> On Mon, 05 Feb 2007 07:01:26 -0700, Steven Bethard wrote: >Laurent Pointal wrote: >> For Python 3.0, AFAIK its a big rewrite and developers know that it will >> be uncompatible in large parts with existing code. > >Wrong on both counts. ;-) Python 3.0 is not a rewrite. It's based on the >same code base as the 2.X line, but with a lot of the old deprecated >things removed. And, while Python 3.0 is allowing itself to break >backwards compatibility, at least that the Python level, it should be >largely compatible with the 2.X line. There will be some breakages, but >(1) they shouldn't be too extensive and (2) there will be utilities to >help you update your code. In many cases, it will be possible to write >code that works in both Python 2.X and 3.0. Hopefully that will be the case. Misunderstandings aren't too surprising though. Until recently, it didn't appear that this would be the case at all. Of course, your statement isn't entirely accurate either. For example, many things which _aren't_ deprecated are being removed as well. Some of them may be deprecated in 2.x releases which haven't happened yet, but that remains to be seen. And 3.0 won't be "largely compatible" with any _existing_ 2.x release, but hopefully a future 2.x release will add a usable transition path. Jean-Paul From nilsoveras at yahoo.no Fri Feb 2 07:19:57 2007 From: nilsoveras at yahoo.no (Nils Overas Bergen) Date: 2 Feb 2007 04:19:57 -0800 Subject: Interpreter window In-Reply-To: References: <1170417263.849798.151010@k78g2000cwa.googlegroups.com> Message-ID: <1170418796.996964.27350@q2g2000cwa.googlegroups.com> On 2 Feb, 13:07, "skyofdreams" wrote: > "Nils Overas Bergen" > 1170417263.849798.151... at k78g2000cwa.googlegroups.com... > > >I have created a Python application in Windows XP which uses > > WxWidgets. When I start the application from the Python interpreter I > > get one empty interpreter window in addition to the application > > window. Is there a way to close the interpreter window without closing > > the application? Or, can I start the interpreter and the application > > script without starting the interpreter window? > > do you mean console window? > you can try pythonw.exe instead of python.exe > > -sods Thanks! Now my application starts without the console window. Nils From artie at cdres.com Mon Feb 5 17:33:40 2007 From: artie at cdres.com (Artie) Date: 5 Feb 2007 14:33:40 -0800 Subject: glutInit and wxPython on Mac OSX Message-ID: <1170714820.700451.33090@v45g2000cwv.googlegroups.com> I seem to have uncovered a problem when using glutInit alongside wxPython on Mac OSX. If glutInit is called prior to creating a wx.App, many window and mouse events are either lost, not generated, or misgenerated for the glcanvas. However, if glutInit is called after the wx.App has been created then all is well. Has anyone ran across this issue before? If so, why does this order matter or affect the wx Event system? --artie From jura.grozni at gmail.com Tue Feb 13 12:38:35 2007 From: jura.grozni at gmail.com (azrael) Date: 13 Feb 2007 09:38:35 -0800 Subject: Testers please In-Reply-To: <1171362346.133027.42210@l53g2000cwa.googlegroups.com> References: <1171362346.133027.42210@l53g2000cwa.googlegroups.com> Message-ID: <1171388315.260790.207310@m58g2000cwm.googlegroups.com> it would be nice when someone would paste some instructions or tutorial how to bound it all together. where to paste the file. a dummy tutorial if possible. From ironfroggy at gmail.com Wed Feb 7 12:07:54 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 7 Feb 2007 12:07:54 -0500 Subject: Object type check In-Reply-To: <1170867552.247093.198800@j27g2000cwj.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> <1170867552.247093.198800@j27g2000cwj.googlegroups.com> Message-ID: <76fd5acf0702070907y70573e4bx685d627d66965f97@mail.gmail.com> On 7 Feb 2007 08:59:12 -0800, king kikapu wrote: > > Dont restrict them to particular types. You would > > not restrict them to a particular class in C#. Instead, you define the > > interfaces simply by how you use the objects. > > Of cource i restrict them to particular types! In C# you cannot pass > something bad > this way because the compiler will just catch it! No, you restrict the interfaces, in your example, not the classes. It is the same in python, but the interfaces are implicitly defined by how you use the objects. > I see what you mean by "duck typing". So you suggest the "do nothing > at all" direction, > better document my code so other can see what is expected, right ? Yes. Also, remember that this means if you write code to expect a dictionary, any mapping type that supports the operations and methods you use will work transparently, allowing your code to be much more flexible. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From michele.simionato at gmail.com Thu Feb 8 15:12:07 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Feb 2007 12:12:07 -0800 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <531b72F1pio0oU1@mid.individual.net> References: <45C9A137.8090009@v.loewis.de> <1170861460.614883.108310@k78g2000cwa.googlegroups.com> <1170862664.972024.322260@a75g2000cwd.googlegroups.com> <1170868322.560426.149920@p10g2000cwp.googlegroups.com> <531b72F1pio0oU1@mid.individual.net> Message-ID: <1170965527.703877.294160@a75g2000cwd.googlegroups.com> On Feb 8, 8:15 pm, Thomas Heller wrote: > I agree with most of the posters is this thread that it is confusing to spread > the definition of a class over several places or files. > > But, there are cases where the trick come in handy - when classes are created > not by class statements. > > In ctypes, for example, a pointer type to a ctypes type is created by calling > the POINTER function which creates a new class. When you have done this, the > usual way to add additional methods to the new class is by assigning them like this: > > from ctypes import * > > pointer_to_c_int = POINTER(c_int) > > @classmethod > def from_param(cls, value): > ... do something ... > > pointer_to_c_int.from_param = from_param > > IMO, using the tricky class in the recipes mentioned above, you can write instead: > > class pointer_to_c_int(partial, POINTER(c_int)): > @classmethod > def from_param(cls, value): > ... do something ... > > Thomas Using a simple decorator like this seeems a better option to me: def attach_to(cls): def attach_method(meth): setattr(cls, meth.__name__, meth) return meth return attach_meth @attach_to(pointer_to_c) @classmethod def from_param(cls, value): ... do something ... Michele Simionato From Bulkan at gmail.com Wed Feb 21 17:47:50 2007 From: Bulkan at gmail.com (placid) Date: 21 Feb 2007 14:47:50 -0800 Subject: getting a thread out of sleep In-Reply-To: References: <1172033277.571978.251170@j27g2000cwj.googlegroups.com> <1172035303.424370.20140@t69g2000cwt.googlegroups.com> <1172035578.410747.319890@j27g2000cwj.googlegroups.com> Message-ID: <1172098070.913952.20730@h3g2000cwc.googlegroups.com> On Feb 22, 3:23 am, mark wrote: > On 20 Feb 2007 21:26:18 -0800, placid wrote: > > > > > On Feb 21, 4:21 pm, "placid" wrote: > > > On Feb 21, 4:12 pm, mark wrote: > > > > On 20 Feb 2007 20:47:57 -0800, placid wrote: > > > > > On Feb 21, 3:08 pm, mark wrote: > > > > > > Right now I have a thread that sleeps for sometime and check if an > > > > > > event has happened and go back to sleep. Now instead I want the thread > > > > > > to sleep until the event has occured process the event and go back to sleep > > > > > > > class eventhndler(threading.Thread): > > > > > > def __init__(self): > > > > > > threading.Thread.__init__(self) > > > > > > def run(self): > > > > > > while True: > > > > > > time.sleep(SLEEPTIME) > > > > > > ''''do event stuff''' > > > > > > The way i would do this is by using an threading.Event ( > > > > >http://docs.python.org/lib/event-objects.html) > > > > > > > > > > > > class eventhandler(threading.Thread): > > > > > def __init__(self): > > > > > threading.Thread.__init__(self) > > > > > self.event = threading.Event() > > > > > def run: > > > > > while True: > > > > > # block until some event happens > > > > > self.event.wait() > > > > > """ do stuff here """ > > > > > self.event.clear() > > > > > > > > > > > the way to use this is to get the main/separate thread to set() the > > > > > event object. > > > > > Can you give an example of how to get the main threead to set teh event object? > > > > this is exactly what i wanted to do! > > > > thanks a lot! > > > > mark> > > oops I've miss-typed the thread variable name the following should > > work > > > > > if __name__ == "__main__": > > evtHandlerThread = eventhandler() > > evtHandlerThread.start() > > > # do something here # > > evtHandlerThread.event.set() > > > # do more stuff here # > > evtHandlerThread.event.set() > > > > > Can I have the same thread process two or more events? Can you tell > how to do this? The code you gave is waiting on one event right. How > can I do it for more events? > thanks a lot! > mark I don't think a thread can block on more than one event at a time. But you can make it block on more then one event one at a time. class eventhandler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.events = [threading.Event(), threading.Event()] self.currentEvent = None def run: while True: for event in self.events: self.currentEvent = event # block until some event happens self.currentEvent.wait() """ do stuff here """ self.currentEvent.clear() if __name__ == "__main__": evtHandlerThread = eventhandler() evtHandlerThread.start() # do something here # evtHandlerThread.currentEvent.set() # do more stuff here # evtHandlerThread.currentEvent.set() what the thread does is sequentially waits for two events to happen and then execute the same code. You could change this code to perform different functions for different event objects. Cheers From bdesth.quelquechose at free.quelquepart.fr Thu Feb 8 15:26:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Feb 2007 21:26:26 +0100 Subject: Fwd: Python new user question - file writeline error In-Reply-To: References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <1170887579.160693.78160@a34g2000cwb.googlegroups.com> <813A863A-3D95-47B5-8E54-B6DDF5A57DF5@Milochik.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> Message-ID: <45cb8045$0$449$426a74cc@news.free.fr> Shawn Milo a ?crit : > To the list: > > I have come up with something that's working fine. However, I'm fairly > new to Python, so I'd really appreciate any suggestions on how this > can be made more Pythonic. > > Thanks, > Shawn > > > > > > > Okay, here's what I have come up with: > > > #! /usr/bin/python > > import sys > import re > > month > ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > > infile=file('TVA-0316','r') > outfile=file('tmp.out','w') > > def formatDatePart(x): > "take a number and transform it into a two-character string, > zero padded" > x = str(x) > while len(x) < 2: > x = "0" + x > return x x = "%02d" % x > regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") regexps are not really pythonic - we tend to use them only when we have no better option. When it comes to parsing CSV files and/or dates, we do have better solution : the csv module and the datetime module.... > for line in infile: > matches = regex.findall(line) > for someDate in matches: > > dayNum = formatDatePart(someDate[1:3]) > monthNum = formatDatePart(month[someDate[4:7]]) > yearNum = formatDatePart(someDate[8:12]) > > newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) > line = line.replace(someDate, newDate) > outfile.writelines(line) > > infile.close > outfile.close I wonder why some of us took time to answer your first question. You obviously forgot to read these answers. From steven.bethard at gmail.com Wed Feb 28 16:21:05 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 28 Feb 2007 14:21:05 -0700 Subject: class declaration shortcut In-Reply-To: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> Message-ID: <7o-dndyPgY_db3jYnZ2dnUVZ_t2tnZ2d@comcast.com> Luis M. Gonz?lez wrote: > I've come across a code snippet in www.rubyclr.com where they show how > easy it is to declare a class compared to equivalent code in c#. > I wonder if there is any way to emulate this in Python. > > The code is as follows: > > Person = struct.new( :name, :birthday, :children) How about something like:: class Person(Record): __slots__ = 'name', 'birthday', 'children' You can then use the class like:: person = Person('Steve', 'April 25', []) assert person.name == 'Steve' assert person.birthday == 'April 25' assert not person.children Is that what you were looking for? If so, the recipe for the Record class is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 STeVe From lorenzo.viscanti at gmail.com Tue Feb 6 06:30:22 2007 From: lorenzo.viscanti at gmail.com (Lorenzo) Date: 6 Feb 2007 03:30:22 -0800 Subject: XMLRPC Server In-Reply-To: <52r41eF1p17pqU1@mid.uni-berlin.de> References: <1170757001.955620.10350@h3g2000cwc.googlegroups.com> <52r41eF1p17pqU1@mid.uni-berlin.de> Message-ID: <1170761422.916375.6490@v33g2000cwv.googlegroups.com> Unfortunately I have to use Apache. The server implementation will we very easy, so I'm also considering more efficient solutions than python lv On Feb 6, 11:36 am, "Diez B. Roggisch" wrote: > visca... at gmail.com wrote: > > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > > It's not too difficult to configure everything, but I would like to > > tune it in order to receive up to 2000 calls per minute without any > > problems. Do Pthon CGIs use threading? > > I need to make it very efficient, but I haven't found much information > > about Python CGI optimization. > > The called function will update a table in a mysql db. I will use > > triggers to export data from the table updated by the xmlrpc server to > > other tables used by the backend application. > > You might consider using the twisted application server framework instead, > and totally ditch the CGI, and even the apache. > > http://twistedmatrix.com/ > > http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py > > Diez From steve at REMOVEME.cybersource.com.au Wed Feb 28 00:21:13 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Feb 2007 16:21:13 +1100 Subject: Changing directories in oswalk [was Re: Walk thru each subdirectory from a top directory] References: <1172525300.450438.57080@8g2000cwh.googlegroups.com> <1172529799.827628.321760@p10g2000cwp.googlegroups.com> <12ua1bo77j0n724@corp.supernews.com> Message-ID: On Tue, 27 Feb 2007 20:31:43 -0800, Scott David Daniels wrote: >> def findallfiles(self, base): >> self.results = [] >> for root,dirs,files in os.walk(base): >> os.chdir(root) > ^^^ Mistake here, don't change directories during os.walk ^^^ I came across this problem some time ago. I had to walk a directory tree, calling an external program on each file. Unfortunately, that external program wrote directly to the current working directory, which caused all sorts of havoc. This is how I dealt with it: def unbin(where): """Walk through a directory tree, calling macunpack to extract the contents of MacBinary files. """ def _unbin(data, dirname, files): for oldname in files: fullname = os.path.normpath(os.path.join(dirname, oldname)) if os.path.isfile(fullname): # Dammit, macunpack writes directly to the current # working directory. Changing the cwd breaks the file # tree walker, so we have to remember the current # directory, change it to where we want to be, then # change it back. wd = os.getcwd() os.chdir(dirname) result = os.system('macunpack -f "%s"' % oldname) if result == 0: # Unpacking worked, so delete the original. os.remove(oldname) os.chdir(wd) # sigh... os.path.walk(where, _unbin, None) Is there another (better) way of dealing with this sort of situation? -- Steven D'Aprano From nszabolcs at gmail.com Wed Feb 14 22:04:31 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 14 Feb 2007 19:04:31 -0800 Subject: Recursive calls and stack In-Reply-To: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> References: <1171433377.004899.25050@a34g2000cwb.googlegroups.com> Message-ID: <1171508671.200196.241750@j27g2000cwj.googlegroups.com> jm.suresh at no.spam.gmail.com wrote: > Hi, > I have a program which literately finds the object that overlapping a > point. The horizontal and vertical search are called recursively from > inside each other. > ... in case you ever need deeply nested recursion: one solution is to use the already mentioned sys.setrecursionlimit(n) another is to use your own stack dummy example: def fact_recursive(n): if n>0: return fact_recursive(n-1)*n else: return 1 def fact_iterative(n): stack = [] while n > 0: stack.append(n) n -= 1 ret = 1 while stack: ret *= stack.pop() return ret actually you can always rewrite recursion with a stack and iterations note that if you use version >= 2.4, then collections.deque is faster for stack (and especially for queue) data structure than list. From mail at timgolden.me.uk Mon Feb 26 11:18:07 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Feb 2007 16:18:07 +0000 Subject: ez_setup.py In-Reply-To: <45E3075E.2090308@knmi.nl> References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> <45E305D0.4010806@timgolden.me.uk> <45E3075E.2090308@knmi.nl> Message-ID: <45E3083F.2020303@timgolden.me.uk> Nader Emami wrote: >>> How can do the second solution, (take off the home from Python path)? >> >> Depends on your setup. Since you're on *nix, I can't >> test whether $HOME is automatically on sys.path (it >> isn't on Win32). Are you running *in* /usr/people/emami? >> If so, go somewhere else before you run ez_setup. Check >> your PYTHONPATH env var; perhaps reset it before >> running ez_setup. There are other more obscure possibilities >> to do with things set in site.py but they're less likely. >> >> TJG > I have a Linux and I don't have any PYTHONPTH variable, because if I run > the next command it returns nothig: > > %env | grep -i pythonpath or > %env | grep -i python I'm no expert here, but I believe that Linux is case-sensitive, so you'd need to do: env | grep PYTHONPATH TJG From mfmdevine at gmail.com Fri Feb 23 03:53:38 2007 From: mfmdevine at gmail.com (amadain) Date: 23 Feb 2007 00:53:38 -0800 Subject: pexpect regex help In-Reply-To: <1172220418.035252.65410@8g2000cwh.googlegroups.com> References: <1172099628.074816.61980@q2g2000cwa.googlegroups.com> <1172099731.535866.234380@s48g2000cws.googlegroups.com> <1172220418.035252.65410@8g2000cwh.googlegroups.com> Message-ID: <1172220818.916947.11650@v33g2000cwv.googlegroups.com> On Feb 23, 8:46 am, "amadain" wrote: > On Feb 21, 11:15 pm, jonathan.s... at gmail.com wrote: > > > > > On Feb 21, 6:13 pm, jonathan.s... at gmail.com wrote: > > > > I have apexpectscript to walk through a cisco terminal server and I > > > was hoping to get some help with this regex because I really suck at > > > it. > > > > This is the code: > > > > index = s.expect(['login: ',pexpect.EOF,pexpect.TIMEOUT]) > > > if index == 0: > > > m = re.search('((#.+\r\n){20,25})(\s.*)', > > > s.before) #<---------- MY PROBLEM > > > print m.group(3), > > > print ' %s %s' % (ip[0], port) > > > s.send(chr(30)) > > > s.sendline('x') > > > s.sendline('disco') > > > s.sendline('\n') > > > elif index == 1: > > > print s.before > > > elif index == 2: > > > print > > > print '%s %s FAILED' % (ip[0], port) > > > print 'This host may be down or locked on the TS' > > > s.send(chr(30)) > > > s.sendline('x') > > > s.sendline('disco') > > > s.sendline('\n') > > > > This is attempting to match the hostname of the connected host using > > > the output of a motd file which unfortunately is not the same > > > everywhere... It looks like this: > > > > ######################################################################### > > > # This system is the property > > > of: # > > > # > > > # > > > # DefNet > > > # > > > # > > > # > > > # Use of this system is for authorized users > > > only. # > > > # Individuals using this computer system without authority, or > > > in # > > > # excess of their authority, are subject to having all of > > > their # > > > # activities on this system monitored and recorded by > > > system # > > > # > > > personnel. # > > > # > > > # > > > # In the course of monitoring individuals improperly using > > > this # > > > # system, or in the course of system maintenance, the > > > activities # > > > # of authorized users may also be > > > monitored. # > > > # > > > # > > > # Anyone using this system expressly consents to such > > > monitoring # > > > # and is advised that if such monitoring reveals > > > possible # > > > # evidence of criminal activity, system personnel may provide > > > the # > > > # evidence of such monitoring to law enforcement > > > officials. # > > > ######################################################################### > > > > pa-chi1 console login: > > > > And sometimes it looks like this: > > > > ######################################################################### > > > # This system is the property > > > of: # > > > # > > > # > > > # DefNet > > > # > > > # > > > # > > > # Use of this system is for authorized users > > > only. # > > > # Individuals using this computer system without authority, or > > > in # > > > # excess of their authority, are subject to having all of > > > their # > > > # activities on this system monitored and recorded by > > > system # > > > # > > > personnel. # > > > # > > > # > > > # In the course of monitoring individuals improperly using > > > this # > > > # system, or in the course of system maintenance, the > > > activities # > > > # of authorized users may also be > > > monitored. # > > > # > > > # > > > # Anyone using this system expressly consents to such > > > monitoring # > > > # and is advised that if such monitoring reveals > > > possible # > > > # evidence of criminal activity, system personnel may provide > > > the # > > > # evidence of such monitoring to law enforcement > > > officials. # > > > ######################################################################### > > > pa11-chi1 login: > > > > The second one works and it will print out pa11-chi1 but when there > > > is a space or console is in the output it wont print anything or it > > > wont match anything... I want to be able to match just the hostname > > > and print it out. > > > > Any ideas? > > > > Thanks, > > > > Jonathan > > > It is also posted here more clearly and formatted as it would appear > > on the terminal: http://www.pastebin.ca/366822 > > what about using s.before.split("\r\n")[-1]? > > A result=[x for x in s.before.split("\r\n") if x != ""] print result[-1] should cover the blank line problem A From gagsl-py at yahoo.com.ar Sat Feb 3 04:04:20 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Feb 2007 06:04:20 -0300 Subject: python bracket References: Message-ID: En Sat, 03 Feb 2007 02:48:45 -0300, escribi?: > there is no bracket in python > > how can i know where a loop or a function ends? You should read some introductory texts at least. You can find the Python Tutorial inside your Python install, or you can read it online at http://docs.python.org/tut/ The book Dive into Python is also available online at http://www.diveintopython.org/ NB: Indentation is important in Python. A block ends when a less indented line appears. -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Feb 26 16:38:38 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Feb 2007 13:38:38 -0800 Subject: Add images together In-Reply-To: <1172524574.348556.216270@z35g2000cwz.googlegroups.com> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> <54gtc3F214sakU1@mid.uni-berlin.de> <1172521836.797866.96220@z35g2000cwz.googlegroups.com> <1172523536.033424.122230@a75g2000cwd.googlegroups.com> <1172524574.348556.216270@z35g2000cwz.googlegroups.com> Message-ID: <1172525918.722674.154130@p10g2000cwp.googlegroups.com> On Feb 26, 10:16 pm, "iceman" wrote: > a)Yes, I am using PIL. > b)The color of each pixel over a sequence of frames I think PIL has it for 2 images, you may have to build a binary tree of merged images: http://www.pythonware.com/library/pil/handbook/image.htm#blend Bye, bearophile From orsenthil at gmail.com Wed Feb 28 07:53:14 2007 From: orsenthil at gmail.com (Phoe6) Date: 28 Feb 2007 04:53:14 -0800 Subject: using telnetlib In-Reply-To: <54l6hpF21daqnU1@mid.individual.net> References: <1172654582.919944.13530@k78g2000cwa.googlegroups.com> <54l6hpF21daqnU1@mid.individual.net> Message-ID: <1172667194.789186.235640@p10g2000cwp.googlegroups.com> On Feb 28, 4:15 pm, Bjoern Schliessmann wrote: > Phoe6 wrote: > >>>> import telnetlib > >>>> tn = telnetlib.Telnet("172.31.128.244") > >>>> tn.read_until("Login: ") > > '\r\nLogin: ' > >>>> tn.write("root\n:") > > ^^^ > > With telnet, use "\r\n" for line breaks at *all* times to be on the > safe side. Thanks a lot, Bj?rn. That did help and solved my problem. ":" after \n was just a typo. -- Senthil From bdesth.quelquechose at free.quelquepart.fr Wed Feb 28 17:49:49 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 28 Feb 2007 23:49:49 +0100 Subject: Question about raise and exceptions. In-Reply-To: References: <45e5e640$0$18215$426a74cc@news.free.fr> Message-ID: <45e5ff3f$0$1861$426a34cc@news.free.fr> Steven W. Orr a ?crit : > On Wednesday, Feb 28th 2007 at 22:03 +0100, quoth Bruno Desthuilliers: > > =>Daniel Klein a ?crit : > =>> On Wed, 28 Feb 2007 13:48:54 -0500 (EST), "Steven W. Orr" > =>> wrote: > =>> > =>> > =>>>When I run it I get this: > =>>> > =>>>884 > ./t_fsm.py > =>>>Traceback (most recent call last): > =>>> File "./t_fsm.py", line 3, in ? > =>>> from fsm import * > =>>> File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76 > =>>> raise TransitionError, self.curr_state, newstate, "Going to error > =>>>state %d from state %d" % (self.curr_state, newstate) > =>>> ^ > =>>>SyntaxError: invalid syntax > =>> > =>> > =>> The arguments for TransitionError must be a tuple, > => > =>Err... > => > =>> eg: > =>> > =>> msg = "Going to error state %d from state %d" % (self.curr_state, > =>> newstate) > =>> raise TransitionError(self, curr_state, newstate, msg) fix: should be: raise TransitionError(self.curr_state, newstate, msg) or raise TransitionError, (self.curr_state, newstate, msg) (snip) > > Ok. Now I'm potentially confused: > 1. TransitionError takes 4 args Almost (cf fix above). > 2. raise takes a tuple with four elements after the exception argument as > its 2nd arg No. > I take it you mean #2? > No. the raise statement syntax is: "raise" [typeOrInstance ["," value ["," traceback]]] Most exceptions only take a single value (the error message), and it's very uncommon (at least in application code) to substitute another traceback. Now back to the "value" part. If your exception type expects more than one arg, it's legal to use a tuple for the value(s). It will then be passed to the exception type (using *args expansion). It's legal, but it doesn't make the code much more readable. It's IMHO better to explicitely instanciate the exception with the needed params. Which of these two lines do you find the most readable ? raise TransitionError(self.curr_state, newstate, msg) vs raise TransitionError, (self.curr_state, newstate, msg) HTH From pDOTpagel at gsf.de Mon Feb 26 09:03:14 2007 From: pDOTpagel at gsf.de (Philipp Pagel) Date: Mon, 26 Feb 2007 14:03:14 +0000 (UTC) Subject: a=b change b a==b true?? References: <1172497824.167581.100230@q2g2000cwa.googlegroups.com> Message-ID: rstupplebeen at gmail.com wrote: > I do not have a clue what is happening in the code below. > >>> a=[[2,4],[9,3]] > >>> b=a > >>> [map(list.sort,b)] > [[None, None]] > >>> b > [[2, 4], [3, 9]] > >>> a > [[2, 4], [3, 9]] > I want to make a copy of matrix a and then make changes to the > matrices separately. I assume that I am missing a fundamental > concept. The concept you are missing is the fact that b = a makes b another name for your nested list. As you correctly stated you really want a copy. This will do what you want: >>> import copy >>> a=[[2,4],[9,3]] >>> b = copy.deepcopy(a) >>> [map(list.sort,b)] [[None, None]] >>> a [[2, 4], [9, 3]] >>> b [[2, 4], [3, 9]] cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel From gagsl-py at yahoo.com.ar Mon Feb 19 19:30:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 21:30:11 -0300 Subject: writing a file:newbie question References: <933431.84534.qm@web7806.mail.in.yahoo.com> Message-ID: En Mon, 19 Feb 2007 08:02:29 -0300, kavitha thankaian escribi?: > Hi, > i have a file test.txt and it contains a list of strings say,,, > "a","b","c","d","a1","b1","c1","d1","a2","b2","c2","d2", > i would like to write the file as > "a","b","c","d" > "a1","b1","c1","d1 > "a2","b2","c2","d2" > and would like to delete the comma at the end. Not enough info... Does the input file contain only one line, or many lines? Always exactly 12 items? Including a trailing , ? The following may work for 12 items. Use the csv module to read the file: import csv reader = csv.reader(open("test.txt", "r")) writer = csv.writer(open("output.txt", "w")) for row in reader: writer.writerow(row[:4]) writer.writerow(row[4:8]) writer.writerow(row[8:]) -- Gabriel Genellina From deets at nospam.web.de Wed Feb 28 09:39:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Feb 2007 15:39:23 +0100 Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01><1172561344.290126.191530@h3g2000cwc.googlegroups.com><3c5Fh.3664$Tg7.2156@trnddc03> Message-ID: <54ligrF21q2biU1@mid.uni-berlin.de> > However I will observe that > - entire languages are structured on the premise that dynamic > attribute creation can be hazardous Yup, and you are free to use one of them. And as an additional benefit, they will be more performant because you then can optimize the code further. But they certainly do need more code to accomplish the same things easily done in python (or other dynamic languages for that matter) > - debuggers watch out for dynamic attribute creation, which > tells us it is a common source of bugs > - I sincerely doubt that anyone who has written more than > a couple scripts in Python has never accidentally created an > attribute dynamically while intending to assign to an existing > attribute. Certainly that happened, but not in a number of occasions that its impact on every day programming isn't dwarfed by the much more prevalent gain in productivity using python. You strive for the combination of disadvantages of statically typed languages with the disadvantages of a dynamically typed one. Not too much of an convincing goal IMHO. Diez From txdyjsyz at gmail.com Tue Feb 6 06:43:58 2007 From: txdyjsyz at gmail.com (mars) Date: 6 Feb 2007 03:43:58 -0800 Subject: How to prevent from race conditions to share data between many process and thread in python In-Reply-To: <52r2njF1of0tpU1@mid.uni-berlin.de> References: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> <52r2njF1of0tpU1@mid.uni-berlin.de> Message-ID: <1170762238.532367.269120@l53g2000cwa.googlegroups.com> On 2?6?, ??6?14?, "Diez B. Roggisch" wrote: > mars wrote: > > I use TurboGears to do some web service. TurboGears use cherrypy. When > > web browser access this site, the cherrypy will call my python > > program. So my program looks like a lib. When web browser access the > > site, the http server will fock a process or gerenate a thread. I need > > share some data or operate some files. How can I prevent from race > > conditions. Is there any way can I lock this. > > Thank you in advance! > > There are the Lock and RLock objects available in the module threading. > > Diez Can this also lock mutil-process? From B.Ogryczak at gmail.com Fri Feb 2 09:56:12 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 2 Feb 2007 06:56:12 -0800 Subject: newbie/ merging lists of lists with items in common In-Reply-To: References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: <1170428172.648199.114160@a34g2000cwb.googlegroups.com> On Feb 2, 3:19 pm, Larry Bates wrote: > l=[x for x in d.items()] d.items() is not an iterator, you don?t need this. This code is equivalent to l = d.items(). From nagle at animats.com Sun Feb 4 17:39:12 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Feb 2007 22:39:12 GMT Subject: Unicode problem in BeautifulSoup; worked in Python 2.4, fails in Python 2.5. In-Reply-To: <1170618799.354069.327210@h3g2000cwc.googlegroups.com> References: <5aoxh.7440$gJ1.6708@newsfe17.lga> <1170618799.354069.327210@h3g2000cwc.googlegroups.com> Message-ID: I'm running a website page through BeautifulSoup. It parses OK with Python 2.4, but Python 2.5 fails with an exception: Traceback (most recent call last): File "./sitetruth/InfoSitePage.py", line 268, in httpfetch self.pagetree = BeautifulSoup.BeautifulSoup(sitetext) # parse into tree form File "./sitetruth/BeautifulSoup.py", line 1326, in __init__ BeautifulStoneSoup.__init__(self, *args, **kwargs) File "./sitetruth/BeautifulSoup.py", line 973, in __init__ self._feed() File "./sitetruth/BeautifulSoup.py", line 998, in _feed SGMLParser.feed(self, markup or "") File "/usr/lib/python2.5/sgmllib.py", line 99, in feed self.goahead(0) File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead k = self.parse_starttag(i) File "/usr/lib/python2.5/sgmllib.py", line 291, in parse_starttag self.finish_starttag(tag, attrs) File "/usr/lib/python2.5/sgmllib.py", line 340, in finish_starttag self.handle_starttag(tag, method, attrs) File "/usr/lib/python2.5/sgmllib.py", line 376, in handle_starttag method(attrs) File "./sitetruth/BeautifulSoup.py", line 1416, in start_meta self._feed(self.declaredHTMLEncoding) File "./sitetruth/BeautifulSoup.py", line 998, in _feed SGMLParser.feed(self, markup or "") File "/usr/lib/python2.5/sgmllib.py", line 99, in feed self.goahead(0) File "/usr/lib/python2.5/sgmllib.py", line 133, in goahead k = self.parse_starttag(i) File "/usr/lib/python2.5/sgmllib.py", line 285, in parse_starttag self._convert_ref, attrvalue) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: ordinal not in range(128) The code that's failing is in "_convert_ref", which is new in Python 2.5. That function wasn't present in 2.4. I think the code is trying to handle single quotes inside of double quotes, or something like that. To replicate, run http://www.bankofamerica.com or http://www.gm.com through BeautifulSoup. Something about this code doesn't like big companies. Web sites of smaller companies are going through OK. Also reported as a bug: [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 John Nagle From Ron at FascinatingElectronics.com Thu Feb 8 16:04:52 2007 From: Ron at FascinatingElectronics.com (Ron Jackson) Date: Thu, 08 Feb 2007 13:04:52 -0800 Subject: Pyserial example program error: win32file.SetupComm reports 'Incorrect function.' In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Wed, 07 Feb 2007 11:14:39 -0800, Ron Jackson > declaimed the following in > comp.lang.python: > > >>I am using Python 2.5 on Windows XP. I have installed Pyserial and >>win32all extensions. >> > > 2.4 on XP Pro SP2... > > >>When I try to run the example program scan.py (included below), or any >>other program using pyserial, as soon as it hits the statement: >> >>s = serial.Serial(i) >> > > >>>>import serial >>>>for i in range(256): > > ... try: > ... print i, > ... s = serial.Serial(i) > ... print s.portstr > ... s.close() > ... except serial.SerialException: > ... print > ... > 0 COM1 > 1 > 2 COM3 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > 11 > and on and on... > > >>What do I need to do to fix this? Thanks for the help! > > > Does the serial port module require a compile for use with 2.5? > Well, with only one download since Python 2.2, guess not... > > Something glitched in win32? Sorry, I don't know... However, since > those are Python source files, you could always plug in some debugging > lines around that win32 call to see what actually is there. Do you have > any unnatural serial ports on the machine? (Like a USB<>serial > converter?) Trying your program, I get the same error 'Incorrect function.': Traceback (most recent call last): File "", line 4, in s = serial.Serial(i) File "C:\Python25\Lib\site-packages\serial\serialutil.py", line 156, in __init__ self.open() File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 57, in open win32file.SetupComm(self.hComPort, 4096, 4096) error: (1, 'SetupComm', 'Incorrect function.') I tried PySerial on a laptop, also running XP Home SP2, and both the example program and the program you suggested work fine on the laptop. The desktop computer that is giving me the error doesn't have any unnatural serial ports on it currently. The laptop worked fine, either with a USB device emulating COMM6 present or with the USB device disconnected. I checked and both machines are running the same version of win32file, which is site-packages\win32\win32file.pyd, 88 KB dated 9/22/2006. So my question is: Why would the statement win32file.SetupComm(self.hComPort, 4096, 4096) work just fine on one machine and not the other? win32file.pyd can't be opened like a .py file, and I don't know what the rather cryptic error 'Incorrect function.' is trying to tell me. Does anyone who is familiar with win32file have an idea what the problem is? Thanks for the help! -- Ron From troy.melhase at gmail.com Fri Feb 23 17:51:09 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Fri, 23 Feb 2007 13:51:09 -0900 Subject: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API In-Reply-To: <1172270184.855786.146510@q2g2000cwa.googlegroups.com> References: <1172270184.855786.146510@q2g2000cwa.googlegroups.com> Message-ID: On 23 Feb 2007 14:36:24 -0800, vj wrote: > Cool. Why is python 2.5 required, will it not work with python 2.4? Short answer: because java2python produces python 2.5 syntax. Long answer: I wrote java2python specifically to translate the IB reference code. That reference code makes heavy use of the java ternary operator, and I wanted the most direct representation of that -- which is the conditional expression provided in python 2.5. From rrr at ronadam.com Sat Feb 3 11:30:35 2007 From: rrr at ronadam.com (Ron Adam) Date: Sat, 03 Feb 2007 10:30:35 -0600 Subject: from __future__ import absolute_import ? In-Reply-To: References: Message-ID: Peter Otten wrote: > Ron Adam wrote: > >> >> work >> | >> |- foo.py # print "foo not in bar" >> | >> `- bar >> | >> |- __init__.py >> | >> |- foo.py # print "foo in bar" >> | >> |- absolute.py # from __futer__ import absolute_import >> | # import foo >> | >> `- relative.py # import foo >> >> >> * Where "work" is in the path. >> >> >> (1) >> >> C:\work>python -c "import bar.absolute" >> foo not in bar >> >> C:\work>python -c "import bar.relative" >> foo in bar >> >> >> (2) >> >> C:\work>python -m "bar.absolute" >> foo not in bar >> >> C:\work>python -m "bar.relative" >> foo not in bar >> >> >> (3) >> >> C:\work>python >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] >> on win 32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import bar.absolute >> foo not in bar >> >>> import bar.relative >> foo in bar >> >> >> (4) >> >> C:\work>cd bar > > A path below the package level is generally a good means to shoot yourself > in the foot and should be avoided with or without absolute import. Seems so. :-/ >> C:\work\bar>python -c "import bar.absolute" >> foo in bar >> >> C:\work\bar>python -c "import bar.relative" >> foo in bar >> >> >> (5) >> >> C:\work\bar>python >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] >> on win 32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import bar.absolute >> foo in bar >> >>> import bar.relative >> foo in bar >> >>> >> >> >> >> Case (2) seems like it is a bug. > > I think so, too. This one is the reasons I had trouble figuring it out. I was using the -m command option when I tried to test it. There is a bug report on absolute/relative imports already. I'm not sure if this particular item is covered under it or not. Doesn't sound like it as the bug report address the relative aspects of it. >> Why not also have (4), and (5) do the same as cases (1) and (3)? > > The work/bar directory is the current working directory and occurs in the > path before the work directory. Yes. Unfortunately this is a side effect of using the os's directory structure to represent a python "package" structure. If a package was represented as a combined single file. Then the working directory would always be the package directory. > When bar.absolute imports foo python is > unaware that work/bar/foo.py is part of the bar package. Umm.... isn't the "bar" stuck on the front of "bar.absolute" a pretty obvious hint. ;-) If you run the module directly as a file... python bar/foo.py or python foo.py Then I can see that it doesn't know. But even then, it's possible to find out. ie... just check for an __init__.py file. Python has a certain minimalist quality where it tries to do a lot with a minimum amount of resources, which I generally love. But in this situation that might not be the best thing. It would not be difficult for python to detect if a module is in a package, and determine the package location. With the move to explicit absolute/relative imports, it would make since if python also were a little smarter in this area. >> in cases (4) and (5), that is the result I would expect if I did: >> >> import absolute # with no 'bar.' prefix. >> import relative >> >> >> From what I understand, in 2.6 relative imports will be depreciated, and >> in 2.7 >> they will raise an error. (providing plans don't change) >> >> Would that mean the absolute imports in (4) and (5) would either find the >> 'foo not in bar' or raise an error? > > No, in 1, 3 -- and 2 if the current behaviour is indeed a bug. This is only > for the relative import which would have to be spelt > > from . import foo Was that a 'yes' for exampels 4 and 5, since 1,2 and 3 are 'no'? > in an absolute-import-as-default environment; > > import foo > > would always be an absolute import. But what is the precise meaning of "absolute import" in this un-dotted case? Currently it is: "A module or package that is located in sys.path or the current directory". But maybe a narrower interpretation may be better?: "A module or package found in sys.path, or the current directory and is *not* in a package." If it's in a package then the dotted "absolute" name should be used. Right? I guess what I'm getting at, is it would be nice if the following were always true. from __import__ import absolute_import import thispackage.module import thispackage.subpackage # If thispackage is the same name as the current package, # then do not look on sys.path. import otherpackage.module import otherpackage.subpackage # If otherpackage is a different name from the current package, # then do not look in this package. import module import package # Module and package are not in a package, even the current one, # so don't look in any packages, even if the current directory is # in this (or other) package. If these were always true, :-) I think it avoid some situations where things don't work, or don't work like one would expect. In addition to the above, when executing modules directly from a directory inside a package, if python were to detect the package and then follow these same rules. It would avoid even more surprises. While you are editing modules in a package, you could then run them directly and get the same behavior you get if you cd'd out of the package and then ran it. All in all, what I'm suggesting is that the concept of a package (type) be much stronger than that of a search path or current directory. And that this would add a fair amount of reliability to the language. IMHO, of course. :-) Cheers, Ron >> If so, is there any way to force (warning/error) behavior now? > > I don't know. > > Peter > From gagsl-py at yahoo.com.ar Sat Feb 17 03:58:34 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Feb 2007 05:58:34 -0300 Subject: HTTP_REFERER value References: <1171701486.540940.151990@h3g2000cwc.googlegroups.com> Message-ID: En Sat, 17 Feb 2007 05:38:06 -0300, Johny escribi?: > Is HTTP_REFERER value transfered between different domains? > For example if I come to a website , say, www.python.org, from > website www.microsoft.com > will www.python.org finds that I came there from www.microsoft.com? Yes. This is how you know who is sending traffic to your site; some browsers (Opera by example) let the user choose not to send this header. (And what has this to do with Python?) -- Gabriel Genellina From gagsl-py at yahoo.com.ar Sat Feb 10 19:22:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 21:22:52 -0300 Subject: Need a cross-platform way to execute binary References: <1171098220.101483.138910@q2g2000cwa.googlegroups.com> <1171108111.691268.168510@v45g2000cwv.googlegroups.com> Message-ID: En Sat, 10 Feb 2007 08:48:31 -0300, techtonik escribi?: > On Feb 10, 12:03 pm, "Gabriel Genellina" >> > Here "executable" means file that >> > could be be launched by system() (if there are any other ways - I'd be >> > happy to know them) This is a very specific definition of "executable". os.access does not use that definition. >> >>>> os.access("../../ufo2map", os.X_OK) >> > False >> >> That's right - such file does not exist. On Windows, in general, X_OK is >> the same as F_OK: for any existing file, whatever name or extension, >> returns True. Permissions are managed thru ACL and this simple function >> does NOT consider them. > > It shouldn't matter if the file exists or not. Quoting http:// > docs.python.org/lib/os-file-dir.html: > " > X_OK > Value to include in the mode parameter of access() to determine > if path can be executed. > " > > See - there is no "file" notation as only "path" is tested and "path" > is pretty executable. It appears that your argument is: os.system("../../ufo2map") launches a new process, so "../../ufo2map" must be executable. But os.system("foo.txt") also works, so "foo.txt" is also executable? Please define "executable" first. The definition may be so restrictive as to only include PE files (all others require a wrapping process) or so broad as to include almost anything known to the system. > I think this should be clarified in os.access() > documentation to make the whole business less confusing if not > implemented in interpreter itself. After all the purpose of cross- > platform language is to free developer from writing platform-specific > code. os.access documentation is rather clear - it's just a wrapper around the access() system call, and I think it should not be changed. It is the underlying OS which gives the answer, not Python. On the other hand, an utility library exposing FindExecutable, ShellExecute, associations and other shell goodies might be useful. Maybe you could do some research, whether such thing exists, and help improve it or design a good interfase? > I would prefer to know as little about underlying platforms as > possible. > It would only be a big plus for Python. Sure, but someone has to write it. I can't think of a good abstraction right now, perhaps you have some ideas? -- Gabriel Genellina From jonc at icicled.net Fri Feb 2 18:56:45 2007 From: jonc at icicled.net (Jonathan Curran) Date: Fri, 2 Feb 2007 17:56:45 -0600 Subject: Where Does One Begin? In-Reply-To: References: Message-ID: <200702021756.45244.jonc@icicled.net> Hey n00b :) If you want to start 2d game programming w/python, I would look at the package pygame. There are some intro. tutorials at http://www.pygame.org/wiki/tutorials. These should give you a head start. Besides that, I suggest you scour the web via google to look at the source of simple 2d games to learn more. Good places to look at: gamedev.net, allegro.cc, amit's game programming information Good luck! - Jonathan From dickinsm at gmail.com Thu Feb 15 18:52:13 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 15 Feb 2007 15:52:13 -0800 Subject: cmath, __float__ and __complex__ Message-ID: <1171583533.455129.261490@k78g2000cwa.googlegroups.com> I was a little surprised by the following behaviour: Python 2.5 (r25, Oct 30 2006, 20:50:32) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from cmath import sqrt >>> class NumericType1(object): ... def __float__(self): return 10.0 ... >>> class NumericType2(object): ... def __complex__(self): return 10+0j ... >>> print sqrt(NumericType1()) (3.16227766017+0j) >>> print sqrt(NumericType2()) Traceback (most recent call last): File "", line 1, in TypeError: a float is required Having recently made the pleasant discovery that math.sqrt and friends will happily accept any object with a working __float__ attribute, I expected the same to be true with regards to cmath and __complex__. The bit that I find really counter-intuitive is that the cmath functions will use __float__ if available, but completely ignore __complex__. Does anyone know of a good reason for the above behaviour? Would a patch to complexobject.c that `fixes' this be of any interest to anyone but me? Or would it likely break something else? Mark From randomgeek at cyberspace.net Mon Feb 26 20:51:59 2007 From: randomgeek at cyberspace.net (Dan Bensen) Date: Mon, 26 Feb 2007 19:51:59 -0600 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: > Tech HR wrote: > easier to train a Java programmer or a Perler on Python than Lisp. Dan Bensen wrote: > Are your technical problems simple enough to be solved by Python > trainees? Aahz wrote: > If they're already good programmers, yes. Sure, but who are these good programmers (coming from Java or Perl)? Do you have a list of them? The employer needs to know how many not-so-good programmers they have to interview before they find one who's good enough. It depends on how hard the programming is. -- Dan www.prairienet.org/~dsb From aspineux at gmail.com Fri Feb 2 14:40:59 2007 From: aspineux at gmail.com (aspineux) Date: 2 Feb 2007 11:40:59 -0800 Subject: imaplib : error reporting use 'randomly' exception or return value In-Reply-To: <1170368897.603190.68750@v45g2000cwv.googlegroups.com> References: <1170368897.603190.68750@v45g2000cwv.googlegroups.com> Message-ID: <1170445259.884492.3100@j27g2000cwj.googlegroups.com> I looked carefully imaplib.py and wrote this version of _simple_command that take care of the way the function is used by other to keep the same functionality class bye(imaplib.IMAP4.abort): pass class bad(imaplib.IMAP4.abort): pass def _simple_command(self, name, *args): typ, dat=self._command_complete(name, self._command(name, *args)) if typ!='OK': if name in ('LOGOUT',): return typ, dat if name in ('EXAMINE', 'SELECT'): self.state = 'AUTH' if typ=='BYE': raise self.bye(dat[-1]) elif typ=='BAD': raise self.bad(dat[-1]) else: raise self.error(dat[-1]) return typ, dat On 1 f?v, 23:28, "aspineux" wrote: > imaplib use exception to report errors, but some problems must be > detected by checking the return value ! > For example, when trying to append into a mailbox with wrong ACL, > imaplib return 'NO', but dont raise any exception (I give a sample at > the end). > This make error handling more complicate, because any imap statement > is supposed to be followed by a test of the returned value! > > Why not report all problems using exceptions ? > > It easy to modify imaplib.py to manage this because most of the imap > call are made through function > _simple_command this way : > > def _simple_command(self, name, *args): > return self._command_complete(name, self._command(name, > *args)) > > I propose to replace it by something like : > > def _simple_command(self, name, *args): > typ, dat=self._command_complete(name, self._command(name, > *args)) > if typ!='OK': > raise self.error(dat[-1]) > return typ, dat > > Any comment ? > > Here is an example, append on a mailbox with the wrong ACL fail by > returning a 'NO' > > import imaplib > > server='localhost' > login='t... at asxnet.loc' > passwd='password' > > c=imaplib.IMAP4(server) > c.login(login, passwd) > c.setacl('INBOX', login, '') # set wrong ACL, removing 'i' > typ, dat=c.append('INBOX', None, None, "From: f... at bar.com\nTo: %s > \nSubject: test append\n\nHello\n" % (login)) > print typ, dat > > output: > > NO ['Permission denied'] From ruan at jcmills.com Sat Feb 3 19:34:19 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Sat, 3 Feb 2007 19:34:19 -0500 Subject: confused about resizing array in Python References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: This seems to be clever to use reference for list. Is it unique to Python? How about the traditional programming languages like C, Pascal or C++? "Roel Schroeven" wrote in message news:qx9xh.325276$Ko7.6479988 at phobos.telenet-ops.be... > Dongsheng Ruan schreef: >> "Roel Schroeven" wrote in message >> news:vc8xh.325172$Au6.6345787 at phobos.telenet-ops.be... >>> Ruan schreef: >>>> Then how about Python's list? >>>> >>>> What is done exactly when list.append is executed? >>>> >>>> For list, is there another larger list initialized and the contents >>>> from the old list is copied to it together with the new appended list? > >>> I'm not sure, but I think each time the list needs to grow, it doubles >>> in size. That leaves room to add a number of elements before the >>> allocated space needs to grow again. It's a frequently used approach, >>> since it is quite efficient and the memory needed is never double the >>> amount of memory strictly needed for the elements of the list. > > > You mentioned "it doubles in size". > > > > Are you saying that a new double sized array is allocated and the > > contents of the old list is copied there? > > > > Then the old list is freed from memory? > > > > It seems to be what is called amortized constant. > > > > Say the list size is 100, before it is fully used, the append takes > > O(1) time. But for the 101th element, the time will be O(100+1), and > > then from then on, it is O(1) again. Like John Machin said in the > > previous post? > > > > But on average, it is O(1). I guess this is the amortized constant. > > Isn't it? > > I think so, more or less, but as I said I'm not entirely sure about how > Python handles lists. > > One thing to keep in mind is that the list (like any other Python data > structure) doesn't store the objects themselves; it only stores references > to the objects. If the list needs to be copied, only the references are > copied; the objects themselves can stay where they are. For small objects > this doesn't make much difference, but if the objects grow larger it gets > much more efficient if you only have to move the references around. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven From mail at ozzmosis.com Mon Feb 12 14:35:36 2007 From: mail at ozzmosis.com (andrew clarke) Date: Tue, 13 Feb 2007 06:35:36 +1100 Subject: c++ for python programmers In-Reply-To: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <20070212193536.GA33388@ozzmosis.com> On Mon, Feb 12, 2007 at 10:00:51AM -0800, Thomas Nelson wrote: > I realize I'm approaching this backwards from the direction most > people go, but does anyone know of a good c/c++ introduction for > python programmers? Thomas, I sent you a message off-list but it bounced due to your mailbox being full. Short answer: Subscribe to the c-prog at yahoogroups.com mailing list and ask your C/C++ questions there. Regards Andrew From gregturn at mindspring.com Fri Feb 2 00:17:27 2007 From: gregturn at mindspring.com (gregturn at mindspring.com) Date: 1 Feb 2007 21:17:27 -0800 Subject: Spring Python 0.2.0 is released Message-ID: <1170393447.301368.124140@l53g2000cwa.googlegroups.com> Spring Python is an offshoot of the Java-based SpringFramework and AcegiSecurityFramework, targeted for Python. Spring provides many useful features, and I wanted those same features available when working with Python. The site is http://springpython.python-hosting.com, with information about source code, releases, and mailing lists. The following features have been implemented. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * InversionOfControl - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. * AspectOrientedProgramming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DistributedRemoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * PetClinic - A nice sample web application has been built utilizing CherryPy as the web container. Go check it out for an example of how to use this framework. * ApplicationSecurity - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * SpringWiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! For more details about implemented features, check out the tickets tied to this baseline at: http://springpython.python-hosting.com/query?status=closed&milestone=0.2 From thegeoffmeister at gmail.com Sat Feb 10 23:20:48 2007 From: thegeoffmeister at gmail.com (Geoff Hill) Date: Sun, 11 Feb 2007 04:20:48 GMT Subject: Regular Expressions References: <1171162731.488726.160400@a75g2000cwd.googlegroups.com> Message-ID: Thanks. O'Reilly is the way I learned Python, and I'm suprised that I didn't think of a book by them earlier. From mail at timgolden.me.uk Fri Feb 16 10:29:15 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 16 Feb 2007 15:29:15 +0000 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: <1171639249.324828.304940@t69g2000cwt.googlegroups.com> References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> <1171639249.324828.304940@t69g2000cwt.googlegroups.com> Message-ID: <45D5CDCB.2060406@timgolden.me.uk> Endless Story wrote: > On Feb 16, 9:56 am, "Jim" wrote: >> On Feb 16, 5:52 am, "Endless Story" wrote: >> Are you talking about the Environment Variables-->System Variable-->path? >> You may want to right click on My Computer-->System Properties-->Advanced--> >> Environment Variables-->System variables-->Path-->Edit. >> And check to see if it's there, if not then add it. > > I've already added the new python to my path in this fashion, but to > no avail. > > Besides, if it were a path problem in the usual sense, the symptom > would be a message at the command line saying that "python" is not > recognized. Since I don't get this message, it's not a typical path > problem. What it is, I don't know - that's my quandry. > I've certainly never seen anything like what you've described, and I've had Python 2.5 installed and uninstalled on several different machines (Win2k & WinXP). I would ask if you had *any* other Python installation -- say a cygwin one -- which might just be getting in the way? Are you an administrator on the machine you're on? Sometimes (a while ago and with the ActiveState distro rather than python.org one) it has been known to cause problems if you're not. Do the previous installations still work? Clutching at straws, really. TJG From jonathan.sabo at gmail.com Wed Feb 21 18:26:53 2007 From: jonathan.sabo at gmail.com (jonathan.sabo at gmail.com) Date: 21 Feb 2007 15:26:53 -0800 Subject: network simulator in Python ? In-Reply-To: <1172078818.126692.17510@k78g2000cwa.googlegroups.com> References: <1172078818.126692.17510@k78g2000cwa.googlegroups.com> Message-ID: <1172100413.550578.105830@h3g2000cwc.googlegroups.com> On Feb 21, 12:26 pm, "DanielJohnson" wrote: > I was wondering if anyblody can suggest me a network simulator written > in python in which I can add on my own code and extend its > functionality. > > I am looking for a simulator which will simualte TCP, UDP, RTP and > most networking protocol. The learning curve for ns2 and other > simulator is too high for me at this time and thats why I am > considering Python for it. > > Every help will be appreciated. > > Thanks Google for Scapy From ah at hatzis.de Thu Feb 8 05:47:49 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Thu, 08 Feb 2007 11:47:49 +0100 Subject: uml and python In-Reply-To: <45caa188$1@news.arcor-ip.de> References: <1170900832.692717.259160@l53g2000cwa.googlegroups.com> <45caa188$1@news.arcor-ip.de> Message-ID: <45CAFFD5.7000202@hatzis.de> Ralf Sch?nian wrote: > azrael schrieb: >> hy guys >> >> i've been googling and got several posts, but nothing that is a >> satisfaction in my eyes. can someone tell me a nice uml diagram tool >> with python export (if possible nice gui), or at least nice uml tool >> >> gpl or freeware (widows) prefered >> >> thanks >> > Take a look at gaphor: http://gaphor.sourceforge.net/ > Yes, Gaphor is fine and already rather powerful. @ azrael, You can also have a look at OpenSwarm: http://openswarm.sourceforge.net/ It is an UML -> Python/SQL generator tool with some kind of runtime architecture. Sadly, still alpha and with-out GUI or Gaphor support. Regards, Anastasios From FreakCERS at gmail.com Sun Feb 25 13:29:06 2007 From: FreakCERS at gmail.com (Christian Sonne) Date: Sun, 25 Feb 2007 19:29:06 +0100 Subject: RegExp performance? In-Reply-To: <1172400479.486951.300070@v33g2000cwv.googlegroups.com> References: <45e145a0$0$90264$14726298@news.sunsite.dk> <1172400479.486951.300070@v33g2000cwv.googlegroups.com> Message-ID: <45e1d367$0$90273$14726298@news.sunsite.dk> John Machin wrote: > On Feb 25, 7:21 pm, Christian Sonne wrote: >> Long story short, I'm trying to find all ISBN-10 numbers in a multiline >> string (approximately 10 pages of a normal book), and as far as I can >> tell, the *correct* thing to match would be this: >> ".*\D*(\d{10}|\d{9}X)\D*.*" > > All of those *s are making it work too hard. > > Starting with your r".*\D*(\d{10}|\d{9}X)\D*.*" [you do have the > r"..." not just "....", don't you?] > > Step 1: Lose the .* off each end -- this is meaningless in the context > of a search() or findall() and would slow the re engine down if it > doesn't optimise it away. > > r"\D*(\d{10}|\d{9}X)\D*" > > Step 2: I presume that the \D* at each (remaining) end is to ensure > that you don't pick up a number with 11 or more digits. You only need > to test that your presumed ISBN is not preceded/followed by ONE > suspect character. Is ABC1234567890DEF OK? I think not; I'd use \b > instead of \D > > r"\b(\d{10}|\d{9}X)\b" > > Step 3: Now that we have only \b (which matches 0 characters) at each > end of the ISBN, we can lose the capturing () > > r"\b\d{10}|\d{9}X\b" > > Step 4: In the case of 123456789X, it fails on the X and then scans > the 123456789 again -- a tiny waste compared to all the * stuff, but > still worth fixing. > > r"\b\d{9}[0-9X]\b" > > Give that a whirl and let us know how correct and how fast it is. > >> (it should be noted that I've removed all '-'s in the string, because >> they have a tendency to be mixed into ISBN's) >> >> however, on my 3200+ amd64, running the following: >> >> reISBN10 = re.compile(".*\D*(\d{10}|\d{9}X)\D*.*") > > You should really get into the habit of using raw strings with re. > >> isbn10s = reISBN10.findall(contents) >> >> (where contents is the string) >> >> this takes about 14 minutes - and there are only one or two matches... > > How many actual matches and how many expected matches? > > Note on "and there are only one or two matches": if your data > consisted only of valid ISBNs separated by a single space or comma, it > would run much faster. It is all the quadratic/exponential mucking > about with the in-between bits that slows it down. To demonstrate > this, try timing dummy data like "1234567890 " * 1000000 and > "123456789X " * 1000000 with your various regexes, and with the step1, > step2 etc regexes above. > >> if I change this to match ".*[ ]*(\d{10}|\d{9}X)[ ]*.*" instead, I risk >> loosing results, but it runs in about 0.3 seconds >> >> So what's the deal? - why would it take so long to run the correct one? > > Because you have .*\D* in other words 0 or more occurrences of almost > anything followed by 0 or more occurrences of almost anything. Even > assuming it ignores the .*, it will find the longest possible sequence > of non-digits, then try to match the ISBN stuff. If it fails, it will > shorten that sequence of non-digits, try the ISBN stuff again, etc etc > until it matches the ISBN stuff or that sequence of non-digits is down > to zero length. It will do that for each character position in the > file contents. Why is it faster when you change \D to []? Presumably > because in your data, sequences of non-digits are longer than > sequences of spaces IOW there is less stuff to back-track over. > > >> - especially when a slight modification makes it run as fast as I'd >> expect from the beginning... >> >> I'm sorry I cannot supply test data, in my case, it comes from >> copyrighted material - however if it proves needed, I can probably >> construct dummy data to illustrate the problem > > What you call "dummy data", I'd call "test data". You should make a > sample of "dummy data" and test that your regex is (a) finding all > ISBNs that it should (b) not reporting incorrect matches, *BEFORE* > being concerned with speed. > >> Any and all guidance would be greatly appreciated, > > For some light reading :-) borrow a copy of Friedl's book (mentioned > in the Python re docs) and read the parts on how backtracking regex > engines work. > > HTH, > John > Thanks to all of you for your replies - they have been most helpful, and my program is now running at a reasonable pace... I ended up using r"\b\d{9}[0-9X]\b" which seems to do the trick - if it turns out to misbehave in further testing, I'll know where to turn :-P From silovana.vjeverica at com.gmail Sat Feb 3 11:27:47 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Sat, 3 Feb 2007 17:27:47 +0100 Subject: Jython References: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> Message-ID: gregturn at mindspring.com wrote: > Files aren't lists and thus don't have the functions for iteration. They do have iterator: C:\Documents and Settings\Silovana Vjeverica\Desktop>python FileReader.py 'import site' failed; use -v for traceback boris ozegovic vedran ozegovic -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" From rds1226 at sh163.net Thu Feb 22 13:23:03 2007 From: rds1226 at sh163.net (John) Date: Thu, 22 Feb 2007 13:23:03 -0500 Subject: How to covert ASCII to integer in Python? References: Message-ID: I just found ord(c), which convert ascii to integer. Anybody know what the reverse is? "John" wrote in message news:erkknl$6d4p$1 at netnews.upenn.edu... > Is there any built in function that converts ASCII to integer or vice versa > in Python? > > Thanks! > > From duncan.booth at invalid.invalid Mon Feb 26 06:49:34 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Feb 2007 11:49:34 GMT Subject: Help on object scope? References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> <1172440275.868863.91120@k78g2000cwa.googlegroups.com> <54eg90F1vupsiU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > You can interact just fine, just qualify the objects with the module > names. So in q, you need to use p.r instead of just r. No. When p.py is being run as a script, the module you need to access is __main__. Much better to put the globals into a separate module created specifically to hold the global variables rather than having them in something which might or might not be the main script. From andrewm at object-craft.com.au Wed Feb 21 03:28:30 2007 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 21 Feb 2007 19:28:30 +1100 Subject: BDFL in wikipedia In-Reply-To: Your message of "Tue, 20 Feb 2007 22:27:54 EDT." <32822fe60702201827k36f8bd53k69908869a19f00e6@mail.gmail.com> Message-ID: <20070221082830.31BD26F4CF3@longblack.object-craft.com.au> >Hi I just hit this page in wikipedia BDFL[1] > >and it redirected me to Guido's wikipedia[2] entry >now without causing any troubles (read flamewar) shouldn't > >a) that page have an explanation of what BDFL is >b) shouldn't it mention Linus, Larry Wall, others?[3] >c) for the ones that have been around longer then me who was the first >being call like that? > >[1] http://en.wikipedia.org/wiki/BDFL >[2] http://en.wikipedia.org/wiki/Guido_van_Rossum >[3] http://www.answers.com/topic/list-of-benevolent-dictators-for-life I'm sure you'll get 101 people telling you this, but this really isn't a question for the python list, rather, it's a question for the Wikipedia editors (and that's anyone). I suspect, in this case, the redirect is implicit. It's happening because the Wikipedia search engine finds no page called BDFL, and the Guido_van_Rossum is the next closest match. If you care and you have enough to say on the subject, maybe you could start a BDFL page. -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From stj911 at rock.com Wed Feb 28 14:33:41 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 28 Feb 2007 11:33:41 -0800 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** In-Reply-To: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> References: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Message-ID: <1172691221.804701.255140@s48g2000cws.googlegroups.com> Top Ten Reasons Why Activists Shouldn't Be "Too Radical" 1. We must be careful not to offend the Average American (AvAm) 2. Self-righteousness is such a turn-off 3. We can't give ammunition to the right wing 4. The AvAm is doing the best he/she can and we shouldn't expect more 5. We can't blame the AvAm because she/he just doesn't know better 6. The AvAm will learn at his/her own pace 7. It's not our place to judge 8. Besides, it's not the AvAm's fault; the Republicans are to blame 9. The AvAm may be indifferent (at best) to reality...but they are still "the people" On Feb 24, 8:22 am, stj... at rock.com wrote: > Canada anti-terror law is struck down>From the Associated Press > > February 24, 2007 > > OTTAWA - Canada's Supreme Court on Friday unanimously declared it > unconstitutional to detain foreign terrorism suspects indefinitely > while the courts review their deportation orders. > > Five Arab Muslim men have been held for years under the "security > certificate" program, which the Justice Department has said is a key > tool in the fight against global terrorism and essential to Canada's > security. > > The court found that the system violated the Charter of Rights and > Freedoms, Canada's bill of rights. However, it suspended its ruling > for a year to give Parliament time to rewrite the part of the > Immigration and Refugee Protection Act that covers the certificate > process. > > The security certificates were challenged by three men from Morocco, > Syria and Algeria - all alleged by the Canadian Security Intelligence > Service to have ties to terrorist networks. > > The men have spent years in jail while fighting deportation orders. > > They risk being labeled terrorists and sent back to their native > countries, where they say they could face torture. > > The court said the treatment of the suspects was a violation of their > rights. > > "The overarching principle of fundamental justice that applies here is > this: Before the state can detain people for significant periods of > time, it must accord them a fair judicial process," Chief Justice > Beverley McLachlin wrote in a ruling for all nine justices. > > "The secrecy required by the scheme denies the person named in a > certificate the opportunity to know the case put against him or her, > and hence to challenge the government's case," she said. > > The challenged law allows sensitive intelligence to be heard behind > closed doors by a federal judge, with only sketchy summaries given to > defense attorneys. > > The court said the men and their lawyers should have a right to > respond to the evidence used against them by intelligence agents. > > Stockwell Day, the minister of public safety, noted that because the > ruling does not take effect for a year, the certificates would remain > in place. He said the government would address the court's ruling "in > a timely and decisive fashion." > > Two of the men are out on bail and remain under house arrest. Three > others are being held in a federal facility in Ontario. From laurent.pointal at wanadoo.fr Tue Feb 20 13:18:05 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Tue, 20 Feb 2007 19:18:05 +0100 Subject: ocaml to python References: Message-ID: <45db3a74$0$27372$ba4acef3@news.orange.fr> Gigs_ wrote: > Is there any way to convert ocaml code to python? but not manually For Python and ocaml, my bookmark contains this link: http://www.programs4all.net/programs/Pycaml-Python-Embedding-API-for-Ocaml.htm But no ocaml to Python compiler... From wattersmt at gmail.com Tue Feb 6 10:37:33 2007 From: wattersmt at gmail.com (wattersmt at gmail.com) Date: 6 Feb 2007 07:37:33 -0800 Subject: Running long script in the background In-Reply-To: <1170769014.352466.135280@h3g2000cwc.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170769014.352466.135280@h3g2000cwc.googlegroups.com> Message-ID: <1170776253.027044.253050@q2g2000cwa.googlegroups.com> On Feb 6, 8:36 am, "jasonmc" wrote: > > Does anybody know a way to make output show in real time? > > You can put: #!/usr/bin/python -u > at the top of the script to have unbuffered binary stdout and stderr. Thanks. I tried that but it still times out waiting for output. Everything works fine until I call the popen function, then it freezes. What I want is to print the output in real time, just like it does when I run it from a shell. From paul at boddie.org.uk Sun Feb 4 17:32:58 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Feb 2007 14:32:58 -0800 Subject: Python does not play well with others In-Reply-To: <1170625204.156763.178460@j27g2000cwj.googlegroups.com> References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> Message-ID: <1170628378.035778.116610@a75g2000cwd.googlegroups.com> Graham Dumpleton wrote: > > Having said all that, perhaps those who are complaining about lack of > support for specific features in mod_python can now clarify what > actually you are talking about. At the moment the brief comments being > made seem to possibly cover some things that mod_python can already do > but may not be obvious. I had a more complete response to this before Google Groups and my browser went into "stupid mode" together, but I'd like to say that I don't have any complaints about mod_python, but I know that there were people who claimed [1] that PHP had its "safe mode" [2] which gave isolation to applications belonging to different users in the same Apache instance, asserting that mod_python not having that particular feature prevented wider adoption of Python in the hosting business. It's good to see a clarification of mod_python and its position in relation to such issues, though. I don't really share the concerns mentioned, and wouldn't want to be using or providing services of the kind previously discussed, anyway. Instead, I'd want to deploy applications using other techniques such as virtualisation, rather than throwing customers into the same Web server and, apparently in the case of PHP, relying on hearsay about whether they can interfere with each other. I note that the creator of mod_python seems to have a similar perspective on virtualisation, given the nature of his hosting company's services. Paul [1] http://groups.google.com/group/comp.lang.python/msg/ 469dd47f5c1ad521 [2] http://no.php.net/features.safe-mode From rune.strand at gmail.com Sat Feb 24 21:20:15 2007 From: rune.strand at gmail.com (Rune Strand) Date: 24 Feb 2007 18:20:15 -0800 Subject: Referencing Items in a List of Tuples In-Reply-To: References: Message-ID: <1172370015.018827.296720@q2g2000cwa.googlegroups.com> On Feb 25, 3:01 am, rshep... at nospam.appl-ecosys.com wrote: > In my case, I have a list of 9 tuples. Each tuple has 30 items. The first > two items are 3-character strings, the remaining 28 itmes are floats. > > I want to create a new list from each tuple. But, I want the selection of > tuples, and their assignment to the new list, to be based on the values of > the first two items in each tuple. > > If I try, for example, writing: > > for item in mainlist: > if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con': > ec.Append(mainlist[item][2:]) > > python doesn't like a non-numeric index. > try this instead: for item in mainlist: if item[0] == 'eco' and item[1] == 'con': ec.append(item[2:]) if you want numeric adressing, try: for i in range(len(mainlist)): if mainlist[i][0] == 'eco' etc. From tiedon_jano at hotmail.com Sat Feb 3 06:56:39 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sat, 03 Feb 2007 11:56:39 GMT Subject: compound statement from C "?:" In-Reply-To: <1170439185.917760.135640@k78g2000cwa.googlegroups.com> References: <1170417674.656853.19930@a34g2000cwb.googlegroups.com> <1170439185.917760.135640@k78g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com kirjoitti: > Jussi Salmela: >> In this particular case you don't need the ternary operator: >> print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) > > The last newline is probably unnecessary. This seems be a bit more > readable: > print "I saw", n, "car" + ("", "s")[n != 1] > > With Python 2.5 this looks better: > print "I saw", n, "car" + ("" if n == 1 else "s") > > Or the vesion I like better: > print "I saw", n, ("car" if n == 1 else "cars") > > Those () aren't necessary, but they help improve readability, and > avoid problems with operator precedence too. That if has a quite low > precedence. > > Bye, > bearophile > This is getting weird but here's 2 more in the spirit of "who needs the ternary operator - I don't!". And I'm starting to wonder what the 'obvious way' (as in 'Zen of Python') to write this would be. print "I saw %d car%s" % (n, {1:''}.get(n==1, 's')) print "I saw %d car%s" % (n, 's'*(n!=1)) Cheers, Jussi From phil at riverbankcomputing.co.uk Wed Feb 28 04:22:20 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 28 Feb 2007 09:22:20 +0000 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <1172653246.535391.105780@a75g2000cwd.googlegroups.com> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <1172650071.878083.106290@h3g2000cwc.googlegroups.com> <1172653246.535391.105780@a75g2000cwd.googlegroups.com> Message-ID: <200702280922.21139.phil@riverbankcomputing.co.uk> On Wednesday 28 February 2007 9:00 am, boris.smirnov at gmail.com wrote: > On Feb 28, 9:07 am, boris.smir... at gmail.com wrote: > > On Feb 28, 8:56 am, Phil Thompson > > > > wrote: > > > On Tuesday 27 February 2007 11:09 pm, shredwheat wrote: > > > > When your programs stops with the error, it should also be printing a > > > > stack trace. This is a list of all the functions that have been > > > > called when Python had the problem. > > > > > > > > You shouldn't have to do anything extra to get the stack trace. > > > > > > The error is raised in Qt and aborts immediately. It never gets back to > > > Python to generate a trace. > > > > > > He needs to produce a short and complete test which demonstrates the > > > problem, then we can point out where the QPaintDevice is being created. > > > > > > Phil > > > > OK, but before I do a complete test, could anybody tell/explain me why > > the same file is working on Windows? > > Did anybody already meet with something similar Win vs. Linux? > > > > b. > > Here is my simple script: > > import sys > from qt import * > class Optimizer(QWidget): > def __init__(self, parent = 0): > QWidget.__init__(self) > QGridLayout(self) > if __name__ == '__main__': > a = QApplication (sys.argv) > mywidget = Optimizer() > a.exec_loop() > > This produces this: > > python qt_script_bs_070228.py > > QPaintDevice: Must construct a QApplication before a QPaintDevice > > Any suggestions here? It works fine for me. > Thanks > > > > BTW: One question: > when I use "import qt" instead of "from qt import *" I get this error: > Traceback (most recent call last): > File "mscarideidtool_bs_070228.py", line 4, in ? > class Optimizer(QWidget): > NameError: name 'QWidget' is not defined > > What is the difference between "import qt" and "from qt import *" ? I > thought that these are the same. The first creates a new namespace called "qt" and imports the module's objects into it. To reference those objects you have to include the namespace name. The second imports the module's objects into the current namespace. Phil From mjl8379 at u.washington.edu Mon Feb 26 20:26:05 2007 From: mjl8379 at u.washington.edu (mjl8379) Date: Mon, 26 Feb 2007 17:26:05 -0800 Subject: ArcGIS and Python Message-ID: Is there any online resource where I can check for ArcGIS scripting? Maybe a forum? Mario From stj911 at rock.com Sat Feb 3 23:56:26 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 3 Feb 2007 20:56:26 -0800 Subject: "President Bush ... you are under arrest" - 911 truth video by Dr Morgan Reynolds, Former Chief Economist under Bush Message-ID: <1170564986.884781.277460@v33g2000cwv.googlegroups.com> You can also save them by right clicking the links and saving them as flv files and download a free flv player. google is your best friend. "Bush Administration Insider Says U.S. Government Behind 911.flv" "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w" <--- key video "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http:// youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" "911 Truth, Consequences of Revealing the Truth about 911.flv" "http:// youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv" "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv" "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax- v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA" "Bush gets caught off guard on 9/11 prior knowledge question.flv" "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" "Bush gets caught off guard on 911 prior knowledge question.flv" "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM" "World Trade Center -- Controlled Demolition.flv" "http:// v187.youtube.com/get_video?video_id=87fyJ-3o2ws" "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv" "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90" From deets at nospam.web.de Sat Feb 3 22:23:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 04 Feb 2007 04:23:27 +0100 Subject: Python does not play well with others In-Reply-To: <7xy7nf1850.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> <7xk5yz2q42.fsf@ruckus.brouhaha.com> <52jt3eF1p85tbU1@mid.uni-berlin.de> <7xy7nf1850.fsf@ruckus.brouhaha.com> Message-ID: <52l1tgF1neqraU1@mid.uni-berlin.de> Paul Rubin schrieb: > "Diez B. Roggisch" writes: >> And they certainly require special treatment like putting them in the >> classpath, setting up the project directory and the like - no simple >> import will work out of the box, as it would witch python standard lib >> drivers. > > Well, that's nowhere near as big a deal as having yet another set of > vendors or maintainer to deal with. Minimizing configuration is nice, > but getting your software from as few different sources as possible is > also a big win. Ehm... .it _is_ another set of vendors and maintainers. It's just that they are standard jdbc-compliant. As the python modules are DB API 2.0 compliant - hopefully. A difference might be that most (not all) of the jdbc-drivers are java-only, and not have any c-dependencies. Well - nice to have, but simple inclusion of existing drivers doesn't remove that. Only a complete rewrite in python would. Diez From paul at boddie.org.uk Tue Feb 20 15:56:13 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Feb 2007 12:56:13 -0800 Subject: Python 3.0 unfit for serious work? In-Reply-To: References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> Message-ID: <1172004973.139495.311980@h3g2000cwc.googlegroups.com> Steven Bethard wrote: > > Well, Python 2.4 code will work on Python 2.6 and 2.7 so just because > your code isn't yet compatible with Python 3.0 doesn't mean you should > give up on Python. Perhaps the most important concern in the context of Python 3.0 is what the term "Python" will come to mean to the different communities using the language. Some people will be maintaining software that needs to be compatible with older releases; these people aren't technologically backwards: they just find that such older releases provide sufficient capabilities for the implementation of their solutions. For such people, "Python" will be the language they've always used, with a gradual accumulation of features, some known quirks, and some relatively minor incompatibility issues over the years. Meanwhile, the risk is that the core developers will only consider Python 3.0 as "Python" and that people doing anything with older releases will be on their own. If the gap is too wide between 2.x and 3.x, any lack of maintenance in the 2.x series will be perceived as an abandonment of "Python" for certain kinds of user, and the result will probably be a loss of confidence in both variants of the language. Although I believe that some of the recent attempts to lower the disruptiveness of Python 3.0 may have helped to maintain "Python" as a single narrow continuum, I think some people overlook how fortunate the relationship between Python's evolution and momentum has been, and how easily such a relationship can be broken. Paul From python at rcn.com Tue Feb 13 14:01:45 2007 From: python at rcn.com (Raymond Hettinger) Date: 13 Feb 2007 11:01:45 -0800 Subject: Fast constant functions for Py2.5's defaultdict() Message-ID: <1171393305.268249.268580@q2g2000cwa.googlegroups.com> FWIW, here are three ways of writing constant functions for collections.defaultdict(): d = defaultdict(int) # slowest way; works only for zero d = defaultdict(lambda: 0) # faster way; works for any constant d = defaultdict(itertools.repeat(0).next) # fastest way; works for any constant Another approach is to use the __missing__ method for dictionary subclasses: class zerodict (dict): def __missing__ (self, key): return 0 # fast on initial miss, but slow on non-misses; works for any constant The itertools.repeat(const).next approach wins on speed and flexibility. Raymond From http Fri Feb 16 13:28:48 2007 From: http (Paul Rubin) Date: 16 Feb 2007 10:28:48 -0800 Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> Message-ID: <7xd54a6jof.fsf@ruckus.brouhaha.com> Steven Bethard writes: > Yes, a lot of people liked this approach, but it was rejected due to > gratuitous breakage. While Python 3.0 is not afraid to break backwards > compatibility, it tries to do so only when there's a very substantial > advantage. I guess enough people felt that having a shortcut for set() > was less important than keeping the current spelling of dict() the same. There's even a sentiment in some pythonistas to get rid of the [] and {} notations for lists and dicts, using list((1,2,3)) and dict((1,2),(3,4)) for [1,2,3] and {1:2, 3:4} respectively. From tjreedy at udel.edu Wed Feb 14 22:48:06 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Feb 2007 22:48:06 -0500 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com><1171437351.206085.236450@q2g2000cwa.googlegroups.com> <1171444128.138234.50640@l53g2000cwa.googlegroups.com> Message-ID: "John Machin" wrote in message news:1171444128.138234.50640 at l53g2000cwa.googlegroups.com... || > | On Feb 14, 5:45 pm, "agent-s" wrote: | > | > btw Steven you are so witty I hope to one day pwn noobs on newsgroups | > | > too. | > | > Sorry, but you are 'pwning' yourself here ;-) | | And the referent of "you" would be .....? agent-s, as I though was obvious. From nagle at animats.com Tue Feb 13 23:07:33 2007 From: nagle at animats.com (John Nagle) Date: Wed, 14 Feb 2007 04:07:33 GMT Subject: How can this Perl regular expression be expressed in Python? Message-ID: <8WvAh.14675$O02.10228@newssvr11.news.prodigy.net> Here's a large Perl regular expression, from a Perl address parser in CPAN: use re 'eval'; $Addr_Match{street} = qr/ (?: # special case for addresses like 100 South Street (?:($Addr_Match{direct})\W+ (?{ $_{street} = $^N }) ($Addr_Match{type})\b (?{ $_{type} = $^N })) | (?:($Addr_Match{direct})\W+ (?{ $_{prefix} = $^N }))? (?: ([^,]+) (?{ $_{street} = $^N }) (?:[^\w,]+($Addr_Match{type})\b (?{ $_{type} = $^N })) (?:[^\w,]+($Addr_Match{direct})\b (?{ $_{suffix} = $^N }))? | ([^,]*\d) (?{ $_{street} = $^N }) ($Addr_Match{direct})\b (?{ $_{suffix} = $^N }) | ([^,]+?) (?{ $_{street} = $^N }) (?:[^\w,]+($Addr_Match{type})\b (?{ $_{type} = $^N }))? (?:[^\w,]+($Addr_Match{direct})\b (?{ $_{suffix} = $^N }))? ) ) /ix; I'm trying to convert this to Python. Those entries like "$(Addr_Match{direct}) are other regular expressions, being used here as subexpressions. Those have already been converted to forms like "Addr_Match.direct" in Python. But how to call them? Is that possible in Python, and if so, where is it documented? John Nagle From attn.steven.kuo at gmail.com Tue Feb 13 00:25:30 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 12 Feb 2007 21:25:30 -0800 Subject: how to compare... In-Reply-To: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> References: <1171339387.160659.298260@k78g2000cwa.googlegroups.com> Message-ID: <1171344330.766097.116720@l53g2000cwa.googlegroups.com> On Feb 12, 8:03 pm, "jairodsl" wrote: > Hello everybody ! > > I have two list, they are, S1=['A','B','C','D','E'], and > S2=['F','G','H','I','J'], but i have to compare both in this way: > > A vs J > A vs I, B vs J > A vs H, B vs I, C vs J > A vs G, B vs H, C vs I, D vs J > A vs F, B vs G, C vs H, D vs I, E vs J > B vs F, C vs G, D vs H, E vs I > C vs F, D vs G, E vs H > D vs F, E vs G > E vs F > (snipped) > Could someone give me any idea how to compare(or print) both list in > this way ??? Thanks a lot !!! > > jDSL s1 = [ 'A', 'B', 'C', 'D', 'E' ] s2 = [ 'F', 'G', 'H', 'I', 'J' ] s3 = [] for count in xrange( len(s1) + len(s2) - 1 ): try: operand = s2.pop() except IndexError: operand = None except: raise s3.insert(0,operand) print [ t for t in zip(s1, s3) if t[1] is not None ] -- Hope this helps, Steven From lance at augustmail.com Fri Feb 16 16:58:13 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Fri, 16 Feb 2007 21:58:13 GMT Subject: help with looping, re.search, multiple indexing Message-ID: Hey all, How do I add another index inside a re.search? I want to add for j in [96,97,98,99] BASE = re.search ... sh.Cells97... for i .... so that the Table 96 within the re.search(s) becomes Table 96, Table 97, Table 98, Table 99 but don't know how to add a second index within the re.search since I already have %char in match = re.search ... " %char, neuro ... VAR=[] BASE = re.search("Table 96.*?BASE.*?\d(.*?)\n", neuro, re.S ).group(1).split()[1] sh.Cells(7,lastcol+1).Value = BASE for i, char in enumerate(["RECEIVED E", "PARTICIPATED "]): match = re.search(r"Table 96.*?%s.*?\n.*?\d(.*?)\n.*?" %char , neuro, re.S ) if match: VAR = match.group(1).split()[1] else: VAR = 0 if VAR=="-": VAR = 0 VAR = even_odd_round(float(str(VAR))) VAR = float(str(VAR))/100 sh.Cells(i+8,lastcol+1).Value = VAR sh.Cells(10,lastcol+1).Value= sh.Cells(9,lastcol+1).Value sh.Cells(9,lastcol+1).Value = sh.Cells(8,lastcol+1).Value - sh.Cells(10,lastcol+1).Value VAR=[] BASE = re.search("Table 97.*?BASE.*?\d(.*?)\n", neuro, re.S ).group(1).split()[1] sh.Cells(11,lastcol+1).Value = BASE for i, char in enumerate(["RECEIVED E", "PARTICIPATED "]): match = re.search(r"Table 97.*?%s.*?\n.*?\d(.*?)\n.*?" %char , neuro, re.S ) if match: VAR = match.group(1).split()[1] else: VAR = 0 if VAR=="-": VAR = 0 VAR = even_odd_round(float(str(VAR))) VAR = float(str(VAR))/100 sh.Cells(i+12,lastcol+1).Value = VAR sh.Cells(14,lastcol+1).Value= sh.Cells(13,lastcol+1).Value sh.Cells(13,lastcol+1).Value = sh.Cells(12,lastcol+1).Value - sh.Cells(14,lastcol+1).Value From marco at waven.com Thu Feb 8 10:08:18 2007 From: marco at waven.com (Marco) Date: Thu, 8 Feb 2007 23:08:18 +0800 Subject: Linux-Signal VS QT Message-ID: <5c62a320702080708v19f9d5ke3707167c326f7c1@mail.gmail.com> Can I use LinuX signal as a tool for commuction with a QT(PyQt4) programme? The follow code didNOT work... from PyQt4 import QtCore,QtGui import signal import sys import os try: import psyco psyco.full() except: pass class Main(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.frame = QtGui.QFrame(self) self.label = QtGui.QLabel(str(os.getpid()), self.frame) signal.signal(15, self.sig_handler) print signal.getsignal(15) def sig_handler(self, signum, sframe): print 'received!' self.label.setText('haha') self.show() ######################## # main routine # ######################## if __name__ == '__main__': app = QtGui.QApplication(sys.argv) main = Main() main.show() app.exec_() -- LinuX Power From irmen.NOSPAM at xs4all.nl Thu Feb 22 13:20:02 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 22 Feb 2007 19:20:02 +0100 Subject: Possible to set cpython heap size? In-Reply-To: <1172166768.967422.225960@p10g2000cwp.googlegroups.com> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> <5462tbF1vfhfrU1@mid.uni-berlin.de> <1172166768.967422.225960@p10g2000cwp.googlegroups.com> Message-ID: <45ddded2$0$335$e4fe514c@news.xs4all.nl> Andy Watson wrote: > > Why do you want that? And no, it is not possible. And to be honest: > I have >> no idea why e.g. the JVM allows for this. >> >> Diez > > The reason why is simply that I know roughly how much memory I'm going > to need, and cpython seems to be taking a fair amount of time ^^^^^ > extending its heap as I read in content incrementally. First make sure this is really the case. It may be that you are just using an inefficient algorithm. In my experience allocating extra heap memory is hardly ever noticeable. Unless your system is out of physical RAM and has to swap. --Irmen From gagsl-py at yahoo.com.ar Wed Feb 21 01:22:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Feb 2007 03:22:43 -0300 Subject: setup.py installation and module search path References: <1172010954.151670.274470@p10g2000cwp.googlegroups.com> <4OGdnbwDvckpGkbYnZ2dnUVZ_qninZ2d@comcast.com> <1172015773.217480.302840@v33g2000cwv.googlegroups.com> Message-ID: En Tue, 20 Feb 2007 20:56:13 -0300, Russ escribi?: >> I'm no expert, but I think what normally happens is the module gets >> installed into ../pythonxx/lib/site-packages/ and if it >> installs __init__.py file there they get automatically searched. >> At least that the way things work for me. > > But if I don't have root priviledge, that doesn't happen. Is there a > setup.py option to get a > package installed just in my own account in such a way that my module > search path gets > updated? Use the --home option (or --prefix). You may need to set the PYTHONPATH environment variable to ~/lib/python -- Gabriel Genellina From boris.smirnov at gmail.com Tue Feb 27 15:56:47 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 27 Feb 2007 12:56:47 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <1172602497.566766.79250@p10g2000cwp.googlegroups.com> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> <1172573562.215310.76760@8g2000cwh.googlegroups.com> <54ih3nF2143jeU2@mid.uni-berlin.de> <1172574041.569357.127440@q2g2000cwa.googlegroups.com> <54ijbdF1urdo2U1@mid.uni-berlin.de> <1172602497.566766.79250@p10g2000cwp.googlegroups.com> Message-ID: <1172609807.109748.93170@8g2000cwh.googlegroups.com> shredwheat nap?sal(a): > On Feb 27, 3:35 am, "Diez B. Roggisch" wrote: > > I don't see any QPaintDevice here. Where does that come from? You need to > > give more information, a stack trace and a reduced example exhibiting the > > behaviour. > > QWidget is derived from QPaintDevice, under Qt, no widgets can be > instantiated before the QApplication. > > This source snippet looks like it should be working. If the exception > is happening inside Optimizer() than something really unsusual is > happening. I suspect there is python code somewhere else happening at > import time that is creating a widget. The exception traceback should > show you right where that would be. Thanks for the reply. I'm not so familiar with python so could you explain me how to use and become the exception traceback. I've tried today to read something for the beginners about traceback and stack trace in the forum, but I haven't found something really understadable for met. Some piece of code for my case will help :) and I want to learn it of course. Thanks. Boris From dimitri.pater at gmail.com Sat Feb 10 19:58:21 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Sun, 11 Feb 2007 01:58:21 +0100 Subject: Regular Expressions In-Reply-To: <7xfy9da8w3.fsf@ruckus.brouhaha.com> References: <7xfy9da8w3.fsf@ruckus.brouhaha.com> Message-ID: Hi, a good start: http://diveintopython.org/regular_expressions/index.html On 10 Feb 2007 15:30:04 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > > "Geoff Hill" writes: > > What's the way to go about learning Python's regular expressions? I feel > > like such an idiot - being so strong in a programming language but > knowing > > nothing about RE. > > Read the documentation? > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Feb 1 08:22:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Feb 2007 14:22:26 +0100 Subject: newbie question: nested archives and zipfile References: <1170335585.254930.210140@k78g2000cwa.googlegroups.com> Message-ID: <52e7siF1oltd8U1@mid.uni-berlin.de> gilbeert at gmail.com wrote: > I sorry, but I'm not very familiar with Python. > Please, help to solve my problem with reading file from "nested" zip > archive. > There is an ear_file.ear and inside this file there is a war_file.war > and inside this file there is a jar_file.jar. > I have to read content of a file (my_file.txt) from inside a > jar_file.jar: > ear_file.ear > war_file.war > jar_file.jar > my_file.txt > > Is it possible to directly read my_file.txt from inside this kind of > nested archive? > Please, give an example how to do that. No. > Do I have to open ear_file.ear, read war_file.war, write it to file > and then open writed war_file.war, read jar_file.jar, write it to > file > and then open wreted jar_file.jar and read my_file.txt?? Yes. Depending on the size of the files, it might be possible to use StringIO to keep the files in-memory without using temp-files. Diez From martin at browns-nospam.co.uk Wed Feb 28 06:01:25 2007 From: martin at browns-nospam.co.uk (Martin Evans) Date: Wed, 28 Feb 2007 11:01:25 -0000 Subject: py2exe, library.zip and python.exe Message-ID: I have converted a Python script using py2exe and have it set to not bundle or compress. The result is my exe and all the support files including library.zip (exactly as planned - nice job py2exe). Question: My py2exe application needs to be able to execute extra copies of python.exe. I have placed python.exe in the same directory. It obviously picks up the main python24.dll but how can I configure things so that it would use the same library.zip for all the library files? This would save me having two sets of files. (The py2exe application happens to be a twisted server app running as a service which has the ability to launch python scripts as a logged on user) Thanks, Martin. From bj_666 at gmx.net Tue Feb 27 01:17:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 27 Feb 2007 07:17:04 +0100 Subject: classobj? References: <1172542760.288738.72550@8g2000cwh.googlegroups.com> Message-ID: In , Venky wrote: >> Do you mean that you want to add it to globals()? >> >> globals()['SomeClass'] = cl >> >> myinst = SomeClass() >> print isinstance(myinst, SomeClass) >> print isinstance(myinst, BaseClass) >> > > Thanks. That's what I was looking for. Probably not because now you have to know the name when you write the static source code. You said the names are discovered at runtime, so how do you know it's `SomeClass`? Put you classes into a dictionary with the name as key. `globals()` is a dictionary too, but it is more work to get an object by name from it (globals()['SomeClass'] vs. some_dict['SomeClass']) and you don't risk that some of your dynamically created classes overwrites an existing one with the same name. Ciao, Marc 'BlackJack' Rintsch From jjl at pobox.com Fri Feb 23 16:35:52 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 23 Feb 2007 21:35:52 GMT Subject: BDFL in wikipedia References: <1172053544.515756.28200@v45g2000cwv.googlegroups.com> Message-ID: <87zm74y2ti.fsf@pobox.com> Robin Becker writes: > Carl Banks wrote: > ...... > > Since when is Larry Wall benevolent? He should be called the SDFL. > > > ..... > > even the great leader has been referred to as the MDFL :) [...] By you?-) John From __peter__ at web.de Mon Feb 19 05:07:08 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Feb 2007 11:07:08 +0100 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> Message-ID: Jay Tee wrote: > Hi, > > I have some code that does, essentially, the following: > > - gather information on tens of thousands of items (in this case, jobs > running on a > compute cluster) > - store the information as a list (one per job) of Job items > (essentially wrapped > dictionaries mapping attribute names to values) > > and then does some computations on the data. One of the things the > code needs to do, very often, is troll through the list and find jobs > of a certain class: > > for j in jobs: > if (j.get('user') == 'jeff' and j.get('state')=='running') : > do_something() > > This operation is ultimately the limiting factor in the performance. > What I would like to try, if it is possible, is instead do something > like this: > > if j.subset_attr({'user' : 'jeff', 'state' : 'running'}) : > do_something() > > > where subset_attr would see if the dict passed in was a subset of the > underlying attribute dict of j: > > j1's dict : { 'user' : 'jeff', 'start' : 43, 'queue' : 'qlong', > 'state' : 'running' } > j2's dict : { 'user' : 'jeff', 'start' : 57, 'queue' : 'qlong', > 'state' : 'queued' } > > so in the second snippet, if j was j1 then subset_attr would return > true, for j2 the answer would be false (because of the 'state' value > not being the same). > > Any suggestions? Constraint : the answer has to work for both python > 2.2 and 2.3 (and preferably all pythons after that). Use a RDBMS (a database), they tend to be good at this kind of operations. Peter From fperez.net at gmail.com Wed Feb 28 19:22:00 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 28 Feb 2007 17:22:00 -0700 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> <1172273227.863743.155210@p10g2000cwp.googlegroups.com> <1172432910.457442.232480@s48g2000cws.googlegroups.com> <1172516522.491585.117160@a75g2000cwd.googlegroups.com> Message-ID: aleaxit at gmail.com wrote: > On Feb 25, 3:09 pm, Fernando Perez wrote: >> Alex, have you had a look at SAGE? >> >> http://modular.math.washington.edu/sage/ >> >> it uses GMP extensively, so they've had to patch it to work around these >> issues. You can look at the SAGE release (they package everything as the >> original tarball + patches) for the GMP-specific stuff you need, though I >> suspect you'll still want to play with SAGE a little bit :). It's a >> mighty impressive system. > > Thanks Fernando, I will take a look at that. Just to save you a bit of time, if you unpack the source tarball, inside the distro you'll find a bunch of .spkg files. Those are really .tar.bz2 files for each included package, containing the original plus any SAGE patches and some install-related scripts. The GMP .spkg has all the OSX patches, plus a few more. Cheers, f From yinglcs at gmail.com Mon Feb 26 23:09:38 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 26 Feb 2007 20:09:38 -0800 Subject: How to use cmp() function to compare 2 files? Message-ID: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> Hi, i have 2 files which are different (1 line difference): $ diff groupresult20070226190027.xml groupresult20070226190027-2.xml 5c5 < x:22 y:516 w:740 h:120 area: --- > x:22 y:516 w:740 h:1202 area: But when I use the cmp() function to compare 2 files, it return "1", $ python Python 2.4.3 (#1, Oct 23 2006, 14:19:47) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> cmp("groupresult20070226190027.xml", "groupresult20070226190027-2.xml") 1 Can you please tell me why? And how can I compare the content of 2 files in python? From ironfroggy at gmail.com Wed Feb 7 11:28:38 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 7 Feb 2007 11:28:38 -0500 Subject: Object type check In-Reply-To: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> References: <1170865075.724236.20080@h3g2000cwc.googlegroups.com> Message-ID: <76fd5acf0702070828i718a0b8bjae1efb22ba3c2f27@mail.gmail.com> The answer is to do nothing at all. Use the interfaces of the objects that you expect. Treat them like numbers if you expect them to be, or stirngs, or iterables. Call methods and access attributes you expect to be there. If the caller passes sometihng bad, and something doesn't work, they'll find out about it and consult your documentation to see what they did wrong. Dont restrict them to particular types. You would not restrict them to a particular class in C#. Instead, you define the interfaces simply by how you use the objects. This is called duck typing (http://en.wikipedia.org/wiki/Duck_typing) which states "If it walks like a duck and it quacks like a duck, it must be a duck." In the end, isn't that what matters to you? Not the type or defined interfaces of an object, but that it does what you expect. On 7 Feb 2007 08:17:55 -0800, king kikapu wrote: > Hi to all, > > in statically-types languages, let's say C# for example, we use > polymorphism through interfaces. So we define an interface I with > method M and then a class C that implements I interface and write code > for the M method. > So, if we have a function that takes a parameter of type I, we know > before-hand that it will have an M method to call. > > But in dynamic languages this is not the case and we can pass whatever > we want to that function. Assuming that someone writes a library in > Python that other programmers will use, what is the correct way to > check inside that function if the parameter passed is of the correct > type, maybe "isinstance" BIF ? > > Thanks in advance! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From aspineux at gmail.com Thu Feb 1 17:28:17 2007 From: aspineux at gmail.com (aspineux) Date: 1 Feb 2007 14:28:17 -0800 Subject: imaplib : error reporting use 'randomly' exception or return value Message-ID: <1170368897.603190.68750@v45g2000cwv.googlegroups.com> imaplib use exception to report errors, but some problems must be detected by checking the return value ! For example, when trying to append into a mailbox with wrong ACL, imaplib return 'NO', but dont raise any exception (I give a sample at the end). This make error handling more complicate, because any imap statement is supposed to be followed by a test of the returned value! Why not report all problems using exceptions ? It easy to modify imaplib.py to manage this because most of the imap call are made through function _simple_command this way : def _simple_command(self, name, *args): return self._command_complete(name, self._command(name, *args)) I propose to replace it by something like : def _simple_command(self, name, *args): typ, dat=self._command_complete(name, self._command(name, *args)) if typ!='OK': raise self.error(dat[-1]) return typ, dat Any comment ? Here is an example, append on a mailbox with the wrong ACL fail by returning a 'NO' import imaplib server='localhost' login='test at asxnet.loc' passwd='password' c=imaplib.IMAP4(server) c.login(login, passwd) c.setacl('INBOX', login, '') # set wrong ACL, removing 'i' typ, dat=c.append('INBOX', None, None, "From: foo at bar.com\nTo: %s \nSubject: test append\n\nHello\n" % (login)) print typ, dat output: NO ['Permission denied'] From irmen.NOSPAM at xs4all.nl Mon Feb 12 16:37:24 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 12 Feb 2007 22:37:24 +0100 Subject: ANN: Pyro 3.6 beta released Message-ID: <45d0de3e$0$327$e4fe514c@news.xs4all.nl> It is with great pleasure that I announce that the release of a beta version of Pyro 3.6-- the greatest Pyro release yet! "What is Pyro?" "Pyro is short for PYthon Remote Objects. It is an advanced and powerful Distributed Object Technology system written entirely in Python, that is designed to be very easy to use. Never worry about writing network communication code again." Go to Pyro's Sourceforge download page to get it, and please give it a good testing. It would be great to hear of any issues or problems you encounter, before putting out the final 3.6 release. Pyro has been a Sourceforge project for over 6 years now. http://pyro.sourceforge.net http://sourceforge.net/projects/pyro I have made a HUGE amount of improvements and fixes since the previous version, 3.5, which was released about 14 months ago (sorry!). If you want to review what has been done, read the 'changes' chapter in the manual, and/or visit Pyro's "todo" wiki page: http://www.razorvine.net/python/PyroTodoList Thanks for your support, and I'm looking forward to release a final Pyro-3.6 version soon ! Sincerely, --Irmen de Jong PS: Sourceforge's shell access is down at the moment so I can't update the Pyro web page itself yet. From ptmcg at austin.rr.com Sun Feb 18 02:08:52 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 Feb 2007 23:08:52 -0800 Subject: Help Parsing XML Namespaces with BeautifulSoup In-Reply-To: <1171760115.450909.65550@q2g2000cwa.googlegroups.com> References: <1171760115.450909.65550@q2g2000cwa.googlegroups.com> Message-ID: <1171782532.851886.73780@v33g2000cwv.googlegroups.com> On Feb 17, 6:55 pm, "snewma... at gmail.com" wrote: > I'm trying to parse out some XML nodes with namespaces using > BeautifulSoup. I can't seem to get the syntax correct. It doesn't like > the colon in the tag name, and I'm not sure how to refer to that tag. > > I'm trying to get the attributes of this tag: > > text="Partly Cloudy/Wind" code="24"> > > The only way I've been able to get it is by doing a findAll with > regex. Is there a better way? > > ---------- > > from BeautifulSoup import BeautifulStoneSoup > import urllib2 > > url = 'http://weather.yahooapis.com/forecastrss?p=33609' > page = urllib2.urlopen(url) > soup = BeautifulStoneSoup(page) > > print soup['yweather:forecast'] > > ---------- If you are just trying to extract a single particular tag, pyparsing can do this pretty readily, and the results returned make it very easy to pick out the tag attribute values. -- Paul from pyparsing import makeHTMLTags import urllib2 url = 'http://weather.yahooapis.com/forecastrss?p=78732' page = urllib2.urlopen(url) html = page.read() page.close() forecastTag = makeHTMLTags('yweather:forecast')[0] for fc in forecastTag.searchString(html): print fc.asList() print "Date: %(date)s, hi:%(high)s lo:%(low)s" % fc print Prints: ['yweather:forecast', ['day', 'Sat'], ['date', '17 Feb 2007'], ['low', '34'], ['high', '67'], ['text', 'Clear'], ['code', '31'], True] Date: 17 Feb 2007, hi:67 lo:34 ['yweather:forecast', ['day', 'Sun'], ['date', '18 Feb 2007'], ['low', '42'], ['high', '65'], ['text', 'Sunny'], ['code', '32'], True] Date: 18 Feb 2007, hi:65 lo:42 From eric_brunel at despammed.com Mon Feb 12 06:03:30 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 12 Feb 2007 12:03:30 +0100 Subject: Tkinter and Tile References: Message-ID: On Mon, 12 Feb 2007 09:24:20 +0100, Ben Finney wrote: > Howdy all, > > Python programmers looking for a built-in GUI toolkit are told two > things: one, Python already comes with a GUI toolkit, and two, it > looks equally ugly on all platforms. This is because the Tk widget > library, that Tkinter uses, defaults to looking like Motif, which > hasn't been the default widget set of *anything* for a long time. > > The Tk folks are apparently getting their act together. Tile is a > "theming engine" for Tk with widgets that look and act native:: > > > > Tile is included with Tcl/Tk 8.5 and Tcl developers, at least, are > encouraged to migrate to using it:: > > > > What effect will this have on Python's Tkinter? Is it possible we can > soon expect that the long-time, but much-neglected, built-in GUI > module for Python can take advantage of this and provide widgets that > look and act like the native GUI on Unix, Windows and MacOS? FYI, changes done in tcl/tk are usually quite rapidly integrated in Tkinter. For example, for the "panedwindow" widget, introduced in tk8.4 (first version out in the end of 2002), a Tkinter wrapper was available in Python 2.3 (first version out mid-2003). So I don't doubt that the Tile extension package will be integrated in Tkinter, as soon as it is available in an official tcl/tk release. Note also that there is already an "unofficial" Tkinter wrappers set for the Tile widgets, done by Kevin Walzer. See: https://sourceforge.net/project/showfiles.php?group_id=165637 (package tkinter-wrapper) I personnally will surely use this package. Not only does it provide a native and more pleasing to the eye appearence, but it also finally provides widgets that are quite standard nowadays (notebook, combo-box, tree widget, ...), but that weren't available before in tk without an extension package. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From rcmonroig at yahoo.com Thu Feb 8 01:55:12 2007 From: rcmonroig at yahoo.com (Ron Monroig) Date: Wed, 7 Feb 2007 22:55:12 -0800 (PST) Subject: PyQt install problem Message-ID: <645958.16918.qm@web53607.mail.yahoo.com> hi Bruce, I was trying to interpret the code you wrote for xroot.sh. I saw it on pg 115 in Sitepoint's "Run Your Own Web Server Using Linux & Apache" Could you possibly consider commenting on what each line of code is doing? It works; the warning message goes away. I just don't understand what its doing. here it is: if [ $# -lt 1 ] then echo "usage: 'basename $0' command" >$2 exit 2 fi su - -c "exec env DISPLAY='$DISPLAY' \ XAUTHORITY= ' ${XAUTHORITY - $HOME/ .Xauthority}' " ' "$SHELL" ' " -c '$*'" --------------------------------- Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rridge at csclub.uwaterloo.ca Mon Feb 12 09:21:39 2007 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 12 Feb 2007 06:21:39 -0800 Subject: Help with Optimization of Python software: real-time audio controller In-Reply-To: <7x1wkw6mbl.fsf@ruckus.brouhaha.com> References: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> <7x1wkw6mbl.fsf@ruckus.brouhaha.com> Message-ID: <1171290098.998292.228980@v45g2000cwv.googlegroups.com> Paul Rubin wrote: > I think you can't really do that, not just because of Python but also > as a result of using a multitasking OS that's not especially designed > for real time. You have to rely on some buffering in the audio > hardware, so you don't have to be sample-accurate with the timings. For his application you don't need "sample-accurate" timings. Between MIDI and synthesizer latency a few milliseconds of delay are inherent in what he's trying to do, regardless of operatings system, and a latency of 20 milliseconds or more is probably acceptable. Assuming he's not trying to write his own synthesizer, he might just be able to write his application in Python under Mac OS X. Ross Ridge From wuwei23 at gmail.com Wed Feb 7 20:22:02 2007 From: wuwei23 at gmail.com (alex23) Date: 7 Feb 2007 17:22:02 -0800 Subject: Threading in Python In-Reply-To: <1170897139.167289.239010@v45g2000cwv.googlegroups.com> References: <1170815802.600716.295960@l53g2000cwa.googlegroups.com> <1170897139.167289.239010@v45g2000cwv.googlegroups.com> Message-ID: <1170897722.874388.162420@l53g2000cwa.googlegroups.com> Also, MYMPI: http://peloton.sdsc.edu/~tkaiser/mympi/ PyMPI: http://sourceforge.net/projects/pympi PyPar: http://datamining.anu.edu.au/~ole/pypar/ parallel: http://cheeseshop.python.org/pypi/parallel/0.2.3 Hopefully something here is of use to you :) - alex23 From jura.grozni at gmail.com Sun Feb 11 16:01:06 2007 From: jura.grozni at gmail.com (azrael) Date: 11 Feb 2007 13:01:06 -0800 Subject: help please!! In-Reply-To: References: <1171222845.396832.120270@l53g2000cwa.googlegroups.com> Message-ID: <1171227666.065046.258220@v33g2000cwv.googlegroups.com> Hey yo kiddie, I hope that you are using the web for some time. So you can get the meaning from my post.: LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, my stomach hurts From danb_83 at yahoo.com Mon Feb 26 23:22:16 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Feb 2007 20:22:16 -0800 Subject: How to use cmp() function to compare 2 files? In-Reply-To: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> References: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> Message-ID: <1172550136.069527.103600@t69g2000cwt.googlegroups.com> On Feb 26, 10:09 pm, "ying... at gmail.com" wrote: > Hi, > > i have 2 files which are different (1 line difference): > $ diff groupresult20070226190027.xml groupresult20070226190027-2.xml > 5c5 > < x:22 y:516 w:740 h:120 area: > --- > > > x:22 y:516 w:740 h:1202 area: > > But when I use the cmp() function to compare 2 files, it return "1", > > $ python Python 2.4.3 (#1, Oct 23 2006, 14:19:47) > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> cmp("groupresult20070226190027.xml", "groupresult20070226190027-2.xml") > > 1 > > Can you please tell me why? Because '.' > '-' (character 25 of each string). But this is comparing the filenames, which isn't what you want to do. > And how can I compare the content of 2 > files in python? Use the difflib module. From deets at nospam.web.de Thu Feb 8 09:56:30 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Feb 2007 15:56:30 +0100 Subject: help on packet format for tcp/ip programming References: <1170897917.839212.167980@l53g2000cwa.googlegroups.com> <52vdh6F1qp2n6U1@mid.individual.net> <1170904453.625206.54970@l53g2000cwa.googlegroups.com> <12sl6tuhkla8ob2@corp.supernews.com> <1170944844.977214.57350@s48g2000cws.googlegroups.com> Message-ID: <530s0uF1q8kfsU1@mid.uni-berlin.de> rattan at cps.cmich.edu wrote: > On Feb 8, 3:40 am, Grant Edwards wrote: >> On 2007-02-08, rat... at cps.cmich.edu wrote: >> >> > struct module pack and unpack will only work for fixed size buffer : >> > pack('>1024sIL', buffer, count. offset) but the buffer size can vary >> > from one packet to the next :-( >> >> Oh for Pete's sake... >> >> struct.pack('>%dsIL' % len(buffer), buffer, count, offset) >> >> -- >> Grant Edwards grante Yow! I want the >> presidency >> at so bad I can already >> taste >> visi.com the hors d'oeuvres. > > that is great but how does one unpack on the other side? By peeking into the header, determining the number of bytes necessary? But why do you need this anyway - if you know that you will have python on both ends, use Pyro or xmlrpc. Diez From rschroev_nospam_ml at fastmail.fm Fri Feb 16 20:31:13 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 17 Feb 2007 01:31:13 GMT Subject: why I don't like range/xrange In-Reply-To: <45d61e34$0$29759$426a74cc@news.free.fr> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <45d61e34$0$29759$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers schreef: > stdazi a ?crit : >> for (i = 0 ; i < 10 ; i++) >> i = 10; > > for i in range(10): > i = 10 > > What's your point, exactly ? In the first iteration, i is set equal to 10. Then, before starting the second iteration, i is incremented to 11; then the loop condition is checked and results in false. So the loop terminates after the first iteration. So, the point is that in C you can influence the loop's behavior by modifying the loop variable, while you cannot do that in Python (at least not in a for-loop). In other words, the point is that you can't translate loops literally from C to Python. Which is nothing new, and I fail to see how that is supposed to be a disadvantage. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From eurleif at ecritters.biz Thu Feb 8 12:54:29 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 08 Feb 2007 12:54:29 -0500 Subject: begin to parse a web page not entirely downloaded In-Reply-To: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> References: <1170956520.985563.245060@v45g2000cwv.googlegroups.com> Message-ID: <45cb63d4$0$6842$4d3efbfe@news.sover.net> k0mp wrote: > Is there a way to retrieve a web page and before it is entirely > downloaded, begin to test if a specific string is present and if yes > stop the download ? > I believe that urllib.openurl(url) will retrieve the whole page before > the program goes to the next statement. Use urllib.urlopen(), but call .read() with a smallish argument, e.g.: >>> foo = urllib.urlopen('http://google.com') >>> foo.read(512) ' ... foo.read(512) will return as soon as 512 bytes have been received. You can keep caling it until it returns an empty string, indicating that there's no more data to be read. From mark.dufour at gmail.com Thu Feb 8 15:41:11 2007 From: mark.dufour at gmail.com (Mark Dufour) Date: Thu, 8 Feb 2007 21:41:11 +0100 Subject: Shed Skin Python-to-C++ Compiler In-Reply-To: <8180ef690701180449k71a7bd78k41bffc5f00973da2@mail.gmail.com> References: <8180ef690701180449k71a7bd78k41bffc5f00973da2@mail.gmail.com> Message-ID: <8180ef690702081241t3cab4f75lb0cd2d50ba338689@mail.gmail.com> Hi all, I have just released version 0.0.19 of Shed Skin, an optimizing Python-to-C++ compiler. It allows for translation of pure (unmodified), implicitly statically typed Python programs into optimized C++, and hence, highly optimized machine language. This latest release adds basic support for iterators and generators, as well as a full implementation of the random module (by converting it to C++ from a Python implementation), among other things. For more details, and a collection of 26 programs, at a total of about 7,000 lines, that work with Shed Skin (resulting in an average speedup of about 40 times over CPython and 11 times over Psyco on my computer), please visit the homepage at: http://mark.dufour.googlepages.com Thanks! Mark Dufour. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From garrickp at gmail.com Tue Feb 6 10:29:39 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 6 Feb 2007 07:29:39 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170437777.785549.214730@l53g2000cwa.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> <1170334830.137876.248230@h3g2000cwc.googlegroups.com> <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <1170437777.785549.214730@l53g2000cwa.googlegroups.com> Message-ID: <1170775779.707583.131420@k78g2000cwa.googlegroups.com> On Feb 1, 8:25 pm, "Krypto" wrote: > The correct answer as told to me by a person is > (N>>3) + ((N-7*(N>>3))>>3) > The above term always gives division by 7 Does anybody else notice that this breaks the spirit of the problem (regardless of it's accuracy)? 'N-7' uses the subtraction operator, and is thus an invalid solution for the original question. Build a recursive function, which uses two arbitrary numbers, say 1 and 100. Check each, times 7, and make sure that your target number, N, is between them. Increase or decrease your arbitrary numbers as appropriate. Now pick a random number between those two numbers, and check it. Figure out which two the answer is between, and then check a random number in that subset. Continue this, and you will drill down to the correct answer, by using only *, +, >, and <. I'll bet money that since this was a programming interview, that it wasn't a check of your knowledge of obscure formulas, but rather a check of your lateral thinking and knowledge of programming. ~G From theller at python.net Thu Feb 8 14:15:47 2007 From: theller at python.net (Thomas Heller) Date: Thu, 08 Feb 2007 20:15:47 +0100 Subject: Partial 1.0 - Partial classes for Python In-Reply-To: <1170868322.560426.149920@p10g2000cwp.googlegroups.com> References: <45C9A137.8090009@v.loewis.de> <1170861460.614883.108310@k78g2000cwa.googlegroups.com> <1170862664.972024.322260@a75g2000cwd.googlegroups.com> <1170868322.560426.149920@p10g2000cwp.googlegroups.com> Message-ID: <531b72F1pio0oU1@mid.individual.net> Ziga Seilnacht schrieb: > Thomas Heller wrote: >> >> Do you have a pointer to that post? >> > > I think that he was refering to this post: > http://mail.python.org/pipermail/python-list/2006-December/416241.html > > If you are interested in various implementations there is also this: > http://mail.python.org/pipermail/python-list/2006-August/396835.html > > and a module from PyPy: > http://mail.python.org/pipermail/python-dev/2006-July/067501.html > > which was moved to a new location: > https://codespeak.net/viewvc/pypy/dist/pypy/tool/pairtype.py?view=markup > Thanks for these links. It seems they all (including Martin's partial) implementation all use more or less the same trick (or hack ;-). I agree with most of the posters is this thread that it is confusing to spread the definition of a class over several places or files. But, there are cases where the trick come in handy - when classes are created not by class statements. In ctypes, for example, a pointer type to a ctypes type is created by calling the POINTER function which creates a new class. When you have done this, the usual way to add additional methods to the new class is by assigning them like this: from ctypes import * pointer_to_c_int = POINTER(c_int) @classmethod def from_param(cls, value): ... do something ... pointer_to_c_int.from_param = from_param IMO, using the tricky class in the recipes mentioned above, you can write instead: class pointer_to_c_int(partial, POINTER(c_int)): @classmethod def from_param(cls, value): ... do something ... Thomas From sjmachin at lexicon.net Wed Feb 28 05:50:53 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2007 02:50:53 -0800 Subject: Installing java2python (Newbie) In-Reply-To: References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172654566.960775.66080@j27g2000cwj.googlegroups.com> <1172657553.589543.176850@v33g2000cwv.googlegroups.com> Message-ID: <1172659853.133365.107140@s48g2000cws.googlegroups.com> On Feb 28, 9:39 pm, "Troy Melhase" wrote: > > Did you think I was suggesting that you write a GUI version of > > java2python? Please carefully (re)?read the documentation link that I > > gave you. The idea is that with a simple variation of your setup.py > > build comamnd, you create a Windows installer for your existing > > package, and make it available for download. Then, all the Windows > > user has to do is to double-click on it, and it guides them through > > the installation. This would save wear'n'tear on you having to try to > > explain to some newbie Windows user how to install your package. > > You're right, and what I didn't communicate was the thought process > that was between "users need an installer" and "users need a gui". I > jumped to the end and only typed that. Sorry for any confusion. I doubt that users need a GUI (but TMMV of course). No need to say sorry -- I wasn't confused :-) Cheers, john From http Tue Feb 27 21:48:50 2007 From: http (Paul Rubin) Date: 27 Feb 2007 18:48:50 -0800 Subject: Yet another unique() function... References: <1172628630.408421.271310@t69g2000cwt.googlegroups.com> Message-ID: <7x8xej80a5.fsf@ruckus.brouhaha.com> "MonkeeSage" writes: > Here's yet another take on a unique() function for sequences. It's > more terse than others I've seen and works for all the common use > cases (please report any errors on the recipe page): > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263 That looks pretty messy, and it's a quadratic time algorithm (or maybe worse) because of all the list.index and deletion operations. This version is also quadratic and passes your test suite, but might differ in some more complicated cases: def unique(seq, keepstr=True): t = type(seq) if t==str: t = (list, ''.join)[bool(keepstr)] seen = [] return t(c for c in seq if (c not in seen, seen.append(c))[0]) From nagle at animats.com Thu Feb 1 19:34:58 2007 From: nagle at animats.com (John Nagle) Date: Fri, 02 Feb 2007 00:34:58 GMT Subject: Python does not play well with others In-Reply-To: References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> Message-ID: Just a followup. I'm still trying to get Python, MySQL, MySQLdb, M2Crypto, and maybe mod_python to work on a shared hosting server. This is amazingly difficult, because of all the version incompatibility issues. Python, MySQL, MySQLdb, SWIG, OpenSSL, and gcc all have to have the right versions, and those aren't necessarily the versions shipping in some major Linux distros. From EZpublishing tech support: "To make matters worse, we can't run the newer version of openSSL on any of our current servers. It's a standard redhat rpm and redhat hasn't upgraded it. We can install it on dedicated servers, but it is too risky for other users to be installed on a shared environment." From Aplus.net tech support: "No, db connectivity with Python is not supported. Modules for Python can't be installed by request on shared hosting." And these are companies that say they support Python. Python still isn't ready for prime time in the web hosting world. John Nagle From kent at kentsjohnson.com Mon Feb 5 15:16:55 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 05 Feb 2007 20:16:55 GMT Subject: Unicode formatting for Strings In-Reply-To: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> References: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> Message-ID: robson.cozendey.rj at gmail.com wrote: > Hi, > > I?m trying desperately to tell the interpreter to put an '?' in my > string, so here is the code snippet: > > # -*- coding: utf-8 -*- > filename = u"Ataris Aqu?ticos #2.txt" > f = open(filename, 'w') > > Then I save it with Windows Notepad, in the UTF-8 format. So: > > 1) I put the "magic comment" at the start of the file > 2) I write u"" to specify my unicode string > 3) I save it in the UTF-8 format > > And even so, I get an error! > > File "Ataris Aqu?ticos #2.py", line 1 > SyntaxError: Non-ASCII character '\xff' in file Ataris Aqu?ticos #2.py > on line 1 It looks like you are saving the file in Unicode format (not utf-8) and Python is choking on the Byte Order Mark that Notepad puts at the beginning of the document. Try using an editor that will save utf-8 without a BOM, e.g. jedit or TextPad. Kent From horpner at yahoo.com Wed Feb 14 11:23:04 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 14 Feb 2007 17:23:04 +0100 Subject: rot13 in a more Pythonic style? References: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> Message-ID: On 2007-02-14, Andy Dingley wrote: > I'm trying to write rot13, but to do it in a better and more > Pythonic style than I'm currrently using. What would you > reckon to the following pretty ugly thing? How would you > improve it? In particular, I don't like the way a three-way > selection is done by nesting two binary selections. Also I > dislike stating the same algorithm twice, but can't see how to > parameterise them neatly. > > Yes, I know of .encode() and .translate(). str.translate is what I'd do. import string rot13table = string.maketrans( 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM') print 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'.translate(rot13table) > No, I don't actually need rot13 itself, it's just a convenient > substitute example for the real job-specific task. No, I don't > have to do it with lambdas, but it would be nice if the final > function was a lambda. How would it being a lambda help you? -- Neil Cerutti From steve at holdenweb.com Sun Feb 11 02:35:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 11 Feb 2007 07:35:13 +0000 Subject: pygame and python 2.5 In-Reply-To: <1171168710.785138.265650@a34g2000cwb.googlegroups.com> References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> <1171089103.528193.157800@v33g2000cwv.googlegroups.com> <1171145277.777740.179060@h3g2000cwc.googlegroups.com> <1171168710.785138.265650@a34g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Feb 10, 4:07?pm, "Ben Sizer" wrote: >> On Feb 10, 6:31 am, "mensana... at aol.com" wrote: >> >>> On Feb 9, 11:39?am, "Ben Sizer" wrote: >>>> Hopefully in the future, some of those convoluted steps will be fixed, >>>> but that requires someone putting in the effort to do so. As is often >>>> the case with Python, and indeed many open source projects, the people >>>> who are knowledgeable enough to do such things usually don't need to >>>> do them, as their setup already works just fine. >>> So you're saying the knowledgeable people's attitude >>> is "fuck everyone else as lomg as it's not MY problem"? >>> And you people complain about Microsoft. >> Am I one of "those people"? You don't exactly make it clear. > > I'm talking about the people who complain about Microsoft > making the VC6 compiler no longer legally available and > yet are so irresponsible that they use it for the latest > release. > I think you'll find those two sets are disjoint. >> But yes, there is a lot of "well, it works for me" going around. If >> you do that long enough, people stop complaining, so people wrongly >> assume there's no longer a problem. This is partly why Python has >> various warts on Windows and why the standard libraries are oddly >> biased, why configuring Linux almost always ends up involving hand- >> editing a .conf file, why the leading cross-platform multimedia >> library SDL still doesn't do hardware graphics acceleration a decade >> after such hardware became mainstream, and so on. >> >> However, the difference between the open-source people and Microsoft >> is the the open-source people aren't being paid by you for the use of >> their product, so they're not obligated in any way to help you. > > This argument has become tiresome. The Python community > wants Python to be a big fish in the big pond. That's why > they make Windows binaries available. > ? I would suggest rather that "the Python community" (by which you apparently mean the developers) hope that the fruits of their labours will be used by as wide a cross-section of computer users as possible. The goals of open source projects are not those of commercial product developers: I and others wouldn't collectively put in thousands of unpaid hours a year to make a commercial product better and protect its intellectual property, for example. >> After all, they have already given freely and generously, and if they choose >> not to give more on top of that, it's really up to them. > > Right. Get people to commit and then abandon them. Nice. > Anyone who committed to Python did so without being battered by a multi-million dollar advertising campaign. The Python Software Foundation has only recently dipped its toes in the advocacy waters, with results that are still under evaluation. And the use of the Microsoft "free" VC6 SDK was never a part of the "official" means of producing Python or its extensions, it was a community-developed solution to the lack of availability of a free VS-compatible compilation system for extension modules. I agree that there are frustrations involved with maintaining extension modules on the Windows platform without having a copy of Visual Studio (of the correct version) available. One of the reasons Python still uses an outdated version of VS is to avoid forcing people to upgrade. Any such decision will have fallout. An update is in the works for those using more recent releases, but that won't help users who don't have access to Visual Studio. >> Yes, it's >> occasionally very frustrating to the rest of us, but that's life. > > As the Kurds are well aware. > I really don't think you help your argument by trying to draw parallels between the problems of compiler non-availability and those of a population subject to random genocide. Try to keep things in perspective, please. >> The best I feel I can do is raise these things on occasion, >> on the off-chance that I manage to catch the attention of >> someone who is >> altruistic, knowledgeable, and who has some spare time on >> their hands! > > Someone who, say, solved the memory leak in the GMPY > divm() function even though he had no way of compiling > the source code? > > Just think of what such an altruistic, knowedgeable > person could do if he could use the current VC compiler > or some other legally available compiler. Your efforts would probably be far better spent trying to build a back-end for mingw or some similar system into Python's development system, to allow Python for Windows to be built on a regular rather than a one-off basis using a completely open source tool chain. The fact that the current maintainers of the Windows side of Python choose to use a commercial tool to help them isn't something I am going to try and second-guess. To do so would be to belittle efforts I would have no way of duplicating myself, and I have far too much respect for those efforts to do so. There are published ways to build extension modules for Windows using mingw, by the way - have you tried any of them? It's much harder than sniping on a newsgroup, but you earn rather more kudos. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From tinaweb at bestemselv.com Tue Feb 27 05:08:12 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 27 Feb 2007 11:08:12 +0100 Subject: HTML to dictionary Message-ID: Hi everyone, I have a small, probably trivial even, problem. I have the following HTML: > > METAR: > > ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 NOSIG >
> > short-TAF: > > ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040 >
> > long-TAF: > > ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 SNRA VV010 BECMG 2124 15012KT >
I need to make this into a dictionary like this: dictionary = {"METAR:" : "ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 NOSIG" , "short-TAF:" : "ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040" , "long-Taf:" : "ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 SNRA VV010 BECMG 2124 15012KT"} I have played around with BeautifulSoup but I'm stuck at stripping off the tags and chop it up to what I need to put in the dict. If someone can offer some hints or example to get me going I would greatly appreciate it. Thanks! Tina From jscrerar at compuserve.com Fri Feb 16 09:56:44 2007 From: jscrerar at compuserve.com (Jim) Date: 16 Feb 2007 06:56:44 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> Message-ID: <1171637804.543331.314020@m58g2000cwm.googlegroups.com> On Feb 16, 5:52 am, "Endless Story" wrote: > My last version of Python was 2.4, running smoothly on XP with path c: > \Python24 - no need even to include this path in PATH; everything > worked as it's supposed to at the command line. > > Just installed Python 2.5, after uninstalling 2.4 (and also 2.3 which > had lingered). Now if I open a shell in Windows Python is not > available! Here are the symptoms: > > - If I open a shell using "Command line here" with XP Powertools, then > enter "python" at the prompt, nothing happens. I don't get a message > that the command is not recognized, but neither do I get the Python > prompt. Instead the Windows prompt comes back. No messages, no Python, > no nothing. > > - If I go so far as to specify the full path to the Python executable, > I do get the Python prompt and Python appears to work properly - > except that I can't exit with CTRL-Z. > > - If I open a shell from the Start menu, e.g. Start > run "command", > then try entering "python", the shell simply blows up. > > What is going on here? I have uninstalled and reinstalled Python 2.5, > to no avail. I have gone so far as to specify c:\Python25 (the install > path) in my PATH variable, but this makes no difference. Right now > Python is unusable to me from the command prompt, meaning all of my > automation scripts that I run at the command line are gone too. Are you talking about the Environment Variables-->System Variable-- >path? You may want to right click on My Computer-->System Properties-- >Advanced-->Environment Variables-->System variables-->Path-->Edit. And check to see if it's there, if not then add it. Thanks, Jim From stesch at no-spoon.de Mon Feb 19 04:49:42 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Mon, 19 Feb 2007 10:49:42 +0100 Subject: Django, one more newbie question References: Message-ID: <0T3segnkI7g0Nv8%stesch@parsec.no-spoon.de> Boris Ozegovic wrote: > Umm, can somebody tell me which language is this one: >

No polls are available.

English? From grante at visi.com Thu Feb 8 17:33:13 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Feb 2007 22:33:13 -0000 Subject: Python Newbie References: <1170973096.113660.264600@l53g2000cwa.googlegroups.com> Message-ID: <12sn999gqac1sef@corp.supernews.com> On 2007-02-08, spazziam wrote: > SyntaxError: invalid syntax > File "C:\Python23\vdrop2\final py\vdrop2.py", line 123 > def INIT_HIGHS(): > ^ > SyntaxError: invalid syntax > > Why would this come up? Because the syntax is invalid. You're going to have to post more of the code if you want a better answer than that. -- Grant Edwards grante Yow! DIDI... is that a at MARTIAN name, or, are we visi.com in ISRAEL? From archaegeo at gmail.com Fri Feb 9 11:50:56 2007 From: archaegeo at gmail.com (archaegeo at gmail.com) Date: 9 Feb 2007 08:50:56 -0800 Subject: Can't import Stackless in Pythonwin Message-ID: <1171039856.077320.163610@s48g2000cws.googlegroups.com> I am getting started in Python, and I have looked on both the stackless page and python.org and cannot find the answer to what I think is a simple problem. If I start the python command line or idle, i can >>>import stackless If I start pythonwin I get the following error ...No Module named Stackless Any help? From eopadoan at altavix.com Thu Feb 15 12:14:00 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Thu, 15 Feb 2007 15:14:00 -0200 Subject: The Python interactive interpreter has no command history In-Reply-To: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> References: <1171555485.838582.38330@v45g2000cwv.googlegroups.com> Message-ID: > Hello, > > How to configure Python2.5's interactive interpreter to get command > history ? > > I always got ^[[A and ^[[B . > Are you using Ubuntu? The last comes with 2.4.x and 2.5. This only occurs on 2.5. This happens when you compile Python with libreadline installed, AFAIK. FIll a bug in the Ubuntu launchpad. You can install libreadline (and build-essential), download the 2.5 source and compile yourself. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From bobmon at gmail.com Sat Feb 24 17:25:34 2007 From: bobmon at gmail.com (bobmon) Date: 24 Feb 2007 14:25:34 -0800 Subject: newbie needs help building Python 2.5 for Fedora Core 6 Message-ID: <1172355934.549788.59820@a75g2000cwd.googlegroups.com> Hello, and please be gentle... I'm trying to build Python 2.5 on my Fedora Core 6 installation. I think I've resolved most of my problems, but "make test" reports an error for test_socket.py, shown below. I suppose my FC6 installation is missing something, but I have no idea what. Any ideas, directions, pointers would be most appreciated. ====================================================================== ERROR: testSockName (__main__.GeneralModuleTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_socket.py", line 456, in testSockName my_ip_addr = socket.gethostbyname(socket.gethostname()) gaierror: (-2, 'Name or service not known') ---------------------------------------------------------------------- Ran 66 tests in 35.478s FAILED (errors=1) Traceback (most recent call last): File "./Lib/test/test_socket.py", line 962, in test_main() File "./Lib/test/test_socket.py", line 958, in test_main test_support.run_unittest(*tests) File "/home/Installer/Python/Python-2.5/Lib/test/test_support.py", line 441, in run_uni ttest run_suite(suite, testclass) File "/home/Installer/Python/Python-2.5/Lib/test/test_support.py", line 426, in run_sui te raise TestFailed(err) test.test_support.TestFailed: Traceback (most recent call last): File "./Lib/test/test_socket.py", line 456, in testSockName my_ip_addr = socket.gethostbyname(socket.gethostname()) gaierror: (-2, 'Name or service not known') From boris.smirnov at gmail.com Tue Feb 27 05:52:42 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 27 Feb 2007 02:52:42 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice In-Reply-To: <54igh0F2143jeU1@mid.uni-berlin.de> References: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> <54igh0F2143jeU1@mid.uni-berlin.de> Message-ID: <1172573562.215310.76760@8g2000cwh.googlegroups.com> On Feb 27, 11:46 am, "Diez B. Roggisch" wrote: > boris.smir... at gmail.com wrote: > > Hi all, > > > I have a python script that works without any problem on Windows but > > with error: > > > QPaintDevice: Must construct a QApplication before a QPaintDevice > > > on Linux. > > > Where could be the problem? > > This is the problem: > > You Must construct a QApplication before a QPaintDevice > > Diez Yes that I can deduce, but why I'm asking is why it's different on Windows and Linux. Should it not be platform independent? From jordan.taylor2 at gmail.com Tue Feb 20 12:59:59 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 20 Feb 2007 09:59:59 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> Message-ID: <1171994399.198264.216830@p10g2000cwp.googlegroups.com> On Feb 18, 7:35 pm, Dave Cook wrote: > On 2007-02-16, ifti_cr... at yahoo.com wrote: > > > i have read about Python, Ruby and Visual C++. but i want to go > > through with GUI based programming language like VB.net > > You might take a look athttp://dabodev.com > > Dave Cook Learn python, and then learn wxpython (python binding of wxWidgets). wxWidgets is one of the most extensive and well built gui tools (in my opinion) and is easier to implement in python than C++ (also my opinion). The only reason I can see for using C++ over Python for gui building is if for some obscure reason Python wasn't fast enough. On the other hand, this brings up the argument of which is faster: Python or C++ ;) so let's not get into that. Python + WxPython = Good Language with Good GUI Toolkit. Cheers, Jordan From S.Mientki-nospam at mailbox.kun.nl Tue Feb 6 17:01:36 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 06 Feb 2007 23:01:36 +0100 Subject: Python editor In-Reply-To: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> Message-ID: <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> BBands wrote: > No, no, no, this is not an invitation to the editor wars. > > I have been using Jos? Cl?udio Faria's superb Tinn-R, http://www.sciviews.org/Tinn-R/, > with the R language, http://www.r-project.org/. This editor allows you > to send code to the R shell for execution. You can easily send a line, > the selection, the balance after the cursor or the whole script. > > I have recently decided to move this project to Python instead of R. > However, I miss the interaction with the shell a la Tinn-R. Do any of > the Python editors support this feature? I think PyScripter and SPE both have these features and much more. cheers, Stef Mientki From tsuraan at gmail.com Fri Feb 16 14:17:16 2007 From: tsuraan at gmail.com (tsuraan) Date: Fri, 16 Feb 2007 13:17:16 -0600 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <84fb38e30702161117q65581a0q3ae6a4c3a2ffe201@mail.gmail.com> > Agreed. This would be similar to: > > py> 1 + 1.0 > > Traceback: can only add int to int. Etc. > > But then again, the unimaginative defense would be that it wouldn't be > python if you could catentate a list and a tuple. Of course, that behaviour would be quite defensible; auto-casting int to float is _wrong_, especially with python implementing abitrary precision integers. Integers are more precise than floats, so why would you automatically cast them in that direction? Seeing >>> 0xffffffffffffffffff+1.0==float(0xffffffffffffffffff) True Is considerably more irritating than your hypothetical Traceback would be. -------------- next part -------------- An HTML attachment was scrubbed... URL: From qual at tiscali.de Wed Feb 7 11:56:20 2007 From: qual at tiscali.de (Uwe Hoffmann) Date: Wed, 07 Feb 2007 17:56:20 +0100 Subject: Group Membership in Active Directory Query In-Reply-To: <1170859017.416570.247920@v33g2000cwv.googlegroups.com> References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> <1170859017.416570.247920@v33g2000cwv.googlegroups.com> Message-ID: kooch54 at gmail.com schrieb: > ldap_obj = ldap_obj.simple_bind_s('username at domain.company.com', > 'password') > > > AttributeError: 'NoneType' object has no attribute 'search_Ext_s' > dummy = ldap_obj.simple_bind_s('username at domain.company.com', 'password') or better simply ldap_obj.simple_bind_s('username at domain.company.com', 'password') From tobias at stud.cs.uit.no Fri Feb 16 12:28:24 2007 From: tobias at stud.cs.uit.no (Tobias Brox) Date: Fri, 16 Feb 2007 17:28:24 +0000 (UTC) Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: [Edward K Ream] > Not at all. Backwards compatibility means that one can still run old code > provided the code eschews new features. Python releases have generally > been backwards compatible with previous releases, with a few minor > exceptions. For example, my app runs fine on Python 2.2.2 through Python > 2.5, and little work was required to make this happen. 2.2 -> 2.5 is a minor step, the 2.2-code should in general work out on 2.5 without problems. 2.6 -> 3.0 will be a major step, and code written for 2.6 or earlier will in general not run on python 3.0. Hopefully this issue can be partially solved by automatic code converting. -- Tobias Brox, 69?42'N, 18?57'E From guettli.usenet at thomas-guettler.de Tue Feb 6 10:37:24 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 6 Feb 2007 15:37:24 GMT Subject: Running long script in the background References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> Message-ID: <52rllkF1p76kmU1@mid.individual.net> wattersmt at gmail.com wrote: > Hello, > > I am trying to write a python cgi that calls a script over ssh, the > problem is the script takes a very long time to execute so Apache > makes the CGI time out and I never see any output. The script is set > to print a progress report to stdout every 3 seconds but I never see > any output until the child process is killed. > > Here's what I have in my python script: > > command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % > (host, domuname) > output = os.popen(command) > for line in output: > print line.strip() try sys.stdout.flush() after every print. Or try something like this: import sys, time class FlushFile: def __init__(self, fd): self.fd = fd def flush(self): self.fd.flush() def write(self, str): self.fd.write(str) self.fd.flush() oldstdout = sys.stdout sys.stdout = FlushFile(sys.stdout) for i in range(5): print "Hello", time.sleep(0.5) print -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From ms at cerenity.org Sun Feb 18 15:33:38 2007 From: ms at cerenity.org (Michael) Date: Sun, 18 Feb 2007 20:33:38 +0000 Subject: c++ for python programmers References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <45d8b736$0$8737$ed2619ec@ptn-nntp-reader02.plus.net> Thomas Nelson wrote: > I realize I'm approaching this backwards from the direction most > people go, but does anyone know of a good c/c++ introduction for > python programmers? There's been lots of answers, but no-one's mentioned the book I like: * Accelerated C++ by Koenig & Moo It dives straight into C++ - rather than attempting to say "look, C++ is built ontop of C, so I'll teach you C first, I'll recognise that the idioms for developing in C++ are different and start from there instead". It's in my opinion by far and away one of the best intros I've read. (I'm not saying that lightly either - I rank it as good/language relevant an introduction as Learning Perl used to be, and the K&R book can be for many C developers). In many respects it'll also show you some of the similarities between python and C++, and the differences. Michael. From arnd.zapletal at googlemail.com Sat Feb 3 18:25:32 2007 From: arnd.zapletal at googlemail.com (Arnd) Date: 3 Feb 2007 15:25:32 -0800 Subject: PyGUI show_text() Message-ID: <1170545132.303861.325340@v33g2000cwv.googlegroups.com> Heya, any PyGUI users out there? I needed some finer text-positioning on a canvas (ie wanted to center a string wrt a point, something show_text() doesn't provide) So I looked into the sources and found all information, eg the dimensions of the surrounding rectangle are given by mycanvas._font._get_pango_layout(mystring, True).get_pixel_size() >From this one can calculate a new basepoint, this works fine. I wonder if there is a more elegant way I've overseen so far. (Or if not, Greg ;) would it be possible to include some optional positioning parameters, something like left,center,right,top,middle,bottom to show_text()). All in all thanks a lot for PyGUI, even if it's still far away from beeing complete. To me it really brought back some fun in python-gui-programming. Arnd From jstroud at mbi.ucla.edu Tue Feb 27 18:47:25 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 27 Feb 2007 15:47:25 -0800 Subject: Running Python scripts from BASH In-Reply-To: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> References: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> Message-ID: Ishpeck wrote: > I'm using Python to automate testing software for my company. I > wanted the computers in my testing lab to automatically fetch the > latest version of the python scripts from a CVS repository and then > ask a local database server which of the scripts to run. > > I built the following: > > #!/bin/bash > # Batcher will run the specified scripts. > > cvs update > > while true > do > # This part makes sure that > # every hour or so, we get the latest > # snapshot of the suite from CVS. > if [ $(date +%M) = 0 ]; then > cvs update > sleep 360 > fi > # Then we grab the name of > # a randomly-selected script > i=$(python randomRun.py) > # If the return-value of randomRun.py > #is empty, we don't run it. > if ["$i"=""]; then > echo Not running anything > sleep 3600 > # If randomRun doesn't return > # empty, we run the script that it prints. > else > python "$i"; > sleep 2 > fi > done > > > --------- END BASH FILE -------- > > For debugging purposes, you can just build "randomRun.py" to do the > following: > > print "randomRun.py" > > It's silly but works. > > Whenever I run this script, Python decides that it doesn't like the > way BASH feeds it the name of the script. I get the following > message: > > ': [Errno 22] Invalid argumentopen file 'foo.py > > I dunno. Maybe this is a better question for a BASH-related group. > How do I get around this? > Perhaps code the whole thing in python and not bash/python. Don't send a boy in to do a man's job. All you need to remember is import os [....] os.system('whatever command here') James From steven.bethard at gmail.com Thu Feb 15 17:06:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 15 Feb 2007 15:06:54 -0700 Subject: Pep 3105: the end of print? In-Reply-To: References: Message-ID: Edward K Ream wrote: > The pros and cons of making 'print' a function in Python 3.x are well > discussed at: > > http://mail.python.org/pipermail/python-dev/2005-September/056154.html > > Alas, it appears that the effect of this pep would be to make it impossible > to use the name 'print' in a backward compatible manner. You could offer up a patch for Python 2.6 so that you can do:: from __future__ import print_function and have the 'print' statement replaced by the 'print' function. That said, why can't you use ``file.write()`` instead of ``print``? While I use print quite frequently in interactive use, it's pretty much nonexistent in all my real code. STeVe From limodou at gmail.com Wed Feb 7 08:28:29 2007 From: limodou at gmail.com (limodou) Date: Wed, 7 Feb 2007 21:28:29 +0800 Subject: Python editor In-Reply-To: <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> References: <1170795073.364979.247450@v33g2000cwv.googlegroups.com> <1a378$45c8fab3$d443bb3a$2464@news.speedlinq.nl> <1170851197.656670.179590@a75g2000cwd.googlegroups.com> <612bf$45c9d14f$d443bb3a$20006@news.speedlinq.nl> Message-ID: <505f13c0702070528h2081db67pcad0bca448311896@mail.gmail.com> Maybe you can try ulipad. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From jgodoy at gmail.com Sat Feb 3 12:33:25 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 03 Feb 2007 15:33:25 -0200 Subject: Python does not play well with others References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> <7xk5yz2q42.fsf@ruckus.brouhaha.com> <52jt3eF1p85tbU1@mid.uni-berlin.de> <7xy7nf1850.fsf@ruckus.brouhaha.com> Message-ID: <87k5yzkuxm.fsf@gmail.com> Paul Rubin writes: > "Diez B. Roggisch" writes: >> And they certainly require special treatment like putting them in the >> classpath, setting up the project directory and the like - no simple >> import will work out of the box, as it would witch python standard lib >> drivers. > > Well, that's nowhere near as big a deal as having yet another set of > vendors or maintainer to deal with. Minimizing configuration is nice, > but getting your software from as few different sources as possible is > also a big win. So we should get a better egg support. Then it would all be just a matter of easy_install . As it is that easy for thousands of modules on CPAN for Perl. -- Jorge Godoy From cniharral at gmail.com Fri Feb 2 07:00:31 2007 From: cniharral at gmail.com (cniharral at gmail.com) Date: 2 Feb 2007 04:00:31 -0800 Subject: How do I print out in the standard output coloured lines Message-ID: <1170417631.268771.108090@v45g2000cwv.googlegroups.com> Hi, I'm interested in printing out coloured lines of my application and I don't know what to use. Can anybody give me an idea?? Regards. Carlos Niharra L?pez From donn at u.washington.edu Fri Feb 16 18:57:54 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 16 Feb 2007 15:57:54 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> <7xfy956gq8.fsf@ruckus.brouhaha.com> Message-ID: In article <7xfy956gq8.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Donn Cave writes: > > Unpredictable? How do you manage to write functions in this case? > > Are all your formal parameter lists like (*a), with logic to deal > > with the variable lengths? > > I'm thinking of functions like printf, which take a variable number of > args and don't assign them into variables by position. I don't really see why you're thinking of them, but if you look at how they do it, you'll see that they use some run time magic to work as if they were written as conventional functions. This invariably involves some accessory data, like printf's format string, that in effect tells the function its parameter implementation at run time - including number of parameters, since you can't tell even that from standard args data as far as I know. What this proves is that you can implement an argument list at run time, but it by no means changes the nature of the argument list as a sequence. Donn Cave, donn at u.washington.edu From tjreedy at udel.edu Mon Feb 19 14:07:58 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Feb 2007 14:07:58 -0500 Subject: Declare a variable global References: <1171904659.500302.70150@q2g2000cwa.googlegroups.com> <1171907496.269876.295200@p10g2000cwp.googlegroups.com> Message-ID: | Here is my complete script: | #!/usr/bin/python | | import re | import sys | import time | import os | import shutil | | colors = ["#FF0000", "#00FF00", "#0000FF", | "#FFFF00" ,"#FFA500" ,"#DA70D6"] | colorIndex = 0 | | def getText( intputstr): | rc = "" | | maxX = 0; | maxY = 0; | minX = 10000000; | minY = 10000000; | | | for str in intputstr: | | print str; | | if str != "": | pattern = "x:(\d+) y:(\d+) w:(\d+) h:(\d+) (.*)" | | match = re.findall(pattern, str) | | if match: | x, y, width, height, area = match[0] | | colorIndex = colorIndex + 1 | | rc = rc + "\n" % colors[colorIndex % len(colors)] | | _x = int(x) | _y = int(y) | _width = int(width) | _height = int(height) | | minX = min(minX, _x); | minY = min(minY, _y); | | maxX = max(maxX, _x+ _width); | maxY = max(maxY, _y+_height); | | | | else: | pattern = "\((\d+),(\d+)\)\((\d+),(\d+)\)(.*)" | | match = re.findall(pattern, str) | | if match: | x1, y1, x2, y2, ignore = match[0] | | rc = rc + "" % locals() | rc = rc + "\n" | | _x1 = int(x1) | _y1 = int(y1) | _x2 = int(x2) | _y2 = int(y2) | | minX = min(_x1, _x2); | minY = min(_y1, _y2); | | maxX = max(_x1, _x2); | maxY = max(_y1, _y2); | | print colorIndex; | | print "match 2!" | | | return rc, minX, minY, maxX, maxY; | | fileName = sys.argv[1] | | inputFile = open(fileName, 'r') | data = inputFile.readlines(); | outdata, minX, minY, maxX, maxY = getText(data); | | print minX, minY, maxX, maxY | | outputFile = open(fileName + '.svg', 'w') | | print >> outputFile, "" | | outputFile.write(outdata); | | print >>outputFile, "" | | | -- | http://mail.python.org/mailman/listinfo/python-list | From nagle at animats.com Sat Feb 3 03:11:51 2007 From: nagle at animats.com (John Nagle) Date: Sat, 03 Feb 2007 08:11:51 GMT Subject: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead" Message-ID: How do I suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead". A library is triggering this message, the library is being fixed, but I need to make the message disappear from the output of a CGI program. John Nagle From stuart at bmsi.com Sat Feb 3 18:29:55 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sat, 03 Feb 2007 18:29:55 -0500 Subject: Is Python Right for Me? References: Message-ID: On Fri, 02 Feb 2007 15:09:20 -0500, Mister Newbie wrote: > I want to make small, 2D games. I have no programming experience. Is > Python a good choice? Definitely. I teach a class for 7th to 12th grade where I use this tutorial to introduce programming: http://www.livewires.org.uk/python/ http://www.livewires.org.uk/python/pdfsheets.html As an adult, just skip rapidly through the elementary material. The final module (Games sheets) walks you through creating 3 2D games with pygame! -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From steveo at syslang.net Fri Feb 9 11:45:28 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 9 Feb 2007 11:45:28 -0500 (EST) Subject: Question about optparse/OptionParser callback. Message-ID: I'm new to python and I have a need to do this. The Cookbook almost takes me there with: def check_order(option, opt_str, value, parser): if parser.values.b: raise OptionValueError("can't use %s after -b" % opt_str) setattr(parser.values, option.dest, 1) but warns that the "it needs a bit of work: the error message and the flag that it sets must be generalized". I do need to do my option processing in an option processor with many options. Is it possible to have a callback that knows how to access all of the options? Many thanks. All I need is to be taught how to fish... -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From michele.simionato at gmail.com Tue Feb 27 03:35:21 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Feb 2007 00:35:21 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area In-Reply-To: References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> Message-ID: <1172565321.372992.57320@v33g2000cwv.googlegroups.com> On Feb 27, 2:51 am, Dan Bensen wrote: > > Tech HR wrote: > > easier to train a Java programmer or a Perler on Python than Lisp.Dan Bensen wrote: > > > Are your technical problems simple enough to be solved by Python > > trainees? > > Aahz wrote: > > If they're already good programmers, yes. > > Sure, but who are these good programmers (coming from Java or Perl)? > Do you have a list of them? The employer needs to know how many > not-so-good programmers they have to interview before they find one > who's good enough. It depends on how hard the programming is. Right, so they should hire Python programmers who know Lisp too. This is not so uncommon, we have at least three people here where I work. Michele Simionato From uval at rz.uni-karlsruhe.de Wed Feb 14 11:55:54 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Wed, 14 Feb 2007 17:55:54 +0100 Subject: builtin set literal Message-ID: Hello, lst = list((1,2,3)) lst = [1,2,3] t = tupel((1,2,3)) t = (1,2,3) s = set((1,2,3)) s = ... it would be nice feature to have builtin literal for set type maybe in P3 .. what about? s = <1,2,3> Regards, Daniel From Ido.Yehieli at gmail.com Wed Feb 7 12:16:03 2007 From: Ido.Yehieli at gmail.com (Ido Yehieli) Date: 7 Feb 2007 09:16:03 -0800 Subject: (n)curses or tcl/tk? In-Reply-To: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> References: <1170866141.200668.178590@a34g2000cwb.googlegroups.com> Message-ID: <1170868563.937217.161550@p10g2000cwp.googlegroups.com> On Feb 7, 5:35 pm, "magnate" wrote: > So my question is, should I go to the trouble of learning how to make > boxes and stuff using tcl/tk, or just go with ncurses as I imagined? If you want to use curses on windows with python you need to install WCurses first. Other then that it is very portable. After you get used to it curses is also quite easy to use, however tk has a more features. Depends on what you want to do. I would have used curses in your position because it is easy to use (although tk is no rocket science either) and I like apps that can run on a terminal emulator. Ido. From mail at microcorp.co.za Sat Feb 24 02:59:04 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 24 Feb 2007 09:59:04 +0200 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <7xy7mpz6df.fsf@ruckus.brouhaha.com> Message-ID: <01fc01c757f2$b7342ae0$03000080@hendrik> "Paul Rubin" wrote: > "Hendrik van Rooyen" writes: > > s = 'some string that needs a bcc appended' > > ar = array.array('B',s) > > bcc = 0 > > for x in ar[:]: > > bcc ^= x > > ar.append(bcc) > > s=ar.tostring() > > Untested: > > import operator > s = 'some string that needs a bcc appended' > ar = array.array('B',s) > s += chr(reduce(operator.xor, ar)) > Yikes! - someday soon I am going to read the docs on what reduce does... Won't this be slow because of the double function call on each char? - Hendrik From mccredie at gmail.com Mon Feb 12 09:42:50 2007 From: mccredie at gmail.com (Matimus) Date: 12 Feb 2007 06:42:50 -0800 Subject: New Pythin user looking foe some good examples to study In-Reply-To: <1171276231.983653.264240@p10g2000cwp.googlegroups.com> References: <1171276231.983653.264240@p10g2000cwp.googlegroups.com> Message-ID: <1171291370.590370.93220@j27g2000cwj.googlegroups.com> I agree, the standard libraries are a good place to start. I learned a lot by looking at them, plus it has the added bonus that you learn the standard libraries. > I suspect them to be below usr/lib on linux. /usr/lib/python2.4 /usr/lib/python2.5 On Debian/Ubuntu anyway. From Bulkan at gmail.com Wed Feb 14 23:51:04 2007 From: Bulkan at gmail.com (placid) Date: 14 Feb 2007 20:51:04 -0800 Subject: How much memory used by a name In-Reply-To: <45d39d03$0$19671$426a74cc@news.free.fr> References: <45d36eea$0$24957$426a74cc@news.free.fr> <45d39d03$0$19671$426a74cc@news.free.fr> Message-ID: <1171515064.650503.326270@q2g2000cwa.googlegroups.com> On Feb 15, 11:08 am, Bruno Desthuilliers wrote: > Bernard Lebel a ?crit : > > > Diez: thanks, I will try that. However isn't sum() returning an > > integer that here would represent the number of elements? > > Nope, it will return the sum of the length of the lines in the list. The > long way to write it is: > > total = 0 > for line in thelist: > total += len(line) > > > > > Bruno: good question. We're talking about text files that can have > > 300,000 lines, if not more. Currently, the way I have coded the file > > writing, every line calls for a write() to the file object, > > Seems sensible so far... > > > The file is on the network. > > Mmm... Let's guess : it's taking too much time ?-) > > > This is taking a long time, > > (You know what ? I cheated) > > > and I'm looking for ways to speed up this > > process. I though that keeping the list in memory and dropping to the > > file at the very end could be a possible approach. > > OTOH, if the list grows too big, you may end up swapping (ok, it would > need a very huge list). A "mixed" solution may be to wrap the file in a > "buffered" writer that only perform a real write when it's full. This > would avoid effective i/o on each line while keeping memory usage > reasonable. Another one would be async I/O, but I don't know if and how > it could be done in Python (never had to manage such a problem myself). > > My 2 cents... What i can suggest is to use threads (for async I/O). One approach would be to split the script into two, so you have your main thread generating the strings, then you use another thread (which has a Queue object) that blocks on the get method of the Queue, once it gets the string it then writes it to the file. Your main thread generates strings and keeps on adding this to the Queue of the second thread. How much of a speed advantage this will provide i do not know. Email me ff you require assistance. I would be more than welcome to help. Cheers From bmaron2 at hotmail.com Sun Feb 25 16:51:15 2007 From: bmaron2 at hotmail.com (bmaron2 at hotmail.com) Date: 25 Feb 2007 13:51:15 -0800 Subject: Help on object scope? In-Reply-To: <0knEh.4753$3b5.1201@newsfe24.lga> References: <1172438758.646750.114860@z35g2000cwz.googlegroups.com> <0knEh.4753$3b5.1201@newsfe24.lga> Message-ID: <1172440275.868863.91120@k78g2000cwa.googlegroups.com> On Feb 25, 9:37 am, hg wrote: > bmar... at hotmail.com wrote: > > Hello everybody, > > > I have a (hopefully) simple question about scoping in python. I have a > > program written as a package, with two files of interest. The two > > files are /p.py and /lib/q.py > > > My file p.py looks like this: > > > --- > > > from lib import q > > > def main(): > > global r > > r = q.object1() > > s = q.object2() > > > if __name__ == "__main__": > > main() > > > --- > > > My file q.py in the subdirectory lib looks like this: > > > class object1: > > t = 3 > > > class object2: > > print r.t > > > --- > > > Python gives me an error, saying it can't recognize global name r. > > However I define r as global in the top-level main definition! Can > > anyone suggest how I can get around this, if I want to define and bind > > global names inside of main() which are valid in all sub-modules? > > > Thanks very much for your help! > > Might be wrong, but globals can only be global to the module they're > declared in. > > I suggest you find another way such as passing your object as a parameter > > hg Dear hg, Thank you for the advice, but that seems a bit unwieldy. My code will have about 10 of these global objects, all of which interact with eachother. It seems silly to have to pass 10 parameters around to each instance I work with. I hope there is a smarter way to do it, or perhaps someone can suggest a smarter way to code it. Am I stuck with just having to put all the code in one file? That is what I wanted to avoid, because the file will get incredibly long. It seems like the only reason my code above failed is because there were two separate modules. Perhaps I just need to import /lib/q.py in a different way? Many thanks. From peterbe at gmail.com Fri Feb 23 10:12:46 2007 From: peterbe at gmail.com (Peter Bengtsson) Date: 23 Feb 2007 07:12:46 -0800 Subject: Finding non ascii characters in a set of files In-Reply-To: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> References: <1172241521.375560.125040@a75g2000cwd.googlegroups.com> Message-ID: <1172243566.906121.189930@h3g2000cwc.googlegroups.com> On Feb 23, 2:38 pm, b... at yahoo.com wrote: > Hi, > > I'm updating my program to Python 2.5, but I keep running into > encoding problems. I have no ecodings defined at the start of any of > my scripts. What I'd like to do is scan a directory and list all the > files in it that contain a non ascii character. How would I go about > doing this? > How about something like this: content = open('file.py').read() try: content.encode('ascii') except UnicodeDecodeError: print "file.py contains non-ascii characters" From http Tue Feb 20 11:35:44 2007 From: http (Paul Rubin) Date: 20 Feb 2007 08:35:44 -0800 Subject: builtin set literal References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <1171988959.628359.260710@l53g2000cwa.googlegroups.com> Message-ID: <7xk5yc7pnj.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > Unrelated: Ruby and Lisp use ? and ! at the end of the function/method > names to denote a predicate or a function that mutates in place (With > them the list.sort() may be called list.sort!() ). Using Python I > usually put an Q at the end of the name for this purpose. Can Py 3.0 > support names ending with "?" too? I don't think that's part of the plan. However, Python seems to use the -ed suffix for the non-mutating versions of these functions, e.g. sorted(list) instead of the mutating list.sort(). From ms at cerenity.org Fri Feb 23 19:17:54 2007 From: ms at cerenity.org (Michael) Date: Sat, 24 Feb 2007 00:17:54 +0000 Subject: Shed Skin Optimizing Python-to-C++ Compiler 0.0.19 References: <45cf1609$0$8717$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <45df8329$0$8717$ed2619ec@ptn-nntp-reader02.plus.net> I randomly scribbled : > Mark Dufour wrote: > >> This >> latest release adds basic support for iterators and generators > > Oooh, I may try our miniaxon tutorial against shed skin in that case. > (ie http://kamaelia.sourceforge.net/MiniAxon/) I thought some people may be interested to hear that I did do this, and whilst ShedSkin does have some limitations, and needs one piece of manual assistance, Shed Skin *can* compile a Kamaelia Mini-Axon. A Kamaelia Mini-Axon is something we use for teaching how a Kamaelia core can be created, but still features the core message passing, compositional nature of Kamaelia. It's essentially the smallest sufficient subset. Personally I think ShedSkin is pretty spectacular for being able to do this, and also generate highly readable C++ code as a result. The code it compiles to C++, the thing I had to manually assist shedskin with, & the code shed skin generates for that are attached on this page: http://yeoldeclue.com/cgi-bin/blog/blog.cgi?rm=viewpost&nodeid=1172157410 I was half expecting as I went through doing this that this would fail at some point, but for me this is a relatively complex, relatively substantial system that *does* compile. (It also shows me that Kamaelia's approach is implementable in C++ beyond a naive approach, which is a nice bonus :) Shedskin home: http://mark.dufour.googlepages.com Many congrats to Mark on this :-) Michael. -- Kamaelia Project Lead http://kamaelia.sourceforge.net/Home http://yeoldeclue.com/blog From supervau at gmail.com Fri Feb 16 18:15:15 2007 From: supervau at gmail.com (Frank) Date: 16 Feb 2007 15:15:15 -0800 Subject: saving path to modules permanently Message-ID: <1171667715.610158.90570@a75g2000cwd.googlegroups.com> Hi, I want to create some modules to use them in my programs. Now the problem is, how to add the path to these modules permanently to the python search path. For example: import sys sys.path.append('path to my modules') works fine for one session but does not save this path permanently. I also tried alreday to set the PYTHONPAHT variable to my modules but for some reason this does not work either. Question: Can one add a permenent path via pathon commands (I checked already sys, but it does not seem to have a function for this). If not, how to do it otherwise. It would be great to give the precise commands if someone knows how. (BTW, I use linux) Thanks! Frank From bdesth.quelquechose at free.quelquepart.fr Thu Feb 1 16:28:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 22:28:58 +0100 Subject: Sorting a list In-Reply-To: <45c246eb$0$31965$c3e8da3@news.astraweb.com> References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> <45c243a7$0$3020$426a34cc@news.free.fr> <45c245e1$0$31965$c3e8da3@news.astraweb.com> <45c246eb$0$31965$c3e8da3@news.astraweb.com> Message-ID: <45c254a2$0$674$426a34cc@news.free.fr> John Salerno a ?crit : > John Salerno wrote: > >> Bruno Desthuilliers wrote: >> >>> John Salerno a ?crit : >>> >>>> Hi everyone. If I have a list of tuples, and each tuple is in the form: >>>> >>>> (year, text) as in ('1995', 'This is a citation.') >>>> >>>> How can I sort the list so that they are in chronological order >>>> based on the year? >>> >>> >>> Calling sort() on the list should just work. >> >> >> Amazing, it was that easy. :) > > > One more thing. What if I want them in reverse chronological order? I > tried reverse() but that seemed to put them in reverse alphabetical > order based on the second element of the tuple (not the year). Really ? >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')] >>> lines.sort() >>> lines [('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc'), ('1996', 'aaa'), ('1996', 'ccc'), ('1997', 'aaa'), ('1997', 'bbb')] >>> lines.reverse() >>> lines [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), ('1995', 'ccc'), ('1995', 'bbb'), ('1995', 'aaa')] >>> As you see, the list is being sorted on *both* items - year first, then sentence. And then of course reversed, since we asked for it !-) If you want to prevent this from happening and don't mind creating a copy of the list, you can use the sorted() function with the key and reverse arguments and operator.itemgetter: >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')] >>> from operator import itemgetter >>> sorted(lines, key=itemgetter(0), reverse=True) [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')] HTH. From parallelpython at gmail.com Sat Feb 10 01:16:51 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 9 Feb 2007 22:16:51 -0800 Subject: Can Parallel Python run on a muti-CPU server ? In-Reply-To: References: Message-ID: <1171088210.987877.112860@s48g2000cws.googlegroups.com> Hi, That is definitely possible! To achieve the best performance split your calculation either into 128 equal parts or int >>128 part of any size (then load balancing will spread workload equally). Let us know the results, if need any help with parallelization feel free to request it here: http://www.parallelpython.com/component/option,com_smf/Itemid,29/ Thank you! On Feb 7, 2:13 am, "fdu.xia... at gmail.com" wrote: > Hi all, > > I'm interested inParallelPythonand I learned from the website ofParallelPython > that it can run on SMP and clusters. But can it run on a our muti-CPU > server ? > We are running an origin3800 server with 128 CPUs. > > Thanks. From craiglewiston at gmail.com Sun Feb 11 21:40:03 2007 From: craiglewiston at gmail.com (craiglewiston at gmail.com) Date: 11 Feb 2007 18:40:03 -0800 Subject: Help with Optimization of Python software: real-time audio controller Message-ID: <1171248003.662467.184700@a34g2000cwb.googlegroups.com> I've been working on a Python-based music training application for a few months, and have recently run into what I believe are some basic limitations (or at least constraints) of Python with regards to timing. I'll try and give a decently thorough description, and hopefully some of you can process this with your knowledge and help steer me in the right direction. As mentioned above, my application deals with music training. I have a Tkinter GUI, which communicates via pyserial with an external device I built myself. The code reads in a MIDI file and converts the song to "output data " for the external device and the GUI, all adjusted to the user-selected tempo. While the MIDI file is playing, there are 4 main actions the code must take: 1) Send "output data" signals out to the external hardware. 2) Poll the input from the external hardware device for incoming keypresses. If detected, then the play the sound corresponding to that key. 3) Start and keep a metronome running for the durations of the song. 4) Update GUI I'm able to get all the above "accomplished" through the use of threads and a top-level loop (for updating the Tkinter GUI - if you've worked with threads and Tkinter, then you know that you can't update a Tkinter GUI from a thread, but instead have to do it on the top level loop). While running, I have the following threads implemented : 1) song processing thread - this thread steps incrementally through a data matrix (the "output data"), and updates two variables: GUI_vars and Device_vars 2) metronome thread - this thread starts at the same time as thread #1, and outputs a "beep" to the audio chain 3) poll input thread - this thread loops continually, looking for data on the serial Input. When data is found, it starts playing the sound corresponding to that key until a "note off" signal is received 4) top-level recursive loop (technically not a thread) for updating GUI and calling Serial Write subfunction. This loop monitors GUI_vars and Device_vars, updating the GUI and writing out to the device when either variable has changed Currently, I have all of the above "working", although I'm running into some serious timing issues. When I run the program, I get irregular timing for my metronome (if it sounds at all), as well as irregular timing in writing to the external device. It's extremely crucial that threads #1 & #2 are executed as close to real-time as possible, as they form the "core" of the song, and their elements can't be delayed without "messing" the song up considerably. I've read up quite a bit on different optimization methods in Python, but am not sure which direction to head. I've checked out profile, Psyco, Pyrex, as well as just porting everything over to C. Since I'm on a Mac (Power PC), I can't use Psyco. And doing any of the others seemed like a big enough project that I should really ask someone else before I embark. So, for a music-based application where it's crucial to have real-time execution of serial writeouts and audio, as well as keeping a continual poll on the input from the same port....can this be done successfully in Python? Does using Tkinter have anything to do with my timing issues? Would it benefit me to move over to wxPython (something I've been considering doing)? As for the metronome, should I incorporate the metronome thread into the "song processing" thread, since both are dealing with events whose timing is crucial? I'm a relative newbie (this is my first Python project) to Python, so any help is GREATLY appreciated! Also, just for reference, here's a list of the modules I'm using and my system info: Audio: SndObj Ser com: pyserial GUI: Tkinter System: Apple PowerBook G4 (PowerPC), Mac OS 10.4, Python 2.4.4 Thanks, Craig Lewiston From http Wed Feb 14 18:22:52 2007 From: http (Paul Rubin) Date: 14 Feb 2007 15:22:52 -0800 Subject: threading and multicores, pros and cons References: <7xodnx2vir.fsf@ruckus.brouhaha.com> <7x7iulqlvx.fsf@ruckus.brouhaha.com> <1171488267.433565.228110@a75g2000cwd.googlegroups.com> <7xejosctev.fsf@ruckus.brouhaha.com> <1171494879.866830.102710@m58g2000cwm.googlegroups.com> Message-ID: <7xabzg2uk3.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" writes: > > question of library functions--you could certainly write JNI > > extensions for that stuff [access to mmap, etc.] > Sure. If you're writing extensions you can work around the GIL, too. I don't think that's comparable--if you have extensions turning off the GIL, they can't mess with Python data objects, which generally assume the GIL's presence. Python's mmap module can't do that either. > Up through 1.3/1.4 or so they were pretty staunchly in the "threads > for everything!" camp, but they've added a select/poll-style call a > couple versions back. That was a pretty big sticking point previously. They've gone much further now and they actually have some STM features: http://www-128.ibm.com/developerworks/java/library/j-jtp11234/ From howardrh at westerncom.net Mon Feb 26 20:00:49 2007 From: howardrh at westerncom.net (hrh1818) Date: 26 Feb 2007 17:00:49 -0800 Subject: is it possible to use ironpython 1.1 in visual studio 2005 In-Reply-To: <1172524556.739101.245050@v33g2000cwv.googlegroups.com> References: <1172524556.739101.245050@v33g2000cwv.googlegroups.com> Message-ID: <1172538049.848100.97380@h3g2000cwc.googlegroups.com> For those who don't subscribe to the Iron Python Mail Group check the following answer to this question. This was good heads up for me http://blogs.msdn.com/533273.aspx Howard On Feb 26, 3:15 pm, "jojoba" wrote: > hi all > is it possible to use ironpython 1.1 in visual studio 2005? > i have 1.0 running great...but would love to use the newer verision > any ideas > thank you immenely, > jojoba From rdm at rcblue.com Sat Feb 3 08:10:44 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 03 Feb 2007 05:10:44 -0800 Subject: Python 2.5 Quick Reference In-Reply-To: <45C479EA.20908@jessikat.plus.net> References: <45C479EA.20908@jessikat.plus.net> Message-ID: <20070203131049.2990B1E4009@bag.python.org> At 04:02 AM 2/3/2007, Robin Becker wrote: >Dick Moores wrote: > > > > Is this reliable? (Looks good to me, but...) > > >..... > >I really like these for a good overview So it looks accurate? Dick Moores From roger.miller at nova-sol.com Fri Feb 16 14:42:03 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: 16 Feb 2007 11:42:03 -0800 Subject: why I don't like range/xrange In-Reply-To: <1171645302.453369.166190@s48g2000cws.googlegroups.com> References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <1171645302.453369.166190@s48g2000cws.googlegroups.com> Message-ID: <1171654923.701607.301080@h3g2000cwc.googlegroups.com> On Feb 16, 7:01 am, "Bart Ogryczak" wrote: > On Feb 16, 4:30 pm, "stdazi" wrote: > > > for (i = 0; some_function() /* or other condition */ ; i++) > > C's "for(pre,cond,post) code" is nothing more, then shorthand form of > "pre; while(cond) {code; post;}" I don't disagree with your basic point, but technically this is not quite true. Try it with for (i = 0; i < n; i++) { if (x[i] == 0) continue; printf("%d\n", x[i]); } From steve at REMOVE.THIS.cybersource.com.au Fri Feb 16 10:17:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Feb 2007 02:17:23 +1100 Subject: Pep 3105: the end of print? References: Message-ID: On Fri, 16 Feb 2007 09:49:03 -0500, Jean-Paul Calderone wrote: > On Sat, 17 Feb 2007 01:32:21 +1100, Steven D'Aprano >> [snip] >> >>I don't think that follows at all. print is only a problem if you expect >>your code to work under both Python 2.x and 3.x. I wouldn't imagine >>that many people are going to expect that: I know I don't. > > I think some people are confused that the language "Python 3.x" has "Python" > in its name, since there is already a language with "Python" in its name, > with which it is not compatible. There is no language "Python 3" -- yet. We're still all guessing just how compatible it will be with Python 2. To be precise, there is an experimental Python 3, but the specifications of the language are not fixed yet. As for the name... big deal. C and C++ and Objective C are completely different languages. Fortran 77 and Fortran 90 aren't exactly the same; nobody expects the same code to run unmodified on Forth 77 and FigForth, or any of another three dozen varieties of Forth. And dare I mention Java and Javascript? Even in the Python world, nobody expects to run the same code base under C Python and Jython and IronPython and PyPy. -- Steven. From donn at u.washington.edu Tue Feb 6 14:00:39 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 06 Feb 2007 11:00:39 -0800 Subject: Repr or Str ? References: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> Message-ID: In article <1170758827.396931.80680 at m58g2000cwm.googlegroups.com>, "Johny" wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences You expect repr to include information that you might call `meta-data' or `type' -- object class and so forth. To the extent that this is of any interest, it's more or less equally of interest with all objects. If you go to the trouble to support str separately, it's a data conversion and of course should render only the data. An application should be able to use str() to force data to string type (that's what I mean by conversion.) If the object can't sensibly be converted to string type, then normally __str__ is omitted, and defaults to __repr__. Donn Cave, donn at u.washington.edu From greg.kujawa at gmail.com Sat Feb 10 21:58:51 2007 From: greg.kujawa at gmail.com (gregarican) Date: 10 Feb 2007 18:58:51 -0800 Subject: Regular Expressions In-Reply-To: References: Message-ID: <1171162731.488726.160400@a75g2000cwd.googlegroups.com> On Feb 10, 6:26 pm, "Geoff Hill" wrote: > What's the way to go about learning Python's regular expressions? I feel > like such an idiot - being so strong in a programming language but knowing > nothing about RE. I highly recommend reading the book "Mastering Regular Expressions," which I believe is published by O'Reilly. It's a great reference and helps peel the onion in terms of working through RE. They are a language unto themselves. A fun brain exercise. From sjmachin at lexicon.net Mon Feb 26 02:42:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 25 Feb 2007 23:42:33 -0800 Subject: RegExp performance? In-Reply-To: References: <45e145a0$0$90264$14726298@news.sunsite.dk> <1172400479.486951.300070@v33g2000cwv.googlegroups.com> <45e1d367$0$90273$14726298@news.sunsite.dk> Message-ID: <1172475753.536102.115830@h3g2000cwc.googlegroups.com> On Feb 26, 2:01 pm, Kirk Sluder wrote: > In article <45e1d367$0$90273$14726... at news.sunsite.dk>, > Christian Sonne wrote: > > > Thanks to all of you for your replies - they have been most helpful, and > > my program is now running at a reasonable pace... > > > I ended up using r"\b\d{9}[0-9X]\b" which seems to do the trick - if it > > turns out to misbehave in further testing, I'll know where to turn :-P > > Anything with variable-length wildcard matching (*+?) is going to > drag your performance down. There was an earlier thread on this very > topic. Another stupid question is how are you planning on handling > ISBNs formatted with hyphens for readability? According to the OP's first message, 2nd paragraph: """ (it should be noted that I've removed all '-'s in the string, because they have a tendency to be mixed into ISBN's) """ Given a low density of ISBNs in the text, it may well be better to avoid the preliminary pass to rip out the '-'s, and instead: 1. use an RE like r"\b\d[-\d]{8,11}[\dX]\b" (allows up to 3 '-'s inside the number) 2. post-process the matches: strip out any '-'s, check for remaining length == 10. Another thought for the OP: Consider (irrespective of how you arrive at a candidate ISBN) validating the ISBN check-digit. Cheers, John From mm2ps at yahoo.co.uk Mon Feb 19 05:34:09 2007 From: mm2ps at yahoo.co.uk (dug) Date: 19 Feb 2007 02:34:09 -0800 Subject: Choices: scipy, matplot ... Message-ID: <1171881249.661739.269400@v45g2000cwv.googlegroups.com> Hi, I would like to do some real time signal processing with a graphical display and I would like your advice as to what I should use. I would like to be able to view the results and to change parameters of some signal processing in 'real time'. Data is coming quite slowly in every 1-5 seconds and will consist of (x,y,t). I have been thinking about SciPy or matplot, but am not restricting myself to these (or even Python). Thank you for any advice, Douglas From grante at visi.com Mon Feb 26 20:01:47 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 27 Feb 2007 01:01:47 -0000 Subject: getting terminal display size? References: <1172451197.309569.166380@k78g2000cwa.googlegroups.com> <12u4g4ci5gqu46c@corp.supernews.com> <12u4gbepet1ek62@corp.supernews.com> <1172537489.610807.288630@p10g2000cwp.googlegroups.com> Message-ID: <12u70nr9lcu4se5@corp.supernews.com> On 2007-02-27, jeff wrote: > I don't really understand any of that; can you right me a function > that'll return the size as a tuple? What do you think I posted? -- Grant Edwards grante Yow! I selected E5... but at I didn't hear "Sam the Sham visi.com and the Pharoahs"! From edreamleo at charter.net Fri Feb 16 10:32:56 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 09:32:56 -0600 Subject: Pep 3105: the end of print? References: Message-ID: > Even in the Python world, nobody expects to run the same code base under C Python and Jython and IronPython and PyPy. Leo now runs under CPython with both wxWidgets and Tkinter. The gui code is confined to plugins, and a similar gui plugin will suffice to run Leo under IronPython. Indeed, Leo's startup code already runs unchanged under CPython and IronPython. I expect minimal changes will be needed to run Leo's core under Jython. And I *am* talking about a single code base: no translator needed. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jura.grozni at gmail.com Sat Feb 10 23:41:41 2007 From: jura.grozni at gmail.com (azrael) Date: 10 Feb 2007 20:41:41 -0800 Subject: favourite editor Message-ID: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> Since i'm new on this forum, and first time meeting a python comunity, i wanted to ask you for your python editors. Im looking for some good python editor, with integrated run function, without having to set it up manualy like komodo. I found the pyscripter, and it has all i need, but it's unsatble. bloated. it crashes when i close an yplication window run by python from pyscripter. please. tell me a good one with buil in run (<-very important) and nice gui. if possible to suport projects, code highlighting, code completition, class browser, python comand line (>>>), traceback. I didn't take a look on vista (and i dont want to), but i hope they improved the notepad. From roman.yakovenko at gmail.com Thu Feb 1 13:12:16 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 1 Feb 2007 20:12:16 +0200 Subject: SWIG overhead In-Reply-To: <4866bea60702010712p431be5b5g1c87ce595d301536@mail.gmail.com> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> <1170328902.611668.271550@k78g2000cwa.googlegroups.com> <52e2bsF1nlgutU1@mid.uni-berlin.de> <1170340876.890010.184840@a75g2000cwd.googlegroups.com> <52ednjF1npm6bU1@mid.uni-berlin.de> <4866bea60702010712p431be5b5g1c87ce595d301536@mail.gmail.com> Message-ID: <7465b6170702011012v579749f7w2576e37001e5681c@mail.gmail.com> On 2/1/07, Chris Mellon wrote: > As I understand it, part of the Boost.Python internals is a C++ > wrapper over the Python C api, That's true. >and there's no separate code generation > phase because it uses template magic to generate the wrappers. Well, actually it depends on the size of the project. If project is small you can use Boost.Python without a code generator. For big projects you have to use the code generator. The advantage is that generated code is pretty readable. > So > while obviously the C API is used at some level, it's not visible to > the wrapper author. Boost.Python hides it pretty well :-) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From openopt at ukr.net Mon Feb 19 04:36:34 2007 From: openopt at ukr.net (openopt at ukr.net) Date: 19 Feb 2007 01:36:34 -0800 Subject: (beginners question) howto set self.field4.subfield8='asdf'? Message-ID: <1171877794.747825.294890@t69g2000cwt.googlegroups.com> I have class A: def __init__(self, objFun, x0): #(I want to have self.primal.f = objFun) #both self.primal.f = objFun #and self.primal = None self.primal.f = objFun yields error what should I do? Thx From jfine at pytex.org Tue Feb 6 05:22:28 2007 From: jfine at pytex.org (Jonathan Fine) Date: Tue, 06 Feb 2007 10:22:28 +0000 Subject: Two mappings inverse to each other: f, g = biject() Message-ID: <45C856E4.6090307@pytex.org> Hello As part of the MathTran project I found myself wanting to maintain a bijection between long names and short names. http://www.open.ac.uk/mathtran In other words, I wanted to have two dictionaries f and g such that f[a] == b g[b] == a are equivalent statements. A google search for biject.py and bijection.py produced no hits, so I suspect that this may not have been done before. I've written a partial implementation of this, and would appreciate comments. http://texd.cvs.sourceforge.net/texd/tex/util.py?revision=1.1&view=markup http://texd.cvs.sourceforge.net/texd/test_tex/test_util.py?revision=1.1&view=markup Here's the code from test_util.py, that shows how it works. The weakref stuff is so that there isn't a circular reference f to g to f. === from tex.util import biject f, g = biject() assert f.inverse is g assert g.inverse is f f[1] = 2 assert f[1] == 2 assert g[2] == 1 assert f.has_value(2) import weakref wr_g = weakref.ref(g) del g assert wr_g() == None assert f.inverse == None === best regards Jonathan From nicola.musatti at gmail.com Tue Feb 13 04:57:00 2007 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 13 Feb 2007 01:57:00 -0800 Subject: c++ for python programmers In-Reply-To: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <1171360620.301301.171560@a75g2000cwd.googlegroups.com> On Feb 12, 7:00 pm, "Thomas Nelson" wrote: > I realize I'm approaching this backwards from the direction most > people go, but does anyone know of a good c/c++ introduction for > python programmers? I don't think there's any book catering specifically for people coming from dynamically typed languages. If you want a crash course try "Accelerated C++", by Koenig & Moo; if you want something more gentle, that may also serve as a reference, go for "C++ Primer", by Lippman, Lajoie & Moo. Both books from Addison Wesley. As for something freely available people speak well of Bruce Eckel's "Thinking in C++", but I haven't read it: http://www.mindview.net/ Books/TICPP/ThinkingInCPP2e.html Cheers, Nicola Musatti From fabiofz at gmail.com Mon Feb 19 11:55:19 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 19 Feb 2007 13:55:19 -0300 Subject: PyDev on Mac In-Reply-To: <1171896514.236693.316700@h3g2000cwc.googlegroups.com> References: <1171774583.972069.161270@j27g2000cwj.googlegroups.com> <53qlrtF1tm3brU1@mid.uni-berlin.de> <1171812580.477975.37060@t69g2000cwt.googlegroups.com> <53rf37F1ttqnuU1@mid.uni-berlin.de> <1171896514.236693.316700@h3g2000cwc.googlegroups.com> Message-ID: > > Pythin runs but PyDev won't use the inerpreter. It gives me an error > saying I'm using an invalid interpreter. > > Is there a way to do this using jPython? > > Pydev usually outputs something into your error log when it says you've specified an invalid interpreter... can you check it? (see http://pydev.sourceforge.net/faq.html#ref_0 for details on how to find it) -- your problem might be that you're specifying a link to the interpreter and not the actual interpreter (unfortunately java does not deal well with symlinks). It should also work with jython (jython 2.1 is the officially supported version). Cheers, Fabio p.s. I also recommend that you take a look at the getting started manual: http://fabioz.com/pydev/manual_101_root.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at reportlab.com Wed Feb 7 05:30:33 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 07 Feb 2007 10:30:33 +0000 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: <17864.51664.838043.38090@montanaro.dyndns.org> References: <17864.51664.838043.38090@montanaro.dyndns.org> Message-ID: <45C9AA49.5060200@chamonix.reportlab.co.uk> skip at pobox.com wrote: > John> MySQLdb isn't fully supported for Python 2.5 yet, and there's no > John> tested Windows executable available, although there's an untested > John> version from a World of Warcraft guild available. > > As Andy Dustman has pointed out a number of times, he doesn't do Windows. > Someone in the MySQLdb community who does use Windows is going to have to > fill that void. ...... well I have managed to build both extant versions (MySQL-python-1.2.1_p2 & MySQL-python-1.2.2b2) from source with the aid of Mr Dustman's comments in the site.cfg files and a very minor hack to the earlier version. I had to have the sources for Mysql available as well, but that probably comes with the territory. It seems the very latest version won't play well with earlier MySQL so I used MySQL-python-1.2.1_p2 as we are still using some 4.0.27 databases. Given that I used a particular version of MySQL, 5.0.33, to build against I'm not certain that my builds are useful for everyone. I copy here the differences I had to make to the source to get stuff to build and run against stock win32 Python-2.5 #############MySQL-python-1.2.1_p2 diff -r -c MySQL-python-1.2.1_p2\_mysql.c \tmp\MySQL-python-1.2.1_p2\_mysql.c *** MySQL-python-1.2.1_p2\_mysql.c Wed Apr 05 18:55:44 2006 --- \tmp\MySQL-python-1.2.1_p2\_mysql.c Fri Jan 26 14:01:49 2007 *************** *** 2767,2772 **** --- 2767,2775 ---- return e; } + #define QUOTE(X) _QUOTE(X) + #define _QUOTE(X) #X + static char _mysql___doc__[] = "an adaptation of the MySQL C API (mostly)\n\ \n\ *************** *** 2801,2811 **** if (!(dict = PyModule_GetDict(module))) goto error; if (PyDict_SetItemString(dict, "version_info", ! PyRun_String(version_info, Py_eval_input, dict, dict))) goto error; if (PyDict_SetItemString(dict, "__version__", ! PyString_FromString(__version__))) goto error; if (PyDict_SetItemString(dict, "connection", (PyObject *)&_mysql_ConnectionObject_Type)) --- 2804,2814 ---- if (!(dict = PyModule_GetDict(module))) goto error; if (PyDict_SetItemString(dict, "version_info", ! PyRun_String(QUOTE(version_info), Py_eval_input, dict, dict))) goto error; if (PyDict_SetItemString(dict, "__version__", ! PyString_FromString(QUOTE(__version__)))) goto error; if (PyDict_SetItemString(dict, "connection", (PyObject *)&_mysql_ConnectionObject_Type)) diff -r -c MySQL-python-1.2.1_p2\site.cfg \tmp\MySQL-python-1.2.1_p2\site.cfg *** MySQL-python-1.2.1_p2\site.cfg Sun Apr 02 18:16:50 2006 --- \tmp\MySQL-python-1.2.1_p2\site.cfg Fri Jan 26 13:48:32 2007 *************** *** 16,28 **** [compiler] #mysql_root: /usr/local/mysql ! #library_dirs: %(mysql_root)s/lib ! #include_dirs: %(mysql_root)s/include ! #libraries: mysqlclient ! # zlib ! # msvcrt ! # libcmt ! # wsock32 ! # advapi32 #extra_compile_args: ! #extra_objects: --- 16,28 ---- [compiler] #mysql_root: /usr/local/mysql ! library_dirs: \tmp\mysql-5.0.33\lib_release ! include_dirs: \tmp\mysql-5.0.33\include ! libraries: mysqlclient ! zlib ! wsock32 ! advapi32 ! #msvcrt ! #libcmt #extra_compile_args: ! extra_objects: /NODEFAULTLIB:MSVCRT #############MySQL-python-1.2.2b2 diff -r -c MySQL-python-1.2.2b2\site.cfg \tmp\MySQL-python-1.2.2b2\site.cfg *** MySQL-python-1.2.2b2\site.cfg Wed Apr 05 02:47:02 2006 --- \tmp\MySQL-python-1.2.2b2\site.cfg Wed Jan 17 15:17:59 2007 *************** *** 16,28 **** [compiler] #mysql_root: /usr/local/mysql ! #library_dirs: %(mysql_root)s/lib ! #include_dirs: %(mysql_root)s/include ! #libraries: mysqlclient ! # zlib ! # msvcrt ! # libcmt ! # wsock32 ! # advapi32 #extra_compile_args: ! #extra_objects: --- 16,28 ---- [compiler] #mysql_root: /usr/local/mysql ! library_dirs: \tmp\mysql-5.0.33\lib_release ! include_dirs: \tmp\mysql-5.0.33\include ! libraries: mysqlclient ! zlib ! wsock32 ! advapi32 ! #msvcrt ! #libcmt #extra_compile_args: ! extra_objects: /NODEFAULTLIB:MSVCRT -- Robin Becker From buffinator at mymail.com Fri Feb 23 17:49:17 2007 From: buffinator at mymail.com (buffinator) Date: Fri, 23 Feb 2007 23:49:17 +0100 Subject: Having multiple instances of a single application start a single instance of another one In-Reply-To: References: <45df6400$0$489$cc7c7865@news.luth.se> Message-ID: <45df6b91$0$487$cc7c7865@news.luth.se> Troy Melhase wrote: >> The first time A starts, it should open a B process and start >> communicating with it. All other times an A instance starts it should >> simply talk with the B that already is open. > > B should write its process id to a location known by both > applications. When A starts, it should read that PID from the file > and attempt to communicate with the process having that PID. > > When B starts, it should also check for the file. If it's found and > if the PID in it is present in the process table, then B should exit. > Otherwise, it should start normally and write its own PID to the file. Three very simple questions then. 1. How do I find out a running applications process ID 2. How do I check if a process ID is bound to a running application. 3. There won't be any issues with different applications trying to read and write the same file doing this? /buffis From B.Ogryczak at gmail.com Fri Feb 2 07:03:58 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 2 Feb 2007 04:03:58 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <1170417838.602781.96220@s48g2000cws.googlegroups.com> On Feb 1, 3:42 am, krypto.wiz... at gmail.com wrote: > How to divide a number by 7 efficiently without using - or / operator. > We can use the bit operators. I was thinking about bit shift operator > but I don't know the correct answer. It?s quiet simple. x == 8*(x/8) + x%8, so x == 7*(x/8) + (x/8 + x%8) x/8 == x>>3, x%8 == x&7 And there you have it, function rounds upwards for numbers not divisible by 7. Gotta change int(x>0) to int(x>3) to round normally, or int(x>6) to round downwards. def d7(x): if(x>>3 == 0): return int(x>0) return (x>>3)+d7((x>>3)+(x&7)) From kleiner at hora-obscura.de Mon Feb 19 06:54:26 2007 From: kleiner at hora-obscura.de (Stefan Palme) Date: Mon, 19 Feb 2007 12:54:26 +0100 Subject: timeout in urllib.open() References: Message-ID: >>> [Peter] >>> I believe this can only be set globally: >>> >>> import socket >>> socket.setdefaulttimeout(seconds) >>> >> [Stefan] >> ... >> But when there is a "default timeout" (as indicated by >> the method name) - isn't there a "per-socket timeout" >> too? > > [Peter] > Yes, but it isn't as easily available... > > Perhaps you find some ideas here: > > http://mail.python.org/pipermail/python-dev/2007-February/070897.html Thanks, will have a look at this. Regards -stefan- From jstroud at mbi.ucla.edu Wed Feb 14 18:12:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 15:12:52 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: skip at pobox.com wrote: > Concatenating tuples and lists seems logical if you think of tuples as > sequences. If you think of them more like Pascal records or C structs > instead (I believe that's Guido's perspective on tuples) then it makes no > sense at all. > > Skip > Then iterating over them makes no sense? James From enleverlesX.XmcX at XmclaveauX.com Mon Feb 5 11:27:57 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 5 Feb 2007 17:27:57 +0100 Subject: Count nb call of a function, without global var or decorator Message-ID: <45c75b0f$0$5090$ba4acef3@news.orange.fr> Hi! Example, with meta-data (attributs of function) : def ff(this): try: this.count=this.count+1 except: this.count=1 a=1 b=2 c=a+b ff(ff) fa=ff ff(ff) fa(fa) print ff.count How to improve that? @-salutations Michel Claveau From bj_666 at gmx.net Sun Feb 4 04:38:56 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 04 Feb 2007 10:38:56 +0100 Subject: Where Does One Begin? References: <1170485721.683685.178470@v33g2000cwv.googlegroups.com> <1170535757.121230.48110@a75g2000cwd.googlegroups.com> Message-ID: In <1170535757.121230.48110 at a75g2000cwd.googlegroups.com>, Eric_Dexter at msn.com wrote: > On Feb 3, 2:16 am, Marc 'BlackJack' Rintsch wrote: >> In <1170485721.683685.178... at v33g2000cwv.googlegroups.com>, >> >> Eric_Dex... at msn.com wrote: >> > pygame is probily a good program to start with as long as you keep in >> > mind that it is possible that up to 50% of the p.c. laptops may not be >> > able to run it. >> >> Huh? Care to explain this? > > This is based on the documentation from panda3d explaining why certain > functions do not work on pc lap tops. Could you point to such documentation? The search function in the online docs doesn't know about "laptop". > The trend in tek is smaller faster exc exc.. based on what they said at > the time of thier documation and I would have to check this certain > functions are not available because of memory of the graphics card??? I > am going by memory and as promised those panda 3d functions do not work > but the program overall is fine. There must be enough memory to display a full screen, obviously, everything else is done in main memory then. And you are talking about panda3d functions and not pygame ones. The OP wanted to write simple 2D games, so it's irrelevant if panda3d doesn't work on some laptops. Claiming pygame doesn't work on about 50% of the laptops out there based on these facts is a bit exaggerated. Ciao, Marc 'BlackJack' Rintsch From skip at pobox.com Sat Feb 3 16:36:03 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 3 Feb 2007 15:36:03 -0600 Subject: Python does not play well with others In-Reply-To: <7xfy9n2pz4.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xejp89pa9.fsf@ruckus.brouhaha.com> <7xfy9n2pz4.fsf@ruckus.brouhaha.com> Message-ID: <17861.67.15833.91112@montanaro.dyndns.org> Paul> Why would I expect your employer to solve my problems anyway, even Paul> if they relate to some module that you actually use? Your reasoning seems to be that Python should contain the functional union of everything at least in Java and PHP if not Perl, Ruby and Tcl as well. Free software or not, each person who contributes to the development of the Python core has to put food on the table. As an example, I suspect most core Java development is funded directly by Sun who pays its employees to develop libraries, JIT compilers and the like. While my employer pays me to program in Python I'm not paid to develop core Python code. What little I do is done on my own time. If you want to turn the Python distribution into a kitchen sink, make the argument on python-dev and be prepared to shoulder your share of the burden should your arguments sway the group as a whole. Skip From Shawn at Milochik.com Thu Feb 8 13:22:40 2007 From: Shawn at Milochik.com (Shawn Milo) Date: Thu, 8 Feb 2007 13:22:40 -0500 Subject: Fwd: Python new user question - file writeline error In-Reply-To: References: <1170876692.167248.244870@s48g2000cws.googlegroups.com> <3a5d609d0702080559u4adf5920k28b1eb61f1d040ac@mail.gmail.com> <2dc0c81b0702080613p32ab3095xc4285c901a5ff0c3@mail.gmail.com> <3a5d609d0702080647y63edde8l80694427b379c96e@mail.gmail.com> <2dc0c81b0702080655o4593fcc2xfabc2fb4704cc7a@mail.gmail.com> <3a5d609d0702080721s3b2fd39cve9078ac56eeb74b8@mail.gmail.com> <2dc0c81b0702080733u2d201885lfed3d1edf47a2c56@mail.gmail.com> <2dc0c81b0702080740g71449de6ic6b82c08d2fa90aa@mail.gmail.com> Message-ID: <2dc0c81b0702081022p2154e8c3n8c03b71eb109ed00@mail.gmail.com> On 2/8/07, Jussi Salmela wrote: > Shawn Milo kirjoitti: > > To the list: > > > > I have come up with something that's working fine. However, I'm fairly > > new to Python, so I'd really appreciate any suggestions on how this > > can be made more Pythonic. > > > > Thanks, > > Shawn > > > > > > > > > > > > > > Okay, here's what I have come up with: > > What follows may feel harsh but you asked for it ;) > > > > > > > #! /usr/bin/python > > > > import sys > > import re > > > > month > > ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > > > > infile=file('TVA-0316','r') > > outfile=file('tmp.out','w') > > > > def formatDatePart(x): > > "take a number and transform it into a two-character string, > > zero padded" > If a comment or doc string is misleading one would be better off without > it entirely: > "take a number": the function can in fact take (at least) > any base type > "transform it": the function doesn't transform x to anything > although the name of the variable x is the same > as the argument x > "two-character string": to a string of at least 2 chars > "zero padded": where left/right??? > > x = str(x) > > while len(x) < 2: > > x = "0" + x > You don't need loops for these kind of things. One possibility is to > replace the whole body with: > return str(x).zfill(2) > > return x > > > > regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") > > > > for line in infile: > > matches = regex.findall(line) > > for someDate in matches: > > > Empty lines are supposed to make code more readable. The above empty > line does the contrary by separating the block controlled by the for > and the for statement > > dayNum = formatDatePart(someDate[1:3]) > > monthNum = formatDatePart(month[someDate[4:7]]) > > yearNum = formatDatePart(someDate[8:12]) > You don't need the formatDatePart function at all: > newDate = ",%4s-%02d-%2s," % \ > (someDate[8:12],month[someDate[4:7]],someDate[1:3]) > > > > newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) > > line = line.replace(someDate, newDate) > > > > outfile.writelines(line) > > > > infile.close > > outfile.close > You have not read the answers given to the OP, have you. Because if you > had, your code would be: > infile.close() > outfile.close() > The reason your version seems to be working, is that you probably > execute your code from the command-line and exiting from Python to > command-line closes the files, even if you don't. > > Cheers, > Jussi > -- > http://mail.python.org/mailman/listinfo/python-list > Jussi, Thanks for the feedback. I received similar comments on a couple of those items, and posted a newer version an hour or two ago. I think the only thing missing there is a friendly blank line after my "for line in infile:" statement. Please let me know if there is anything else. Shawn From horpner at yahoo.com Wed Feb 14 14:22:03 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 14 Feb 2007 19:22:03 GMT Subject: multiple inheritance of a dynamic list of classes? References: <1171295313.109446.281410@j27g2000cwj.googlegroups.com> <1171326403.786021.203490@k78g2000cwa.googlegroups.com> <1171360113.585827.17440@v45g2000cwv.googlegroups.com> Message-ID: On 2007-02-14, Peter Otten <__peter__ at web.de> wrote: > Neil Cerutti wrote: > >> On 2007-02-13, Peter Otten <__peter__ at web.de> wrote: >>> Well, what problems ocurring with >>> >>> class A: pass >>> class B: pass >>> class C(A, B): pass >>> >>> could be avoided by writing >>> >>> class A: pass >>> class B(A): pass >>> class C(B): pass >>> >>> instead? >> >> With multiple inheritance, the choice of algorithm for Method >> Resolution Ordering isn't obvious or trivial. As I understand it, >> Python got it wrong for quite some time, allowing "bad" >> hierarchies to compile, i.e., classes for which the properties of >> local precedence ordering and monotonicity did not hold. >> >> URL:http://www.python.org/download/releases/2.3/mro/ > > Is it correct that as long as no classes occur twice in the > hierarchy no such ambiguities can arise? As long as you forbid the diamond-shaped hierarchy, I think so. Of course, since all new-style classes inherit from 'object' you can't avoid it in practice, and a good algorithm for MRO had to be stolen from Dylan. ;) -- Neil Cerutti From hg at nospam.org Sat Feb 10 08:07:57 2007 From: hg at nospam.org (hg) Date: Sat, 10 Feb 2007 14:07:57 +0100 Subject: wxPython libraries never detected References: <1171122904.981749.322260@h3g2000cwc.googlegroups.com> Message-ID: d.lidell at gmail.com wrote: > Hi, I recently started coding with Python and I've been trying for the > past hour or so to determine why, every time I "import wx" (or compile > another piece of code that imports wx), Python can never find the > libraries. > > I'm running Ubuntu Edgy 6.10, and, as per > http://www.wxpython.org/download.php#sources, updated sources.list with > the sources and installed python-wxgtk2.8, python-wxtools and wx2.8-i18n. > I compiled the latest Python (as of writing), 2.5, from source. > > For example, SPE tells me that I "need to install at least wxPython v. > 2.5.4.1 to run SPE" and any code that relies on "import wx" reports > "ImportError: No module named wx". However, "whereis wx" on the > command line reports "wx: /usr/lib/wx /usr/local/lib/wx /usr/include/ > wx". What could be wrong here? I can't figure out why wx isn't being > detected. > > Many thanks. By default, you need to have wx installed in the python site-package path / under Mandriva, I have wx 2.8 installed here: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-ansi/ hg From troy.melhase at gmail.com Wed Feb 28 00:27:56 2007 From: troy.melhase at gmail.com (troy.melhase at gmail.com) Date: 27 Feb 2007 21:27:56 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172637721.119848.188380@a75g2000cwd.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> Message-ID: <1172640476.259853.245530@8g2000cwh.googlegroups.com> > Hi Jeremy, that's the problem I'm having. Where should I type that " > python setup.py install" ? Once again I'm using Windows system and not > Unix. Should I move the file to a specific folder under Python 2.5 and > then type " python setup.py install" in IDLE or Command Line window? > I get the error "SyntaxError: invalid syntax" with the word "setup" hi andy, you want to run the windows command prompt, which is called "cmd.exe" in windows xp. press the "start menu", then select "run", then type "cmd.exe" without the quotes. a window will pop up that looks black, and it will have a prompt like "C:\" or "D:\something". with this window, you need to type several commands. the first command is "cd", which changes the working directory. you'll want to type the name of the drive and folder where you extracted the j2py package. this can be anywhere, and it doesn't have to be in your python folders. example: C:\> cd D:\temp\java2python-0.2 next, you'll need to run the setup script with python. you can test for python at the prompt like this: D:\temp\java2python-0.2\> python -V if you get "Python 2.5", you're ready to run the script. if you don't get that, or if you get something along the lines of "command not found", then you'll have to qualify the command with the full path to the 2.5 interpreter. for example: D:\temp\java2python-0.2\> C:\Python2.5\python.exe -V i don't know where you installed python, nor do i remember much about how the windows installation layout, so you'll have to figure out these paths on your own. once you get the "Python 2.5" response, you can install the package. this is the easy part. use whatever command you got to reply "Python 2.5", enter it again, along with a space followed by "setup.py install" (again, no quotes). continuing the example above: D:\temp\java2python-0.2\> C:\Python2.5\python.exe setup.py install you should read all of the output closely -- look for errors. you might have problems installing the software if you're not an administrator. if you don't have problems, the setup process will have copied a script named "j2py" somewhere in your system path. try "j2py -- version", and if everything works, you'll get the reply "j2py 0.2". once the script is installed, change to the directory of your java files (using "cd"), then do something like this, substituting your file names where appropriate: D:\myjavafiles\> j2py -i someclass.java -o someclass.py best of luck to you, and please do let me (or the group) know how everything works out. From http Thu Feb 1 12:16:29 2007 From: http (Paul Rubin) Date: 01 Feb 2007 09:16:29 -0800 Subject: Question about a single underscore. References: Message-ID: <7x8xfh4x3m.fsf@ruckus.brouhaha.com> "Steven W. Orr" writes: > ------------------><8------------------- const.py------------- > ... > sys.modules[__name__]=_const() __name__ is 'const' since this file is const.py. So you've juset set the const module to actually be a const instance. > 1. Why do I not have to say > _const.pi = 3.14159 const.pi refers to item 'pi' in the const module, which you've set in sys.modules above. > 2. Can I make this behave in such a way that I can create my constants > with a classname that is different for different uses? e.g., > irrational_const.pi = 3.14159 Yes, irrational_const = _const() From bdesth.quelquechose at free.quelquepart.fr Sun Feb 4 16:19:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Feb 2007 22:19:55 +0100 Subject: Definitions of editor and IDE? In-Reply-To: References: <20070203224824.0CC7C1E400A@bag.python.org> Message-ID: <45c646f0$0$21118$426a34cc@news.free.fr> Necmettin Begiter a ?crit : > 04 ?ub 2007 Paz 00:48 tarihinde, Dick Moores ?unlar? yazm??t?: > >> Are there generally accepted definitions of "editor" and "IDE". Is there a >>clear-cut distinction between them? I've been looking at the lists of each >>at python.org, < http://wiki.python.org/moin/PythonEditors> and < >>http://wiki.python.org/moin/IntegratedDevelopmentEnvironments>. Many >>programs are on both lists: Komodo, Eclipse, jedit, SPE, Wing IDE, UliPad, >>etc. >> >> Dick Moores > > Can't give definitions, but here is the difference: if you use an editor, you > will have to run your script or program from outside the editor; if you use > an IDE, you will press a key or key combination in the IDE (say F9 or F5) and > your program/script will run... In which case Emacs is an IDE - while it's usually descibed as an editor... IDE stands for "Integrated Development Environment". Since one of the central tasks in development is editing code, IDEs are usually built around the editor. From spammers-die at spam.microsoft.com Thu Feb 8 15:06:36 2007 From: spammers-die at spam.microsoft.com (John McCallum) Date: Thu, 08 Feb 2007 20:06:36 +0000 Subject: python linux distro References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: Hiya, > last night i was lying in my bed and thinking about something. is > there any linux distro that is primary oriented to python. Well, it's a general purpose distro, but Gentoo (www.gentoo.org) relies on Python as it's package management system is written in Python & Bash. most python things I use are available, but scipy is masked at the moment (this means that there is a problem with the package - you can normally use masked packages, but at your own risk ;). Also, it should be noted that unlike most other distro's, Gentoo is a source distro: the package system downloads and builds for your system and so you can set global preferences, such as the optimisation level or processor support. It just takes a few CPU more cycles to upgrade things. HTH, John McCallum From edreamleo at charter.net Fri Feb 16 10:07:02 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Feb 2007 09:07:02 -0600 Subject: Pep 3105: the end of print? References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171629096.256958.213180@q2g2000cwa.googlegroups.com> <1171632839.412221.274200@s48g2000cws.googlegroups.com> Message-ID: >> That's the proof. Can you find a flaw in it? > No, but it doesn't matter. There's no particular reason why you have to > write "print (whatever)" in your code. What you need is *some function* > that is capable of duplicating the functionality of print, Precisely wrong. The title of this thread is 'the end of print', and the whole point of my comments is that spelling matters. I would have absolutely no objection to the pep if it specified some other name for an 'official' print function. Pick any name, preferably longer than two characters, that does not conflict with either an existing global function or module. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From spe.stani.be at gmail.com Sat Feb 24 19:36:33 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 24 Feb 2007 16:36:33 -0800 Subject: What happened to SPE? In-Reply-To: <1l3xeojrs48dh.dlg@zabiello.com> References: <1l3xeojrs48dh.dlg@zabiello.com> Message-ID: <1172363793.033467.235700@j27g2000cwj.googlegroups.com> On Feb 3, 2:18 am, Jaroslaw Zabiello wrote: > Dnia 11 Jan 2007 17:02:49 +0100, Neil Cerutti napisa?(a): > > >SPElost its web host, and last I heard is looking for a new > > home. For now you can get it here: > > > http://sourceforge.net/projects/spe/ > > That is old addres. Never ishttp://developer.berlios.de/projects/python/ > > -- > Jaroslaw Zabiellohttp://blog.zabiello.com SPE will restart. Follow it on http://pythonide.stani.be Stani From reid at reidster.net Thu Feb 1 20:53:31 2007 From: reid at reidster.net (Reid Priedhorsky) Date: Thu, 01 Feb 2007 19:53:31 -0600 Subject: A* search implementation in Python Message-ID: Hi folks, I'm looking for an open-source Python implementation of A* search for use in a mapping application. As the star is an operator in Google, I haven't figured out how to formulate a useful search. :/ Any help would be very much appreciated. Reid From martin at v.loewis.de Thu Feb 22 13:09:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 22 Feb 2007 19:09:03 +0100 Subject: unicodedata implementation In-Reply-To: References: <23fce8e60702151556v8e99633w65721740c194d88d@mail.gmail.com> Message-ID: <45DDDC3F.7020107@v.loewis.de> James Abley schrieb: > So from my understanding of the Unicode (3.2.0) spec, the code point > 0x325F has a numeric property with a value of 35, but the python (2.3 > and 2.4 - I haven't put 2.5 onto my box yet) implementation of > unicodedata disagrees, presumably for good reason. > > I can't see where I'm going wrong. You might not be wrong at all. CPython has a hard-coded list for the numeric mapping (see Object/unicodectype.c), and that hadn't been updated even when the rest of the character database was updated. Patch #1494554 corrected this and updated the numeric properties to Unicode 4.1, for Python 2.5. There is still a patch pending generating this function, instead of maintaining it manually. HTH, Martin From http Fri Feb 16 14:32:31 2007 From: http (Paul Rubin) Date: 16 Feb 2007 11:32:31 -0800 Subject: f---ing typechecking References: <17876.32824.293063.624185@montanaro.dyndns.org> <003401c75140$761f0650$5138d953@notebook> <7xr6srgm3c.fsf@ruckus.brouhaha.com> <7xfy97uhv0.fsf@ruckus.brouhaha.com> Message-ID: <7xfy956gq8.fsf@ruckus.brouhaha.com> Donn Cave writes: > Unpredictable? How do you manage to write functions in this case? > Are all your formal parameter lists like (*a), with logic to deal > with the variable lengths? I'm thinking of functions like printf, which take a variable number of args and don't assign them into variables by position. From vlapi at att.com Thu Feb 8 08:37:58 2007 From: vlapi at att.com (LAPI, VINCENT J, ATTLABS) Date: Thu, 8 Feb 2007 08:37:58 -0500 Subject: Simple Interpolation in Numpy? Message-ID: <134863FF4EA9A54E8EC307A2F4214566096E0E51@ACCLUST01EVS1.ugd.att.com> Hi, Please bear with me as I am new to Python and have not done any programming in about 20 years. I am attempting to do a simple interpolation of a line's intermediate points given the x,y coordinates of the line's two endpoints within an Active State Python script that I am working with. Is there a simple way to do this simple interpolation in the Active state Python 2.4 that I have or do I need to get Numeric Python? And where do I get it? Thanks, Vince Lapi -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at designaproduct.biz Wed Feb 21 08:30:43 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 21 Feb 2007 14:30:43 +0100 Subject: metaclasses (beginner question) Message-ID: <45DC4983.90305@designaproduct.biz> Hello, I would like to create a hierarchy classes, where the leaves have a special attribute called "producer_id". In addition, I would like to have a function that can give me back the class assigned to any producer_id value. I tried to implement this with a metaclass, but I failed. Please help me, what I did wrong? Thanks, Laszlo class ProducerHandlerType(type): producer_handlers = {} @classmethod def registerProducerHandler(cls,producer_id): ph = cls.producer_handlers if ph.has_key(producer_id): ccls = ph[producer_id] raise Exception("This producer already has a calculator: "+str(ccls)) else: print "Registering "+str(cls)+" for producer_id=",producer_id ph[producer_id] = cls def __init__(cls,name,bases,dct): super(ProducerHandlerType,cls).__init__(cls,name,bases,dct) if hasattr(cls,'producer_id'): cls.registerProducerHandler(getattr(cls,'producer_id')) else: print "No producer_id for ",str(cls) class A(ProducerHandlerType): pass class B(A): producer_id = 1 class C(A): producer_id = 2 # Metaclass methods are not called above, and the line below prints an empty dict. :-( print B.producer_handlers From pythonnews at nospam.jmbc.fr Thu Feb 8 15:24:32 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Thu, 08 Feb 2007 21:24:32 +0100 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170939698.599843.232030@j27g2000cwj.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> <1170939698.599843.232030@j27g2000cwj.googlegroups.com> Message-ID: <45cb872a$0$21146$7a628cd7@news.club-internet.fr> > On the OSS side, SPE is very good too - more of an IDE than Komodo > Edit. DrPython is worth a look as is the similar Ulipad. Also have a > look at Boa. > Boa is excellent if you plan to use wxwidgets. Regards jm From moin at blackhole.labs.rootshell.ws Wed Feb 7 18:48:43 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Wed, 7 Feb 2007 17:48:43 -0600 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com><1170872694.018720.301410@m58g2000cwm.googlegroups.com> Message-ID: <004d01c74b12$81c16c20$e9936540@cisco.com> I would like to add my problem in this thread. I have a network application in Python which sends and recv using a single socket. There is a dictionary on which I store/read data values. I want to seperate the send and recv functionality on two different processes so that the parallel execution becomes fast. Is there any way to do so, so that the Dict's consitency is not lost(able to read & write) and also the performance improves. I am looking upon the MPI4Py module to see if it does the job for me. Any ideas would be appreciated. ----- Original Message ----- From: "Sergei Organov" To: Sent: Wednesday, February 07, 2007 1:03 PM Subject: Re: multithreading concept > "sturlamolden" writes: >> On Feb 7, 6:17 pm, John Nagle wrote: > [...] >> MPI does not use threads on SMPs because it performs worse than using >> multiple processes. > > I fail to see how threads in general could perform worse than > processes. I do understand that processes are inherently more > safe/secure, but when it comes to speed I really can't imagine why it > could happen that threads perform worse (poor threads implementation and > programming practices aside). Care to give some references? > > -- Sergei. > > -- > http://mail.python.org/mailman/listinfo/python-list From ccw.thomas at gmail.com Wed Feb 28 10:48:15 2007 From: ccw.thomas at gmail.com (ThomasC) Date: 28 Feb 2007 07:48:15 -0800 Subject: The Python interactive interpreter has no command history In-Reply-To: References: <1171991560.901546.8280@v45g2000cwv.googlegroups.com> Message-ID: <1172677695.004263.98820@q2g2000cwa.googlegroups.com> On 2?16?, ??1?14?, "Eduardo \"EdCrypt\" O. Padoan" wrote: > > Hello, > > > How to configure Python2.5's interactive interpreter to get command > > history ? > > > I always got ^[[A and ^[[B . > > Are you using Ubuntu? The last comes with 2.4.x and 2.5. This only > occurs on 2.5. This happens when you compile Python with libreadline > installed, AFAIK. > FIll a bug in the Ubuntu launchpad. You can install libreadline (and > build-essential), download the 2.5 source and compile yourself. > > -- > EduardoOPadoan (eopadoan->altavix::com) > Bookmarks:http://del.icio.us/edcrypt I have fixed this issue by recompile python2.5 with libreadline and libncursesw. I run python on Zaurus, but Zaurus toolchain has no readline and ncursesw libraries, so I add those libraries. I have posted my experience on http://bean-pig.idv.tw/emb_study/archives/001059.html Thanks a lot!! From chadrik at gmail.com Thu Feb 15 21:57:29 2007 From: chadrik at gmail.com (chadrik at gmail.com) Date: 15 Feb 2007 18:57:29 -0800 Subject: IOError: [Errno 4] Interrupted system call In-Reply-To: References: Message-ID: <1171594649.279210.139470@l53g2000cwa.googlegroups.com> i'm getting the same error when trying to read results from popen2 within a pyQt window. is this a threading issue? is my pyQt window responsible for interrupting the read? i'm fairly new to python so i'm struggling to figure this out. can you recommend any possible methods of preventing this? for instance, could acquiring a thread lock before calling popen solve the problem? thanks, chad From horpner at yahoo.com Thu Feb 22 09:27:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 22 Feb 2007 15:27:28 +0100 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172105179.708565.201600@v33g2000cwv.googlegroups.com> Message-ID: On 2007-02-22, Jussi Salmela wrote: > Steven D'Aprano kirjoitti: >> On Wed, 21 Feb 2007 16:46:19 -0800, Harlin Seritt wrote: >> >>>> WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM. It is just a >>>> nuisance for someone that really wants to decrypt the string. But >>>> it might work for your application. >>>> >>>> -Larry >>> Thanks Larry! I was looking for something more beautiful but what the >>> hey, it works! >> >> >> Is this beautiful enough? >> >> >>>>> s = "Python" >>>>> u = unicode(s, "ascii") >>>>> u >> u'Python' >>>>> u.encode('rot13') >> 'Clguba' >> >> >> For extra security, you can encode the string with rot13 twice. >> >> >> > > Like this? ;) > > >>> s = "Python" ; u = unicode(s, "ascii") ; u > u'Python' > >>> u.encode('rot13') > 'Clguba' > >>> u.encode('rot13').encode('rot13') > 'Python' Woah! You better quadruple it instead. How about Double Pig Latin? No, wait! Use the feared UDPLUD code. You go Ubbi Dubbi to Pig Latin, and then Ubbi Dubbi again. Let's see here... Ubububythubububonubpubay That's what I call ubububeautubububifubububulbubay. -- Neil Cerutti This is not a book to be put down lightly. It should be thrown with great force. --Dorothy Parker From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 18:13:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Feb 2007 00:13:43 +0100 Subject: lambda functions ? In-Reply-To: References: Message-ID: <45c7b311$0$32371$426a74cc@news.free.fr> Maxim Veksler a ?crit : > Hello, > I'm new on this list and in python. Welcome on board... > It seems python has some interesting concept of "ad hoc" function > which I'm trying to understand without much success. > > Take the following code for example: > > """ > >>>> def make_incrementor(n): > > ... return lambda x: x + n > ... > >>>> f = make_incrementor(42) >>>> f(0) > > 42 > >>>> f(1) > > 43 > """ > > I really don't understand whats going on here. > On the first instantiating of the object "f" where does "x" gets it's > value? Nowhere. The above code is strictly equivalent to: def make_incrementor(n): def inc(x): return x + n return inc It's based on the fact that (for short): 1/ Python functions are first-class objects, and as such can be passed around just like any other object 2/ Python functions are closures, meaning they carry the environment in which they where defined. IOW, make_incrementor(n) creates and returns a new function each time it's called. This function remembers the value of n with which it was created, and just awaits to be called with the missing x arg. Or is it evaluated as 0? ie "x: 0 + 42" > > And what is the "f" object? An integer? a pointer? an Object? an object, instance of class function. > I'm coming from the C world... > > Could some please try (if even possible) to implement the above code > without using "lambda" I believe it would help me grasp this a bit > faster then. cf above. FWIW, lambda is just a syntactic sugar for creating anonymous, dead-simple functions, usually used as callbacks for generic functions or methods like map, filter, list.sort etc. FWIW(2), this programming style (anonymous functions, closures etc) comes from functional programming (Haskell, ML, lisp, etc...). > Thank you, HTH From kristnjov at nospam.com Mon Feb 12 07:44:29 2007 From: kristnjov at nospam.com (Deniz Dogan) Date: Mon, 12 Feb 2007 13:44:29 +0100 Subject: string.replace non-ascii characters In-Reply-To: References: Message-ID: Duncan Booth wrote: > "Gabriel Genellina" wrote in triplicate: > >> If I were paid for the number of lines *written* that would not be a >> great deal :) > > You don't by any chance get paid by the number of posts to c.l.python? I was thinking the same thing. From boris.smirnov at gmail.com Tue Feb 27 05:29:57 2007 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 27 Feb 2007 02:29:57 -0800 Subject: QPaintDevice: Must construct a QApplication before a QPaintDevice Message-ID: <1172572196.954309.230560@h3g2000cwc.googlegroups.com> Hi all, I have a python script that works without any problem on Windows but with error: QPaintDevice: Must construct a QApplication before a QPaintDevice on Linux. Where could be the problem? Thanks. Boris From steve at REMOVE.THIS.cybersource.com.au Tue Feb 20 07:57:34 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 20 Feb 2007 23:57:34 +1100 Subject: Bypassing __setattr__ for changing special attributes References: <1171946368.994287.131980@a75g2000cwd.googlegroups.com> <1171955882.929647.86700@v33g2000cwv.googlegroups.com> Message-ID: On Mon, 19 Feb 2007 23:18:02 -0800, Ziga Seilnacht wrote: > George Sakkis wrote: >> I was kinda surprised that setting __class__ or __dict__ goes through >> the __setattr__ mechanism, like a normal attribute: >> >> class Foo(object): >> def __setattr__(self, attr, value): >> pass >> >> class Bar(object): >> pass >> >> >>> f = Foo() >> >>> f.__class__ = Bar >> >>> print f.__class__ is Foo >> True >> >> Is there a way (even hackish) to bypass this, or at least achieve >> somehow the same goal (change f's class) ? >> >> George > >>>> object.__setattr__(f, '__class__', Bar) >>>> f.__class__ is Bar > True This version is arguably more "correct", although a tad longer to write, and doesn't need you to hard-code the class superclass: super(f.__class__, f).__setattr__('__class__', Bar) But what surprised me was that this *didn't* work: >>> f = Foo() >>> f.__dict__['__class__'] = Bar >>> f.__class__ Unless I'm confused, it looks like instance.__class__ bypasses the usual lookup mechanism (instance.__dict__, then instance.__class__.__dict__) for some reason. >>> Foo.x = 1 # stored in class __dict__ >>> f.x 1 >>> f.__dict__['x'] = 2 # stored in instance __dict__ >>> f.x 2 >>> Foo.x 1 But __class__ doesn't behave like this. Why? -- Steven. From skip at pobox.com Thu Feb 1 16:02:52 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Feb 2007 15:02:52 -0600 Subject: division by 7 efficiently ??? In-Reply-To: <000001c74642$b95a57c0$0d7d12ac@kearfott.com> References: <1170361512.204099.191740@a75g2000cwd.googlegroups.com> <000001c74642$b95a57c0$0d7d12ac@kearfott.com> Message-ID: <17858.21884.241901.810016@montanaro.dyndns.org> Michael> I think it is off by 1 in small numbers, off by a little more Michael> with large numbers: ... Sorta makes you think using the DIV instruction in the CPU is the way to go. ;-) Skip From ptmcg at austin.rr.com Thu Feb 15 02:53:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 Feb 2007 23:53:47 -0800 Subject: f---ing typechecking In-Reply-To: References: Message-ID: <1171526027.568047.186800@v33g2000cwv.googlegroups.com> Since tuples are immutable, I think of them as fixed data objects with some simple sequential structure, as opposed to lists which are much more dynamically accessible/updateable data containers. Back in my relational database design days, I sometimes had to create a primary key for a table by combining values stored in two or more columns - neither column value alone was unique, but the combination of them was, and so made a good retrieval index. In Python, such data pairs would be ideally represented with tuples, in support of in-memory data cacheing or tree indexing - for a given record, the values don't change, so the immutability of their tupleness doesn't get in the way. In similar vein, I've used tuples internally in my Python code as cache keys for function memoizing. They are WORM structures - write once, read many - built to represent the cache value, but never updated. With this idea of tuples as a data structure, I could reasonably interpret this: (1,"abc",3) + [1] to result in (1,"abc",3,[1]) just as well as (1,"abc",3,1). But instead of just picking one, Python complains about this, and so forces me to explicitly use (1,"abc",3) + tuple([1]) or (1,"abc",3) + ([1],) I don't think tuples are just an academic curiosity, as your post seems to suggest. -- Paul From tim at tdw.net Tue Feb 20 15:26:28 2007 From: tim at tdw.net (Tim Williams) Date: Tue, 20 Feb 2007 20:26:28 +0000 Subject: Sorting directory contents In-Reply-To: References: Message-ID: <9afea2ac0702201226i2cd60f20le17749e89e8d70@mail.gmail.com> On 20/02/07, Wolfgang Draxinger wrote: > H folks, > > I got, hmm not really a problem, more a question of elegance: > > In a current project I have to read in some files in a given > directory in chronological order, so that I can concatenate the > contents in those files into a new one (it's XML and I have to > concatenate some subelements, about 4 levels below the root > element). It all works, but somehow I got the feeling, that my > solution is not as elegant as it could be: > > src_file_paths = dict() > for fname in os.listdir(sourcedir): > fpath = sourcedir+os.sep+fname > if not match_fname_pattern(fname): continue > src_file_paths[os.stat(fpath).st_mtime] = fpath > for ftime in src_file_paths.keys().sort(): > read_and_concatenate(src_file_paths[ftime]) > > of course listdir and sorting could be done in a separate > function, but I wonder if there was a more elegant approach. > > Wolfgang Draxinger > -- > E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 Are you running on windows? >>> i,o,e = os.popen3("dir c:\windows /OD /A-D /B") >>> [x.strip() for x in o.readlines() if 'a' in x ] Gives a list of filenames (but not directories) in date order, that match a pattern ('a' in x) >>> i,o,e = os.popen3("dir c:\windows /O-D /A-D /B") >>> [x.strip() for x in o.readlines() if 'a' in x] Gives the same list but in reverse chronological order. Something containing an approximation of my poor-writing style below would do the job. >>> i,o,e = os.popen3("dir c:\windows /OD /A-D /B") >>> [os.path.join(a_path, x.strip()) for x in o.readlines() if match_fname_pattern(x)] ['c:/windows/NeroDigital.ini', 'c:/windows/WindowsUpdate.log', 'c:/windows/setupapi.log', 'c:/windows/wiadebug.log', 'c:/windows/wiaservc.log' .................................... c:\> Dir /? will give you more help HTH :) From mail at timgolden.me.uk Mon Feb 26 11:07:44 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Feb 2007 16:07:44 +0000 Subject: ez_setup.py In-Reply-To: <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> References: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> <6681a$45e300f3$9117fe9b$11548@news1.tudelft.nl> Message-ID: <45E305D0.4010806@timgolden.me.uk> Nader Emami wrote: > Tim Golden wrote: >> Nader Emami wrote: >>> L.S., >>> >>> I have installed locally Python-2.4.4 without any problem. Then I >>> would install the "ez_setup.py" to be able using of "easy_install" >>> tool, but I get the next error: >>> >>> %python ez_setup.py >>> Traceback (most recent call last): >>> File "ez_setup.py", line 223, in ? >>> main(sys.argv[1:]) >>> File "ez_setup.py", line 155, in main >>> egg = download_setuptools(version, delay=0) >>> File "ez_setup.py", line 111, in download_setuptools >>> import urllib2, shutil >>> File "/usr/people/emami/lib/python2.4/urllib2.py", line 108, in ? >>> import cookielib >>> File "/usr/people/emami/lib/python2.4/cookielib.py", line 35, in ? >>> from calendar import timegm >>> File "/usr/people/emami/calendar.py", line 23, in ? >>> import pygtk >>> ImportError: No module named pygtk >>> >>> I don't understand what is the problem! Could somebody tell me what I >>> have to do to solve it? >> >> You have a module called "calendar" in your user directory >> /usr/people/emami/calendar.py which is shadowing the stdlib >> calendar module -- which doesn't get used much so you've >> probably never noticed. Either rename your local one or take >> your home folder off the Python path... at least for long enough >> for ez_setup to do its stuff. >> >> TJG > How can do the second solution, (take off the home from Python path)? Depends on your setup. Since you're on *nix, I can't test whether $HOME is automatically on sys.path (it isn't on Win32). Are you running *in* /usr/people/emami? If so, go somewhere else before you run ez_setup. Check your PYTHONPATH env var; perhaps reset it before running ez_setup. There are other more obscure possibilities to do with things set in site.py but they're less likely. TJG From steve at holdenweb.com Thu Feb 15 13:34:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Feb 2007 18:34:16 +0000 Subject: TKinter newbie In-Reply-To: References: Message-ID: Gigs_ wrote: > Hi Im new to gui programming > > from Tkinter import * # get widget classes > from tkMessageBox import askokcancel # get canned std dialog > > class Quitter(Frame): # subclass our GUI > def __init__(self, parent=None): # constructor method > Frame.__init__(self, parent) > self.pack() > widget = Button(self, text='Quit', command=self.quit) > widget.pack(side=LEFT) > def quit(self): > ans = askokcancel('Verify exit', "Really quit?") > if ans: Frame.quit(self) > > class Demo(Frame): > def __init__(self, parent=None): > Frame.__init__(self, parent) > self.pack() > Label(self, text="Basic demos").pack() > for (key, value) in demos.items(): > func = (lambda key=key: self.printit(key)) > Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) > Quitter(self).pack() # here > def printit(self, name): > print name, 'returns =>', demos[name]() > > > My problem is in class Demo. How is the best way to use class Quitter in > class Demo? > should it be: > Quitter(self).pack() > Quitter(self) > ... The Quitter really needs to Destroy its parent, so you will need to have something like self.parent = parent in the __init__() method to keep a reference to the parent frame. Then the quit() method can call self.parent.destroy() which will also result in the destruction of the child Quitter. In this particular case you don't appear to need a reference to the Quitter object in the main Frame's code, so it's acceptable to use Quitter(self).pack() However in the more general case yo umight want to be abel to refer to some subsidiary object in the Frame's methods, and in that case the easiest way to do so is to save that reference when you create the object, than pack the obejct separately, as in self.quitter = Quitter(self) self.quitter.pack() Here's a simple program to show you the difference between quit() and destroy(). You will notice that you have to press the Quit button twice, but the Destroy button only once - once the window is destroyed calling its mainloop() method no longer does anything. from Tkinter import * t = Tk() Button(t, command=t.quit, text="Quit").pack() Button(t, command=t.destroy, text="Destroy").pack() t.mainloop() t.mainloop() regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gagsl-py at yahoo.com.ar Sat Feb 10 20:55:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Feb 2007 22:55:43 -0300 Subject: Python 2.4 pdf Tutorial--Available References: <1hpzh.5885$4H1.5133@newssvr17.news.prodigy.net> Message-ID: En Sat, 10 Feb 2007 21:20:43 -0300, W. Watson escribi?: > Gabriel Genellina wrote: >> En Sat, 10 Feb 2007 16:45:08 -0300, W. Watson >> escribi?: >> >>> I was able to download the 2.5 tutorial, but think I may need the 2.4 >>> tutorial (Guido van Rossum) if it exists. Anyone know where to find it? >> >> Go to http://docs.python.org/ and follow the link "Locate previous >> versions" >> > Thanks. Found the 2.4 Python Tutorial web page by Guido van Rossum, but > would like the pdf. Go to http://docs.python.org/ Click on "Locate previous versions" Click on "Python 2.4.4" (latest release on the 2.4 series) Click on "Download all these documents" Choose your format (PDF), page size (PDF A4 or PDF Letter), and your favorite compression format (Zip or bzip2) and download it. You get the whole documentation in the chosen format, not only the tutorial. On that same page, it says: "These documents are not available for download individually." -- Gabriel Genellina From gagsl-py at yahoo.com.ar Mon Feb 5 18:38:34 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Feb 2007 20:38:34 -0300 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Message-ID: En Sat, 03 Feb 2007 14:25:31 -0300, Stef Mientki escribi?: > Is it possible to change the searchpath for modules on the flight, > under winXP ? > Most preferred is some command to extend the searchpath. > (the environment variable PYTHONPATH needs a reboot) PYTHONPATH is used to build the initial contents of sys.path, which is the actual list of directories searched. It's a standard list object so you can modify it easily. -- Gabriel Genellina From jeffwatkins2000 at gmail.com Wed Feb 28 11:13:42 2007 From: jeffwatkins2000 at gmail.com (jeffwatkins2000 at gmail.com) Date: 28 Feb 2007 08:13:42 -0800 Subject: Eric on XP for Newbie Message-ID: <1172679222.026525.248430@a75g2000cwd.googlegroups.com> I'm starting on the path of freeing myself from proprietory software but I need to migrate, not make one huge jump. I'm looking at using Python and Eric for programming I've got Python up and running but can someone please point me to a simple step by step guide for installing Eric? I've downloaded the tar files, but what do I do with them? Thanks From chenying3176 at gmail.com Mon Feb 5 02:10:29 2007 From: chenying3176 at gmail.com (yc) Date: 4 Feb 2007 23:10:29 -0800 Subject: subprocess stdin encoding Message-ID: <1170659429.228953.52200@q2g2000cwa.googlegroups.com> I have a encoding problem during using of subprocess. The input is a string with UTF-8 encoding. the code is: tokenize = subprocess.Popen(tok_command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,close_fds=True,shell=True) (tokenized_text,errs) = tokenize.communicate(t) the error is: File "/usr/local/python/lib/python2.5/subprocess.py", line 651, in communicate return self._communicate(input) File "/usr/local/python/lib/python2.5/subprocess.py", line 1115, in _communicate bytes_written = os.write(self.stdin.fileno(), input[:512]) UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 204: ordinal not in range(128) How I change the default encoding from "ascii" to "utf-8"? Ying Chen From eopadoan at altavix.com Thu Feb 8 10:50:52 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Thu, 8 Feb 2007 13:50:52 -0200 Subject: idea for testing tools In-Reply-To: <8764adm2jw.fsf@arcor.de> References: <87ejp1mzla.fsf@arcor.de> <45ca5f5a$0$26771$426a74cc@news.free.fr> <8764adm2jw.fsf@arcor.de> Message-ID: > #!/usr/bin/python > > a = 1 > b = 2 > > def test_some(): > assert a == b > > didn't reveal the values for a and b, though some more complex cases > showed something. def test_some(): print 'a:', a, 'b:', b assert a == b http://codespeak.net/py/current/doc/test.html#debug-with-the-print-statement -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com From george.sakkis at gmail.com Fri Feb 2 20:14:46 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 2 Feb 2007 17:14:46 -0800 Subject: Where Does One Begin? In-Reply-To: References: Message-ID: <1170465286.881096.262380@v33g2000cwv.googlegroups.com> On Feb 2, 3:39 pm, Mister Newbie wrote: > I have no programming experience. I want to learn Python so I can make > simple, 2D games. Where should I start? Can you recommend a good book? > > Thank you. http://www.amazon.com/Game-Programming-Python-Development/dp/1584502584 From sjmachin at lexicon.net Tue Feb 20 08:08:30 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2007 05:08:30 -0800 Subject: Weird result returned from adding floats depending on order I add them In-Reply-To: References: Message-ID: <1171976910.217520.53970@l53g2000cwa.googlegroups.com> On Feb 20, 11:29 pm, "joanne matthews (RRes-Roth)" wrote: > I'm getting different results when I add up a list of floats depending > on the order that I list the floats. This is quite expected. Floating point arithmetic is subject to rounding errors. [doesn't add to 1.0] > inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1] > > However, if I swap, the 4th and 5th list items like this: > > inputs=[0.2,0.2,0.2,0.2,0.1,0,0.1] [adds to 1.0] What is happening: print repr(whatever_you_are_puzzled_by) is a Very Good Idea (TM). >>> a = [0.2, 0.2, 0.2, 0.1, 0.2, 0.1] >>> b = [0.2, 0.2, 0.2, 0.2, 0.1, 0.1] >>> sum(a) 1.0000000000000002 >>> sum(b) 1.0 >>> tot = 0.0 >>> for x in a: ... tot += x ... print repr(x), repr(tot) ... 0.20000000000000001 0.20000000000000001 0.20000000000000001 0.40000000000000002 0.20000000000000001 0.60000000000000009 0.10000000000000001 0.70000000000000007 0.20000000000000001 0.90000000000000013 0.10000000000000001 1.0000000000000002 >>> tot = 0.0 >>> for x in b: ... tot += x ... print repr(x), repr(tot) ... 0.20000000000000001 0.20000000000000001 0.20000000000000001 0.40000000000000002 0.20000000000000001 0.60000000000000009 0.20000000000000001 0.80000000000000004 0.10000000000000001 0.90000000000000002 0.10000000000000001 1.0 >>> As you can see, 0.1 and 0.2 can't be represented exactly as floating point numbers. Consequently there is only a rough chance that they will add up to what you think they should add up to. Fixes: (1) Round the sums to a suitable precision. >>> round(sum(a), 3) 1.0 >>> round(sum(b), 3) 1.0 >>> (2) Test against a range, rather than for equality: >>> abs(sum(a) - 1.0) < 0.001 True >>> abs(sum(b) - 1.0) < 0.001 True >>> (3) Use the Decimal module (4) Google this group (or the Python cookbok, I forget which) for fancy algorithms for doing accurate sums of lists of floats. HTH, John From nick at craig-wood.com Sun Feb 18 14:30:35 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 18 Feb 2007 13:30:35 -0600 Subject: 'import dl' on AMD64 platform References: <1171757251.224765.171800@s48g2000cws.googlegroups.com> Message-ID: John Pye wrote: > I have a tricky situation that's preventing my Python/SWIG/C > application from running on the Debian Etch AMD64 platform. > > It seems that the 'dl' module is not available on that platform. The > only reason I need the 'dl' module, however, is for the values of > RTLD_LAZY etc, which I use with sys.setdlopenflags() in order to make > my imported SWIG module share its symbols correctly with more deeply- > nested plugin modiles in my C-code layer. > > I wonder if there is a workaround for this -- perhaps another way to > access the values of those RTLD flags? Read stuff out of /usr/include/bits/dlfcn.h ? It seems to be a constant 1 anyway #define RTLD_LAZY 0x00001 You could try compiling the dl module by hand. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From robin at NOSPAMreportlab.com Sat Feb 3 15:36:28 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 03 Feb 2007 20:36:28 +0000 Subject: ctypes.com.IUnknown Message-ID: <45C4F24C.7060204@jessikat.plus.net> I find that ctypes.com has disappeared from the ctypes extension bundled with Python 2.5. I think I only need the IUnknown, I was playing with building a dialog using venster, but it needs IUnknown, STDMETHOD, HRESULT, GUID from ctypes.com. Any ideas what should replace those or is venster now too old to bother with. -- Robin Becker From tubby at bandaheart.com Tue Feb 27 21:21:43 2007 From: tubby at bandaheart.com (tubby) Date: Tue, 27 Feb 2007 21:21:43 -0500 Subject: threading a thread In-Reply-To: <54k0v7F1nt481U1@mid.individual.net> References: <54jm2pF20dq64U2@mid.individual.net> <54k0v7F1nt481U1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > RTFM? One last things... here's a *very* small sample netstat output from a threaded py script: > tcp 0 1 192.168.1.100:41066 192.168.17.132:www SYN_SENT > tcp 0 1 192.168.1.100:46412 192.168.5.132:www SYN_SENT > tcp 0 1 192.168.1.100:58297 192.168.83.132:www SYN_SENT > tcp 0 1 192.168.1.100:44011 192.168.157.4:www SYN_SENT > tcp 0 1 192.168.1.100:51936 192.168.243.4:www SYN_SENT > tcp 0 1 192.168.1.100:40812 192.168.39.132:www SYN_SENT > tcp 0 1 192.168.1.100:41903 192.168.155.4:www SYN_SENT > tcp 0 1 192.168.1.100:39110 192.168.35.132:www SYN_SENT > tcp 0 1 192.168.1.100:33060 192.168.59.132:www SYN_SENT > tcp 0 1 192.168.1.100:33060 192.168.59.132:www SYN_SENT > tcp 0 1 192.168.1.100:46544 192.168.15.132:www SYN_SENT > tcp 0 1 192.168.1.100:51863 192.168.119.132:www SYN_SENT > tcp 0 1 192.168.1.100:51666 192.168.117.132:www SYN_SENT > tcp 0 1 192.168.1.100:60085 192.168.85.132:www SYN_SENT > tcp 0 1 192.168.1.100:57431 192.168.195.4:www SYN_SENT > tcp 0 1 192.168.1.100:48253 192.168.31.132:www SYN_SENT > tcp 0 1 192.168.1.100:48253 192.168.31.132:www SYN_SENT > tcp 0 1 192.168.1.100:55402 192.168.251.4:www SYN_SENT > tcp 0 1 192.168.1.100:48510 192.168.159.4:www SYN_SENT > tcp 0 1 192.168.1.100:46516 192.168.23.132:www SYN_SENT > tcp 0 1 192.168.1.100:60412 192.168.73.132:www SYN_SENT > tcp 0 1 192.168.1.100:56050 192.168.127.132:www SYN_SENT > tcp 0 1 192.168.1.100:58080 192.168.199.4:www SYN_SENT > tcp 0 1 192.168.1.100:58080 192.168.199.4:www SYN_SENT > tcp 0 1 192.168.1.100:55805 192.168.253.4:www SYN_SENT > tcp 0 1 192.168.1.100:57871 192.168.69.132:www SYN_SENT > tcp 0 1 192.168.1.100:50699 192.168.225.4:www SYN_SENT > tcp 0 1 192.168.1.100:50245 192.168.227.4:www SYN_SENT > tcp 0 1 192.168.1.100:34634 192.168.161.4:www SYN_SENT > tcp 0 1 192.168.1.100:43256 192.168.97.132:www SYN_SENT > tcp 0 1 192.168.1.100:58740 192.168.173.4:www SYN_SENT > tcp 0 1 192.168.1.100:40337 192.168.211.4:www SYN_SENT > tcp 0 1 192.168.1.100:46584 192.168.15.4:www SYN_SENT > tcp 0 1 192.168.1.100:37866 192.168.175.132:www SYN_SENT Now, try doing a netstat while you're running a 'parallel' nmap report and see the difference for yourself. It's huge. Have you ever actually tried what you recommended??? From NikitaTheSpider at gmail.com Tue Feb 20 13:29:52 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Tue, 20 Feb 2007 13:29:52 -0500 Subject: threading and multicores, pros and cons References: <7x4pphfjnx.fsf@ruckus.brouhaha.com> Message-ID: In article <7x4pphfjnx.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Nikita the Spider writes: > > note, there a (sort of) new module available that allows interprocess > > communication via shared memory and semaphores with Python. You can find > > it here: > > http://NikitaTheSpider.com/python/shm/ > > This is from the old shm module that was floating around several years > ago? Cool, I remember trying to find it recently and it seemed to > have disappeared--the original url was dead and it wasn't mirrored > anywhere. Yes, this is almost certainly the one which you remember. I had a hard time finding it myself, but it's still shipped with a few Linux distros that have their SVN repository online and indexed by Google. FYI, I fixed a few bugs in the original, added some small features and a wrapper module. If you're compiling for Linux you might need to remove the HAVE_UNION_SEMUN definition from setup.py. (Just learned this yesterday thanks to Eric J. and I haven't updated the documentation yet.) > How about putting it in CheeseShop or some other such repository? Hmmm, I hadn't thought about that since I've never used the Cheese Shop myself. What benefits does Cheese Shop confer to someone looking for a package? I ask because from my perspective it just adds overhead to package maintenance. > Having it in the stdlib would be even better, of course. That'd be fine with me! -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From gagsl-py2 at yahoo.com.ar Sun Feb 25 04:26:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Feb 2007 06:26:33 -0300 Subject: RegExp performance? References: <45e145a0$0$90264$14726298@news.sunsite.dk> Message-ID: En Sun, 25 Feb 2007 05:21:49 -0300, Christian Sonne escribi?: > Long story short, I'm trying to find all ISBN-10 numbers in a multiline > string (approximately 10 pages of a normal book), and as far as I can > tell, the *correct* thing to match would be this: > ".*\D*(\d{10}|\d{9}X)\D*.*" Why the .* at the start and end? You dont want to match those, and makes your regexp slow. You didn't tell how exactly a ISBN-10 number looks like, but if you want to match 10 digits, or 9 digits followed by an X: reISBN10 = re.compile("\d{10}|\d{9}X") That is, just the () group in your expression. But perhaps this other one is better (I think it should be faster, but you should measure it): reISBN10 = re.compile("\d{9}[\dX]") ("Nine digits followed by another digit or an X") > if I change this to match ".*[ ]*(\d{10}|\d{9}X)[ ]*.*" instead, I risk > loosing results, but it runs in about 0.3 seconds Using my suggested expressions you might match some garbage, but not loose anything (except two ISBN numbers joined together without any separator in between). Assuming you have stripped all the "-", as you said. > So what's the deal? - why would it take so long to run the correct one? > - especially when a slight modification makes it run as fast as I'd > expect from the beginning... Those .* make the expression match a LOT of things at first, just to discard it in the next step. -- Gabriel Genellina From paul at boddie.org.uk Tue Feb 27 07:27:24 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Feb 2007 04:27:24 -0800 Subject: Python, Embedded linux and web development In-Reply-To: <1172578332.957236.247800@8g2000cwh.googlegroups.com> References: <1172578332.957236.247800@8g2000cwh.googlegroups.com> Message-ID: <1172579243.995924.87580@m58g2000cwm.googlegroups.com> On 27 Feb, 13:12, "Tzury" wrote: > > c) small web application that will be used as front end to configure > the system (flat files and sqlite3 db are the back-end). > > Our platform is base on the Intel PXA270 processor (XSCALE family, > which is ARM compatible) running at 312MHz. You might want to read this article which got mentioned fairly recently either on comp.lang.python or on some blog or other: http://www.linuxdevices.com/articles/AT5550934609.html Paul From laurent.pointal at limsi.fr Fri Feb 2 09:46:48 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Feb 2007 15:46:48 +0100 Subject: newbie/ merging lists of lists with items in common In-Reply-To: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> References: <1170424548.194724.113820@m58g2000cwm.googlegroups.com> Message-ID: ardief a ?crit : > Hi everyone > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] > > I have the feeling it's trivial, and I've scoured the group archives - > sets might be a possibility, but I'm not sure how to operate on a list > of lists with sets. > > This function also gives me what I want, more or less, but I don't > know how to make it run until it's covered all the possibilities, if > that makes sense... > > def sigh(list): > for a in list: > i = list.index(a) > if a != list[-1]: ##if a is not the last one, i.e. there is a > next one > n = alist[i+1] > if a[0] == n[0]: > a.append(n[1:]) > del alist[i+1] > > Sorry about the lengthy message and thanks for your suggestions - I'm > trying to learn... > You may take a look to the groupby iterator in the standard itertools module. http://docs.python.org/lib/itertools-functions.html From python at hope.cz Sat Feb 10 09:00:05 2007 From: python at hope.cz (Johny) Date: 10 Feb 2007 06:00:05 -0800 Subject: How to find all the same words in a text? In-Reply-To: References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> Message-ID: <1171116005.380549.73690@l53g2000cwa.googlegroups.com> On Feb 10, 2:42 pm, Marco Giusti wrote: > On Sat, Feb 10, 2007 at 05:29:23AM -0800, Johny wrote: > >I need to find all the same words in a text . > >What would be the best idea to do that? > >I used string.find but it does not work properly for the words. > >Let suppose I want to find a number 324 in the text > > >'45 324 45324' > > >there is only one occurrence of 324 word but string.find() finds 2 > >occurrences ( in 45324 too) > > >>> '45 324 45324'.split().count('324') > 1 > >>> > > ciao Marco, Thank you for your help. It works perfectly but I forgot to say that I also need to find the possition of each word's occurrence.Is it possible that Thanks. L From gagsl-py at yahoo.com.ar Tue Feb 13 11:54:23 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Feb 2007 13:54:23 -0300 Subject: Newbie question about Class References: Message-ID: En Tue, 13 Feb 2007 13:01:59 -0300, escribi?: > But I'm still confused that what's the "real dictionary"?I can't know > this > point.Please help and thanks again. I'm talking about a Python dictionary (a "real" one, as opposed to UserDict, which is a "fake" dictionary; it looks and acts like a dictionary but it's not). py> from UserDict import UserDict py> d = {"a": 1, "b": 2, "c": 3} # This is a "real" dictionary # I create an UserDict instance, its initial contents come from a dictionary py> ud1 = UserDict(d) py> ud1 {'b': 2, 'a': 1, 'c': 3} # Now I create a second UserDict instance, its initial contents come from the UserDict instance py> ud2 = UserDict(ud1) py> ud2 {'b': 2, 'a': 1, 'c': 3} -- Gabriel Genellina From sulsa at gazeta.pl Sun Feb 4 11:05:03 2007 From: sulsa at gazeta.pl (Sulsa) Date: Sun, 4 Feb 2007 17:05:03 +0100 Subject: Dlaczego ten destruktor nie dziala Message-ID: <20070204170503.4dbb1b14.sulsa@gazeta.pl> Mam klase A po ktorej dziedziczy B i jesli w destruktorze klasy B wywolam: self.__class__.__bases__[0].__del__(self) to wszytkos jest ok, i destruktor klasy a jest wywolywany, jesli natomiast napisze: A.__del__(self) to otrzymuje nastepujacy wyjatek: Exception exceptions.AttributeError: "'NoneType' object has no attribute '__del__'" in > ignored czemu tak sie dzieje? From weinhand at unileoben.ac.at Tue Feb 27 06:14:55 2007 From: weinhand at unileoben.ac.at (WEINHANDL Herbert) Date: Tue, 27 Feb 2007 12:14:55 +0100 Subject: HTML to dictionary In-Reply-To: References: Message-ID: <45e4128a$0$8024$3b214f66@aconews.univie.ac.at> Tina I schrieb: > Hi everyone, > > I have a small, probably trivial even, problem. I have the following HTML: >> >> METAR: >> >> ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 NOSIG >>
... BeautifulSoup is really fun to work with ;-) > I have played around with BeautifulSoup but I'm stuck at stripping off > the tags and chop it up to what I need to put in the dict. If someone > can offer some hints or example to get me going I would greatly > appreciate it. > > Thanks! > Tina #!/usr/bin/python # -*- coding: utf-8 -*- from BeautifulSoup import BeautifulSoup, Tag, NavigableString html = """ Title METAR: ENBR 270920Z 00000KT 9999 ...
short-TAF: ENBR 270800Z 270918 VRB05KT ...
long-TAF: ENBR 271212 VRB05KT 9999 ...
""" soup = BeautifulSoup( html, convertEntities='html' ) bolds = soup.findAll( 'b' ) dict = {} for b in bolds : key = b.next.strip() val = b.next.next.strip() print 'key=', key print 'val=', val, '\n' dict[key] = val print dict #---- end ---- happy pythoning Herbert From exarkun at divmod.com Fri Feb 2 11:52:30 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 2 Feb 2007 11:52:30 -0500 Subject: asyncore DoS vulnerability In-Reply-To: <17859.26973.898595.251480@montanaro.dyndns.org> Message-ID: <20070202165230.25807.916181291.divmod.quotient.7521@ohm> On Fri, 2 Feb 2007 10:39:57 -0600, skip at pobox.com wrote: > > billie> asyncore aims to be a framework, right? I think that when > billie> select() limit is reached asyncore should just drop other > billie> connections. That's all. > >You're asking asyncore to make a policy decision on behalf the controlling >application. It has no idea what that application wants to do when the open >file limit is reached. Maybe it should close the oldest connection instead >of refusing all new ones. Maybe it should adjust the rate at which it >accepts new connections. asyncore doesn't know. It could ask the application. On the other hand, maybe asyncore remains in a perfectly consistent state even after it raises this exception, and it is already "asking" by letting this exception propagate up: if the application is free to start the loop again after this happens, then it seems everything is just fine; if some state becomes inconsistent, though, then asyncore should probably do something more (assuming asyncore applications are supposed to be able to be resistent to this kind of DoS). Still, this basically means every asyncore-based server can be shut down more or less at the whim of the public internet. Doesn't that problem merit some attention (maybe it doesn't, I don't know - that's why I'm asking)? Jean-Paul From paul at boddie.org.uk Tue Feb 27 06:28:18 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 Feb 2007 03:28:18 -0800 Subject: HTML to dictionary In-Reply-To: References: Message-ID: <1172575698.207717.34780@h3g2000cwc.googlegroups.com> On 27 Feb, 11:08, Tina I wrote: > > I have a small, probably trivial even, problem. I have the following HTML: >> >> METAR: >> >> ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 NOSIG >>
>> >> short-TAF: >> >> ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040 >>
>> >> long-TAF: >> >> ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 SNRA VV010 >> BECMG 2124 15012KT >>
This looks almost like XHTML which means that you might be able to use a normal XML parser. > I need to make this into a dictionary like this: > > dictionary = {"METAR:" : "ENBR 270920Z 00000KT 9999 FEW018 02/M01 Q1004 > NOSIG" , "short-TAF:" : "ENBR 270800Z 270918 VRB05KT 9999 FEW020 SCT040" > , "long-Taf:" : "ENBR 271212 VRB05KT 9999 FEW020 BKN030 TEMPO 2012 2000 > SNRA VV010 BECMG 2124 15012KT"} So what you want to do is to find each "b" element, extract the contents to produce a dictionary key, and then find all following text nodes up to the "br" element, extracting the contents of those nodes to produce the corresponding dictionary value. Now, with a DOM/XPath library, the first part is quite straightforward. Let's first parse the document, though: import libxml2dom # my favourite ;-) d = libxml2dom.parse(the_file) # add html=1 if it's HTML Now, let's get the "b" elements providing the keys: key_elements = d.xpath("//b") The above will find all "b" elements throughout the document. If that's too broad a search, you can specify something more narrow. For example: key_elements = d.xpath("/html/body/b") At this point, key_elements should contain a list of nodes, each corresponding to a "b" element, and you can get the contents of each element by asking for all the text nodes inside it and joining them together, stripping the whitespace off each end to make the dictionary key itself: def get_key(key_element): texts = [] # Get all text child nodes, collecting the contents. for n in key_element.xpath("text()"): texts.append(n.nodeValue) # Join them together, removing leading/trailing space. return "".join(texts).strip() (Currently, libxml2dom lets you ask an element for its nodeValue, erroneously returning text inside that element, but I don't want to promote this as a solution since I may change it at some point.) The process of getting the dictionary values is a bit more difficult. What we need to do is to ask for the following siblings of the "b" element, then to loop over them until we find a "br" element. The dictionary value is then obtained from the discovered text fragments by joining them together and stripping whitespace from the ends: def get_value(key_element): texts = [] # Loop over nodes following the element... for n in key_element.xpath("following-sibling::node()"): # Stop looping if we find a "br" element. if n.nodeType == n.ELEMENT_NODE and n.localName == "br": break # Otherwise get the (assumed) text content. texts.append(n.nodeValue) # Join the texts and remove leading/trailing space. return "".join(texts).strip() So, putting this together, you should get something like this: dictionary = {} for key_element in key_elements: dictionary[get_key(key_element)] = get_value(key_element) As always with HTML processing, your mileage may vary with such an approach, but I hope this is helpful. You should also be able to use something like 4Suite or PyXML with the above code, albeit possibly slightly modified. Paul P.S. Hopefully, Google Groups won't wrap the code badly. Whatever happened to the preview option, Google? From darius at dons.net.au Thu Feb 8 02:02:23 2007 From: darius at dons.net.au (Daniel O'Connor) Date: Thu, 08 Feb 2007 17:32:23 +1030 Subject: winsound/ossaudiodev equivalent on a mac References: <1170901197.595238.32000@m58g2000cwm.googlegroups.com> Message-ID: <12slio0i595vl42@corp.supernews.com> Andr? wrote: > I'm using winsound and ossaudiodev to produce simple sounds (of set > frequency for a given duration) in a an application that is used on > Windows-based computer and Linux-based ones. Is there a similar > module for Mac OS? Use SDL? http://gna.org/projects/pysdlmixer/ I've never used it but I like the idea of cross platform code, makes life a lot simpler for the programmer :) -- Daniel O'Connor software and network engineer for Genesis Software - http://www.gsoft.com.au "The nice thing about standards is that there are so many of them to choose from." -- Andrew Tanenbaum GPG Fingerprint - 5596 B766 97C0 0E94 4347 295E E593 DC20 7B3F CE8C From deron.meranda at gmail.com Sun Feb 18 00:59:18 2007 From: deron.meranda at gmail.com (Deron Meranda) Date: 17 Feb 2007 21:59:18 -0800 Subject: Need an identity operator because lambda is too slow Message-ID: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> This is an optimization problem, one that occurs deep inside a loop that gets executed thousands of times. I'm looking for something in Python which would act like an identity operator, or I-combinator: a do-nothing function. The best I know of is: (lambda x: x), but it is not ideal. Consider a much-simplified example of such an iteration where sometimes you need to transform an item by some function, but most of the time you don't: if some_rare_condition: func = some_transform_function else: func = lambda x: x for item in some_sequence: item2 = func(item) ..... # more stuff Now the "lambda x:x" acts suitably like an identity operator. But it is very slow, when compared to using more complex-looking code: do_transform = some_rare_condition for item in some_sequence: if do_transform: item2 = transform_function(item) else: item2 = item ..... # more stuff What python needs is something like a built-in "operator.identity" function, which acts like "lambda x:x", but which the byte compiler could recognize and completely optimize away so there is no function call overhead. Does this exist someplace in the corners of the language, or are there any ideas about how best to do something like this without having to push a bunch of ugly if-then-else constructs inside all the loops rather than a more elegant function object? (The need for this is more obvious in my real-world code versus the simplified examples above). Thanks -- Deron Meranda From nyamatongwe+thunder at gmail.com Sat Feb 3 17:10:26 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 03 Feb 2007 22:10:26 GMT Subject: Python does not play well with others In-Reply-To: <7xk5yz2q42.fsf@ruckus.brouhaha.com> References: <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> <1170448427.755864.20320@l53g2000cwa.googlegroups.com> <7xirek9pdt.fsf@ruckus.brouhaha.com> <52htlaF1mrd9iU1@mid.uni-berlin.de> <7xk5yz2q42.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > I thought J2SE comes with JSP. Maybe that's not a "framework" in the > fancy sense though. J2SE does not include JSP. Neil From zaz600 at gmail.com Mon Feb 5 20:14:30 2007 From: zaz600 at gmail.com (NoName) Date: 5 Feb 2007 17:14:30 -0800 Subject: Why? In-Reply-To: References: <1170721943.034518.223210@l53g2000cwa.googlegroups.com> Message-ID: <1170724470.440893.269370@a75g2000cwd.googlegroups.com> thanx a lot!! On 6 ???., 12:04, "Gabriel Genellina" wrote: > En Mon, 05 Feb 2007 21:32:23 -0300, NoName escribio: > > > # -*- coding: cp1251 -*- > > from glob import glob > > > src= "C:\\0000\\????? ?????\\*.*" > > print "src=",src > print "repr(src)=",repr(src)> print glob(src) > > for fn in glob(src): > print fn > > > > > ['C:\\0000\\\xcd\xee\xe2\xe0\xff \xef\xe0\xef\xea\xe0\\ksdjfk.txt', 'C: > > \\0000\\\xcd\xee\xe2\xe0\xff \xef > > \xe0\xef\xea\xe0\\\xeb\xfb\xe2\xee\xe0\xeb\xee\xe0\xeb.txt'] > > > Why not "C:\\0000\\????? ?????\\ksdjfk.txt" and etc? > > glob returns a list; when you print a list, it uses repr() on its > elements. It *looks* strange, but has the right contents. See the above > modifications. > > -- > Gabriel Genellina From ljz at asfast.com Thu Feb 22 13:35:33 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Thu, 22 Feb 2007 13:35:33 -0500 Subject: How to covert ASCII to integer in Python? References: Message-ID: <878xeq6nwq.fsf@asfast.com> "John" writes: > I just found ord(c), which convert ascii to integer. > > Anybody know what the reverse is? The inverse of "ord" is "chr": % python Python 2.5 (r25:51908, Jan 5 2007, 00:12:45) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ord('i') 105 >>> chr(105) 'i' >>> IIRC, the first use of the names "ord" and "chr" for these functions appeared in the Basic language in the 1960's ... in case anyone is interested in this bit of historical trivia. -- Lloyd Zusman ljz at asfast.com God bless you. From steve at REMOVE.THIS.cybersource.com.au Thu Feb 22 04:56:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Feb 2007 20:56:30 +1100 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172105179.708565.201600@v33g2000cwv.googlegroups.com> Message-ID: On Wed, 21 Feb 2007 16:46:19 -0800, Harlin Seritt wrote: >> WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM. It is just a >> nuisance for someone that really wants to decrypt the string. But >> it might work for your application. >> >> -Larry > > Thanks Larry! I was looking for something more beautiful but what the > hey, it works! Is this beautiful enough? >>> s = "Python" >>> u = unicode(s, "ascii") >>> u u'Python' >>> u.encode('rot13') 'Clguba' For extra security, you can encode the string with rot13 twice. -- Steven. From mail at microcorp.co.za Tue Feb 13 07:39:36 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 13 Feb 2007 14:39:36 +0200 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com><1171264811.509582.224870@p10g2000cwp.googlegroups.com> <1171359919.372059.148820@a75g2000cwd.googlegroups.com> Message-ID: <005001c74f6c$2353b860$03000080@hendrik> "John Machin" wrote: > On Feb 13, 4:57 pm, "Hendrik van Rooyen" wrote: > > "John Machin" wrote: > > > > > Now for the algorithm: all of that testing to see if you are about to > > > sail off the end of the world is a bit ugly and slow. You can use bit- > > > bashing, as Paul suggested, even though it's on Steven D'Aprano's list > > > of 6 deadly sins :-) > > > > Thou shallt not bit - bash > > > > What are the other five? > > """ > ... regexes have their place, together with pointer arithmetic, bit > manipulations, reverse polish notation and goto. The problem is when > people use them inappropriately ... > """ > I find this unsatisfactory - I was hoping for a five commandment style of thing, setting out proper prohibitions against evil stuff. It seems that I am a closet fundamentalist. A sixth, btw is: Thou shallt not use globals. - Hendrik From dwahler at gmail.com Sun Feb 18 07:10:03 2007 From: dwahler at gmail.com (David Wahler) Date: 18 Feb 2007 04:10:03 -0800 Subject: Need an identity operator because lambda is too slow In-Reply-To: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> References: <1171778358.458520.269360@j27g2000cwj.googlegroups.com> Message-ID: <1171800603.064704.283480@t69g2000cwt.googlegroups.com> On Feb 18, 5:59 am, "Deron Meranda" wrote: > Consider a much-simplified example of such an iteration where > sometimes you need to transform an item by some function, but most of > the time you don't: > > if some_rare_condition: > func = some_transform_function > else: > func = lambda x: x > for item in some_sequence: > item2 = func(item) > ..... # more stuff > > Now the "lambda x:x" acts suitably like an identity operator. But it > is very slow, when compared to using more complex-looking code: > > do_transform = some_rare_condition > for item in some_sequence: > if do_transform: > item2 = transform_function(item) > else: > item2 = item > ..... # more stuff > > What python needs is something like a built-in "operator.identity" > function, which acts like "lambda x:x", but which the byte compiler > could recognize and completely optimize away so there is no function > call overhead. Unless I'm misunderstanding you, you seem to be proposing that the compiler should avoid generating the call to func2() if it has a certain value. How could that information possibly be available at compile time? -- David From ian.brady1 at gmail.com Tue Feb 6 13:54:20 2007 From: ian.brady1 at gmail.com (ian.brady1 at gmail.com) Date: 6 Feb 2007 10:54:20 -0800 Subject: Help with multiple key sort In-Reply-To: References: <1170786670.535839.118650@s48g2000cws.googlegroups.com> Message-ID: <1170788060.466000.240000@v33g2000cwv.googlegroups.com> Paul already answered it. Tnx Paul. My data is in a file and now I have to take care to strip \t and \n from it. Thanks > I'm not a guru. Maybe that's why I don't understand which "sql-like > sort-by on multiple keys" would produce output that lacks some of the > input but has additional items. ;) > > In other words: why don't you show your concrete program and the input > and output data to use. Is the data a list of tuples or lists or what? > > Cheers, > Jussi From nagle at animats.com Mon Feb 5 12:52:01 2007 From: nagle at animats.com (John Nagle) Date: Mon, 05 Feb 2007 17:52:01 GMT Subject: Python does not play well with others In-Reply-To: <1170664604.049592.164180@h3g2000cwc.googlegroups.com> References: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> <7xodob2q7c.fsf@ruckus.brouhaha.com> <1170548886.842563.121630@v33g2000cwv.googlegroups.com> <7xfy9mekxr.fsf@ruckus.brouhaha.com> <1170625204.156763.178460@j27g2000cwj.googlegroups.com> <0mtxh.1615$gj4.450@newssvr14.news.prodigy.net> <1170664604.049592.164180@h3g2000cwc.googlegroups.com> Message-ID: <59Kxh.58118$wc5.26300@newssvr25.news.prodigy.net> sjdevnull at yahoo.com wrote: > John Nagle wrote: > >>Graham Dumpleton wrote: >> >>>On Feb 4, 1:05 pm, Paul Rubin wrote: >>> >>> >>>>"Paul Boddie" writes: >> Realistically, mod_python is a dead end for large servers, >>because Python isn't really multi-threaded. The Global Python >>Lock means that a multi-core CPU won't help performance. > > > The GIL doesn't affect seperate processes, and any large server that > cares about stability is going to be running a pre-forking MPM no > matter what language they're supporting. Pre-forking doesn't reduce load; it just improves responsiveness. You still pay for loading all the modules on every request. For many AJAX apps, the loading cost tends to dominate the transaction. FastCGI, though, reuses the loaded Python (or whatever) image. The code has to be written to be able to process transactions in sequence (i.e. don't rely on variables intitialized at load), but each process lives for more than one transaction cycle. However, each process has a copy of the whole Python system, although maybe some code gets shared. John Nagle From skip at pobox.com Mon Feb 12 12:17:14 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 12 Feb 2007 11:17:14 -0600 Subject: Regular Expressions In-Reply-To: <1171275611.208401.212000@v33g2000cwv.googlegroups.com> References: <1171211726.044702.241100@a34g2000cwb.googlegroups.com> <1171227036.789128.188720@q2g2000cwa.googlegroups.com> <1171275611.208401.212000@v33g2000cwv.googlegroups.com> Message-ID: <17872.41242.406744.90401@montanaro.dyndns.org> dbl> The source of HTMLParser and xmllib use regular expressions for dbl> parsing out the data. htmllib calls sgmllib at the begining of it's dbl> code--sgmllib starts off with a bunch of regular expressions used dbl> to parse data. I am almost certain those modules use regular expressions for lexical analysis (splitting the input byte stream into "words"), not for parsing (extracting the structure of the "sentences"). If I have a simple expression: (7 + 3.14) * CONST that's just a stream of bytes, "(", "&", " ", "+", ... Lexical analysis chunks that stream of bytes into the "words" of the language: LPAREN (NUMBER, 7) PLUS (NUMBER, 3.14) RPAREN TIMES (IDENT, "CONST") Parsing then constructs a higher level representation of that stream of "words" (more commonly called tokens or lexemes). That representation is application-dependent. Regular expressions are ideal for lexical analysis. They are not-so-hot for parsing unless the grammar of the language being parsed is *extremely* simple. Here are a couple much better expositions on the topics: http://en.wikipedia.org/wiki/Lexical_analysis http://en.wikipedia.org/wiki/Parsing Skip From nick at craig-wood.com Tue Feb 20 01:34:24 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 20 Feb 2007 00:34:24 -0600 Subject: 'import dl' on AMD64 platform References: <1171757251.224765.171800@s48g2000cws.googlegroups.com> <1171884470.410211.311270@v33g2000cwv.googlegroups.com> Message-ID: John Pye wrote: > On Feb 19, 6:30 am, Nick Craig-Wood wrote: > > John Pye wrote: > > > application from running on the Debian Etch AMD64 platform. > > > It seems that the 'dl' module is not available on that platform. The > > > only reason I need the 'dl' module, however, is for the values of > > > RTLD_LAZY etc, which I use with sys.setdlopenflags() in order to make > > > my imported SWIG module share its symbols correctly with more deeply- > > > nested plugin modiles in my C-code layer. > > > > > I wonder if there is a workaround for this -- perhaps another way to > > > access the values of those RTLD flags? > > > > Read stuff out of /usr/include/bits/dlfcn.h ? > > > > It seems to be a constant 1 anyway > > > > #define RTLD_LAZY 0x00001 > > > > You could try compiling the dl module by hand. > > Well yes, and that's the workaround I came up with: for systems that > don't provide the 'dl' module, I just default to the values I found on > my linux (ubuntu) system. This is a nasty hack however. > > I wonder if anyone could say why the Debian people left out this > important module from their AMD64 platform? There is a note (from a 2002) in the changelog about * Always build the dl module. Failure in case of sizeof(int)!=sizeof(long)!=sizeof(void*) is delayed until dl.open is called. Closes: #141681. http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=141681 so maybe it doesn't build properly on amd64. That, or it violating the free software guidelines (unlikely in this case) are the two major reasons for missing features in debian. The normal procedure would be to try the package from unstable. If that doesn't work then report a bug. (Easiest with the reportbug package.) I don't have an amd64 machine to try otherwise I'd try it for you! I looked in the latest packages for python2.4 & python2.5 for amd64 and /usr/lib/python2.4/lib-dynload/dl.so doesn't appear to be there. http://packages.debian.org/cgi-bin/search_contents.pl?searchmode=filelist&word=python2.5&version=unstable&arch=amd64&page=9&number=50 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From google at mrabarnett.plus.com Thu Feb 8 18:39:17 2007 From: google at mrabarnett.plus.com (MRAB) Date: 8 Feb 2007 15:39:17 -0800 Subject: Strings in Python In-Reply-To: <1170959568.410295.285410@l53g2000cwa.googlegroups.com> References: <1170952105.836043.43110@a34g2000cwb.googlegroups.com> <1170959568.410295.285410@l53g2000cwa.googlegroups.com> Message-ID: <1170977957.862904.164100@a75g2000cwd.googlegroups.com> On Feb 8, 6:32 pm, attn.steven.... at gmail.com wrote: > On Feb 8, 8:28 am, "Johny" wrote: > > > > > Playing a little more with strings, I found out that string.find > > function provides the position of > > the first occurance of the substring in the string. > > Is there a way how to find out all substring's position ? > > To explain more, > > let's suppose > > > mystring='12341' > > import string > > > >>> string.find(mystring ,'1') > > > 0 > > > But I need to find the possition the other '1' in mystring too. > > Is it possible? > > Or must I use regex? > > In this case, you can use: > > mystring = '12341' > indices = [ _ for _ in range(len(mystring)) if mystring[_] == '1' ] > print indices > Or: mystring = '12341' indices = [ i for i, c in enumerate(mystring) if c == '1' ] print indices From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 1 09:42:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 01 Feb 2007 15:42:35 +0100 Subject: Inconsistent list/pointer problem In-Reply-To: References: Message-ID: <45c1fc05$0$26727$426a74cc@news.free.fr> Doug Stell a ?crit : > I am having a problem with the corruption of a list. It occurs only > the first time that I call a function and never happens on subsequent > calls. Any suggestions would be appreciated. > > I call the function, passing in a list as the input data. The function > must manipulate and operate on a copy of that list's data, without > altering the list in the calling routine. > > def myFunc(listA): > listB = listA > work on & modify listB > return(listB) return is a statement, not a function. Please remove these useless (and possibly harmful) parens. > The first time this function touches listB, listA is corrupted. It's not. It's just that you did *not* copy listA - you just made listB reference the same object. > > I concluded that it appears that listB is still pointing at elements > of listA It's even worse : both names listA and listB are pointing to the exact same object. listA = ['A', 'B', 'C'] listB = listA assert listA is listB > and I need to force Python to reassign those pointers s/pointers/references/ > to > point to copies of listA's elements. copy.deepcopy() is your friend then. From S.Mientki-nospam at mailbox.kun.nl Mon Feb 5 14:08:54 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 05 Feb 2007 20:08:54 +0100 Subject: Calling J from Python In-Reply-To: <52p5mbF1p0r0cU2@mid.individual.net> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: > > Mh, just looking at some "advanced" J source taken from > wikipedia.org makes me feel sick: > > | Here's a J program to calculate the average of a list of numbers: > | avg=: +/ % # > | avg 1 2 3 4 > | 2.5 > And here is the Python way of calculating the average >>> mean([1,2,3,4]) 2.5 sorry, I don't see any advantage. cheers, Stef Mientki From kirk at nospam.jobsluder.net Sun Feb 4 19:17:24 2007 From: kirk at nospam.jobsluder.net (Kirk Sluder) Date: Mon, 05 Feb 2007 00:17:24 GMT Subject: "Subscribing" to topics? References: <5aoxh.7440$gJ1.6708@newsfe17.lga> <1170618799.354069.327210@h3g2000cwc.googlegroups.com> <1170623565.106773.263940@m58g2000cwm.googlegroups.com> Message-ID: In article <1170623565.106773.263940 at m58g2000cwm.googlegroups.com>, "Mizipzor" wrote: > On Feb 4, 9:55 pm, Toby A Inkster > wrote: > > You discovered wrong -- Google does not provide a free newsserver. They no > > doubt *have* several newsservers, but don't provide direct access to them > > either free, or for a fee. They only provide a web interface to access the > > contents of their newsservers, with a fraction of the features that a real > > newsreader would. > > Hehe, it has all the features I knew existed in a newsreader, except > this "subscribe to topic" thing Im looking for. If you have My Groups enabled, you can highlight a topic as a favorite. When reading a thread, click on the star near the upper left corner of the screen under the subject header. This will add that subject to your favorites. Then to see your favorite topics, click "favorites" at the top of the page, toward the right-hand side. In an email client, you can set a filter that dumps messages from a list that don't match specific keywords into the trash or an archive folder. From max at alcyone.com Tue Feb 6 14:40:36 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 06 Feb 2007 11:40:36 -0800 Subject: Running long script in the background In-Reply-To: <1170777052.386308.290760@q2g2000cwa.googlegroups.com> References: <1170768405.583908.138190@j27g2000cwj.googlegroups.com> <1170769014.352466.135280@h3g2000cwc.googlegroups.com> <1170776253.027044.253050@q2g2000cwa.googlegroups.com> <1170777052.386308.290760@q2g2000cwa.googlegroups.com> Message-ID: wattersmt at gmail.com wrote: > I tried flushing stdout and the same thing happens. As soon as the > os.popen(command) line runs it stops there, the next print statement > never even runs. > > I've also tried using os.spawnv to make the process run in the > background but then the ssh command never runs. Based on what you describe, this isn't a good application for a single-transaction CGI exchange. The timeouts are not happening at the level of your CGI script, but rather either at the HTTP server itself or at the remote client. In either case, fixing it as a one-transaction, one-script solution is not going to be very feasible. A more sensible way to do it is to have one logical page (which could be the same physical page if you want) which accepts job requests, spawns them off in the background, and offers a link to a second logical page which sees if the job has completed -- showing the results if it has -- or refreshes periodically if it hasn't yet. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis You could have another fate / You could be in another place -- Anggun From vithi99 at hotmail.com Fri Feb 16 21:36:26 2007 From: vithi99 at hotmail.com (vithi) Date: 16 Feb 2007 18:36:26 -0800 Subject: how to use Dispatch to open an application in win32com.client Message-ID: <1171679786.355275.191860@h3g2000cwc.googlegroups.com> Hi' I am trying to launch an application. When I try like that When I try like that Excel is opening import win32com.client object = win32com.client.Dispatch("Excel.Application") object.Visible = 1 But when I try my application which is QeepIt.exe which is in the c:\ drive it is not running Any body tell me how to give path to open an exectable application in Dispatch modules I try like that object = win32com.client.Dispatch("c:\Folder\QeepIt.exe") It give an error. From http Thu Feb 22 04:05:10 2007 From: http (Paul Rubin) Date: 22 Feb 2007 01:05:10 -0800 Subject: Finding a tuple in a tuple References: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> Message-ID: <7xd5427ebd.fsf@ruckus.brouhaha.com> bg_ie at yahoo.com writes: > Lists say I have the following tuple - > t1 = ("ONE","THREE","SIX") > t2 = ("ONE","TWO","THREE") > t3 = ("TWO","FOUR","FIVE","SIX") > t4 = ("TWO",) > t5 = ("TWO","FIVE") > > What I want to do is return true if any member of tuple t1 is found in > the remaining tuples. Convert them into sets and use the set intersection (&) operator, then convert to bool to represent whether the intersection is empty. print bool(set(t1) & set(t2)) print bool(set(t1) & set(t3)) print bool(set(t1) & set(t4)) print bool(set(t1) & set(t5)) From B.Ogryczak at gmail.com Fri Feb 9 06:10:15 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 9 Feb 2007 03:10:15 -0800 Subject: UNIX shell in Python? In-Reply-To: References: Message-ID: <1171019415.764194.304470@q2g2000cwa.googlegroups.com> On Feb 9, 8:49 am, Deniz Dogan wrote: > Hello. > > I was thinking about writing a UNIX shell program using Python. Has > anyone got any experience on this? Is it even possible? Use the Google, Luke. http://sourceforge.net/projects/pyshell/ From skpeterson at nospam.please.ucdavis.edu Mon Feb 12 00:05:49 2007 From: skpeterson at nospam.please.ucdavis.edu (Samuel Karl Peterson) Date: 11 Feb 2007 21:05:49 -0800 Subject: About getattr() References: Message-ID: "Jm lists" on Mon, 12 Feb 2007 12:36:10 +0800 didst step forth and proclaim thus: > Hello, > > Since I can write the statement like: > > >>> print os.path.isdir.__doc__ > Test whether a path is a directory > > Why do I still need the getattr() func as below? > > >>> print getattr(os.path,"isdir").__doc__ > Test whether a path is a directory getattr lets you lookup an attribute given a string, so the attribute wouldn't have to be hardcoded in your program, it could come from a file, or from user input. -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From phil at riverbankcomputing.co.uk Thu Feb 1 06:12:35 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 1 Feb 2007 11:12:35 +0000 Subject: SWIG overhead In-Reply-To: <1170325295.575450.84340@s48g2000cws.googlegroups.com> References: <1170325295.575450.84340@s48g2000cws.googlegroups.com> Message-ID: <200702011112.35201.phil@riverbankcomputing.co.uk> On Thursday 01 February 2007 10:21 am, Bart Ogryczak wrote: > Hi, > I?m looking for some benchmarks comparing SWIG generated modules with > modules made directly with C/Python API. Just how much overhead does > SWIG give? Doing profile of my code I see, that it spends quiet some > time in functions like _swig_setattr_nondinamic, _swig_setattr, > _swig_getattr. There was a EuroPython paper describing some benchmarks. It's from 2004 so things have probably changed a bit (SIP is now fully documented for example). http://people.web.psi.ch/geus/talks/europython2004_geus.pdf Phil From pink at odahoda.de Wed Feb 21 11:41:46 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 21 Feb 2007 17:41:46 +0100 Subject: Creating a daemon process in Python References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Message-ID: Hello, Sakagami Hiroki wrote: > What is the easiest way to create a daemon process in Python? Google > says I should call fork() and other system calls manually, but is > there no os.daemon() and the like? You could try HTH -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From s.mientki at id.umcn.nl Tue Feb 13 03:41:30 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 13 Feb 2007 09:41:30 +0100 Subject: Testers please In-Reply-To: References: Message-ID: <8cde9$45d179ba$83aef404$16072@news1.tudelft.nl> martien friedeman wrote: > I have written this tool that allows you to look at runtime data and > code at the same time. > And now I need people to test it. > > The easiest way to see what I mean is to look at some videos: > http://codeinvestigator.googlepages.com/codeinvestigator_videos > > It requires Apache and Sqlite. > > It works for me with a Firefox browser on Linux. Great idea ! Especially for newbies, so you've to make sure it's always in the "first starters package". As most modern code-editors, already support context sensitive popup's, can't you make a module that can be added to any editor ? a few other suggestions - for large datasets, display only the "corner" values - for loops, also only display the "corner" values - to decrease datasize enormuous, limit the functionality to a piece of code selected by the user - get rid of Apache and SQLite, too complicated for newbies keep on the good work, cheers, Stef Mientki From jura.grozni at gmail.com Wed Feb 7 17:00:42 2007 From: jura.grozni at gmail.com (azrael) Date: 7 Feb 2007 14:00:42 -0800 Subject: Python does not play well with others In-Reply-To: References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: <1170885641.942886.268960@h3g2000cwc.googlegroups.com> you have to undestand that python is not like other languages. I am working wih it for 3 months. in this time i learned more than throgh c, c++, java or php. you take. what the hell is php. a language developed primary for webaplications. take zope and you have the same. besides that zope will do fantastic things crossing with other modules. c and c++ are incredible languages and if i am not wrong, c is the way to make aplications working on minimum time (not including assembler). it has been developed for quite a long time and the researches have been sponsored even from the goverments. the development of php is continued while Rasmus Lerdorf is working for yahoo. the python comunity is not so big as the php (at least in my country), but such people like me, who fell in love with python, we work on our projects, we know what we want, and if it dosn't work we make it work. I ma working on a project and had no filters i needed for signal processing so I wrote it. My next step when they are finished and work well is to send it to the admins from pil. this is open source, and we help each others. thats open source. you try python and you like it or not, you keep using it or not. if something dosn't work, be so kind and make it work, but please, don't expect someone else to do your "homework". If there are some problems, contact the admins and offer them your help. On Jan 25, 6:17 pm, John Nagle wrote: > Paul Boddie wrote: > > On 25 Jan, 12:01, "Ben Sizer" wrote: > > >> I think that is why many of the SIGs are stagnant, why the standard library > >> has so much fluff yet still lacks in key areas such as multimedia and web > >> development, etc. > > ... I think this is also a good insight into why things are as they are > > within the core development section of the community, although one can wonder > > what some people actively developing the language are actually doing with it > > if they are satisfied with the state of some of the standard library > > solutions. However, there are lots of factors which motivate people and the > > proliferation (or otherwise) of solutions to common problems: whether one > > develops one's own solutions as separate projects and/or tries to push for a > > consensus, whether one cares about other people using such solutions, whether > > one aspires to contributing to the standard library. > > > Over the years, people have tended towards building their own communities > > around their projects rather than attempting to engage the wider Python > > community, and I think a motivation behind that has been the intractability > > of improving parts of the standard library. > > Yes. Working on "frameworks" is perceived as cooler than working > on libraries. Things like Ruby on Rails, Struts, Zope, and Twisted > get attention. There are papers and conferences on these things. > It's hard to get people excited about overhauling > the CGI library, or making mod_python work securely in shared-hosting > environments. > > The key distinction between a framework and a library is that users > are expected to make their code fit the framework. In particular, > frameworks aren't expected to play well with each other. If you need > something from Zope and something from Twisted, you're probably not > going to be able to make it work. Libraries, on the other hand, > are expected to play well together. Which means that they have to > handle the hard cases correctly, not just the easy ones. > > > > > True. It also doesn't address the issue of development priorities and their > > role in defining the platform's own standards > ... > > I do wonder whether the interests of language/runtime project developers > > eventually become completely aligned with the needs of such projects, making > > things like "multimedia and web development" seem irrelevant, uninteresting > > or tangential. This has worrying implications for the perceived relevance of > > Python with regard to certain kinds of solutions, despite the wealth of > > independently produced libraries available for the language. > > Something like that happened to the C++ standards committee. > The committee was captured by the template fanatics, and most new > standards work involves doing computation at compile time via template > expansion. That's seldom done in production code, yet most of the > standards effort is devoted to making cool template hacks work better. > Meanwhile, real problems, like doing something about memory leaks and buffer > overflows, are ignored by the C++ committee. As a result, C++ is > being displaced by Java and C#, which don't have elaborate templates but do have > memory safety. > > I'm not sure how the Python development community will deal with this > problem. But what's happened in the C++ standards world has clearly > been very bad for users of the language. Learn from the mistakes there. > > My main concern is with glue code to major packages. The connections > to OpenSSL, MySQL, and Apache (i.e. mod_python) all exist, but have major > weaknesses. If you're doing web applications, those are standard pieces > which need to work right. There's a tendency to treat those as abandonware > and re-implement them as event-driven systems in Twisted. Yet the > main packages aren't seriously broken. It's just that the learning curve > to make a small fix to any of them is substantial, so nobody new takes > on the problem. > > John Nagle > Animats From nejucomo at gmail.com Mon Feb 19 17:47:26 2007 From: nejucomo at gmail.com (Nathan) Date: Mon, 19 Feb 2007 15:47:26 -0700 Subject: FPE: Add bindings to exception tracebacks. Message-ID: <13f991410702191447o41969227k72ffb9417993f55b@mail.gmail.com> Hi folks! Throughout my python development career, I've occasionally made various developer tools to show more information about assertions or exceptions with less hassle to the programmer. Until now, these tools didn't pass a utility vs pain-to-use threshold. Now I've created a tool I believe to have passed that threshold, which I call "binding annotated exception tracebacks". In short, this tool adds text showing relevant local bindings to each level in a stack trace print out. I consider it to be so useful that it should be part of the standard library. I'm not sure the best process to propose this (shall I make a PEP? -is this already an FPE?), so I thought I'd start with a published early/often patch, then point people to it. I've submitted a patch against the 2.6 head on the sf tracker as ticket 1654974, or try this url: http://sourceforge.net/tracker/index.php?func=detail&aid=1654974&group_id=5470&atid=305470 The patch modifies the traceback module. It's also entirely reasonable to have this functionality in a new, separate module (and also it may be implemented in earlier python versions), but for my personal build I wanted all programs to use this new feature. Here's an example to clarify. Consider the following script: #! /usr/bin/env python2.6 import sys import traceback # Install annotated exception printing: sys.excepthook = lambda t, v, b: traceback.print_exception(t, v, b, annotate=True) def f(c): d = 2*c return g(c) def g(x): return (lambda z: z+'foo')(x) f(42) -The output (with the patch of course) is: Traceback (most recent call last): File "/home/n/tmp/demo-bindann.py", line 16, in # With bindings: # f = # Source: f(42) File "/home/n/tmp/demo-bindann.py", line 11, in f # With bindings: c = 42 # g = # Source: return g(c) File "/home/n/tmp/demo-bindann.py", line 14, in g # With bindings: x = 42 # Source: return (lambda z: z+'foo')(x) File "/home/n/tmp/demo-bindann.py", line 14, in # With bindings: z = 42 # Source: return (lambda z: z+'foo')(x) TypeError: unsupported operand type(s) for +: 'int' and 'str' From bearophileHUGS at lycos.com Thu Feb 1 21:25:17 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Feb 2007 18:25:17 -0800 Subject: Overloading the tilde operator? In-Reply-To: References: Message-ID: <1170383117.207665.3610@v33g2000cwv.googlegroups.com> Peter Otten: > No, you will get a syntax error before python even look up the names: There are some tricks that allow the use of "undefined" symbols in Python too, but they are probably just toys. I have recently posted a recipe in the cookbook for that. Bye, bearophile From cwitts at gmail.com Fri Feb 9 02:36:19 2007 From: cwitts at gmail.com (Chris) Date: 8 Feb 2007 23:36:19 -0800 Subject: pyExcelerator - Protecting Cells Message-ID: <1171006579.885603.4760@j27g2000cwj.googlegroups.com> I'm sitting with a bit of an issue with pyExcelerator and creating an Excel file with certain cells protected while the rest of the spreadsheet is password protected. The Protection class under Formatting has 2 variables for cell_locked and formula_hidden, tbh I only need to alter cell_locked to 0 to make those cells writable but changing that on a global scale ends up with everything I write being "writeable" if you re-open the file after it has been produced. I decided to import Formatting into the Worksheet module like this: import Formatting self.Formatting = Formatting.Protection self.__cell_protect = 1 self.__formula_hidden = 0 which is the defaults in the Protection class anyway but now when I do my create file routine when I try to change the cell_protect variable to 0 it makes absolutely no effect. The code has been written as such: if protection: work_sheet.set_protect(protection) work_sheet.set_password(password) else: pass for each_heading in each_work_sheet[1]: work_sheet.write(7, heading_cnt, str(each_heading), header_style) heading_cnt += 1 vert_cnt = 8 for each_set in each_work_sheet[2]: horiz_cnt = 0 for data_set in each_set: work_sheet.cell_protect = 1 work_sheet.formula_hidden = 1 if len(str(data_set)) < 1: work_sheet.cell_protect = 0 work_sheet.formula_hidden = 0 work_sheet.write(vert_cnt, horiz_cnt, ' ') horiz_cnt += 1 else: work_sheet.write(vert_cnt, horiz_cnt, str(data_set), data_style) horiz_cnt += 1 vert_cnt += 1 As you can see I only want to be able to write to cells that have a string '' which is parsed correctly through to data which was originally extracted from a database. The problem is that I can only seem to set it to protect all written cells or not. Any advice or help would be most appreciated. :) Chris From stefan.behnel-n05pAM at web.de Sun Feb 18 10:38:15 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 18 Feb 2007 16:38:15 +0100 Subject: xml.dom.minidom memory usage In-Reply-To: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> References: <1170359470.815711.95470@a75g2000cwd.googlegroups.com> Message-ID: <45d872ea$0$20289$9b4e6d93@newsspool3.arcor-online.net> Dan wrote: > I'm using python's xml.dom.minidom module to generate xml files, and > I'm running into memory problems. Then take a look at cElementTree. It's part of Python 2.5 and is available as a separate module for Python 2.4. It's fast, has a very low memory profile and if you ever decide to need more features, there's lxml to the rescue. You might also consider streaming your XML piece by piece instead of creating in-memory trees. Python's generators are a good starting point here. Stefan From eurleif at ecritters.biz Mon Feb 26 20:06:45 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 26 Feb 2007 20:06:45 -0500 Subject: Lists: Converting Double to Single In-Reply-To: References: Message-ID: <45e38410$0$6830$4d3efbfe@news.sover.net> rshepard at nospam.appl-ecosys.com wrote: > So I have lists that look like this: [1, 2, 3, 4, 5]. When I > concatenate lists, I end up with a list of lists that looks like > this: [[1, 2, 3. 4, 5]. [6, 7. 8, 9. 10]]. Really? >>> [1, 2, 3, 4, 5] + [6, 7, 8, 9, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > Then, I average the column values so I end up with a single list, but > with two brackets on each end, for example, [[3.5, 4.5, 5.5, 6.5, > 7.5]]. > > Unfortunately, when I try to use that last list in a NumPy function, > I'm told that it cannot be broadcast to the correct shape. So, what I > want to do is strip the extra brackes from each end to leave just > [3.5, 4.5, 5.5, 6.5, 7.5]. l = l[0] From donn at u.washington.edu Wed Feb 7 13:05:36 2007 From: donn at u.washington.edu (Donn Cave) Date: Wed, 07 Feb 2007 10:05:36 -0800 Subject: IOError: [Errno 4] Interrupted system call References: Message-ID: In article , Marco wrote: > Hello,every one, I meet a question: > > in my old script, I usually use os.popen2() to get info from standard > unix(LinuX) program like ps,ifconfig... > > Now, I write a OO-based programme, I still use os.popen2( check > whether mplayer still working via ps command ), but some things I got > the following message: > > Traceback (most recent call last): > File "./mkt.py", line 351, in loop_timeout > self.process(self.event.get_next()) > File "./mkt.py", line 361, in process > self.player.play(command[1]) > File "./mkt.py", line 107, in play > if self.is_playing(): > File "./mkt.py", line 78, in is_playing > info = rfd.readlines() > IOError: [Errno 4] Interrupted system call > > why? Thank you! Some signal was evidently delivered to your process, while you had a "slow" read in progress (i.e., not from disk.) The read was interrupted to deliver the signal. Look for signal handlers in your code and any library functions you call. I hope library functions don't have signal handlers, sounds like a horrible idea to me. If your code has a signal handler for SIGCHLD, try to get rid of that - the handler itself is causing your problem. OO (Object Oriented?) doesn't have anything to do with the problem, that I can think of. Donn Cave, donn at u.washington.edu From fuzzyman at gmail.com Thu Feb 8 19:35:47 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 8 Feb 2007 16:35:47 -0800 Subject: Looking for a MoinMoin guru - MoinMoin+SpamBayes == no wiki spam? In-Reply-To: References: Message-ID: <1170981347.050263.181360@j27g2000cwj.googlegroups.com> On Feb 9, 12:31 am, s... at pobox.com wrote: > I have this idea that I should be able to write a security policy for > MoinMoin which uses SpamBayes to judge the appropriateness of any given > submission. It would be more accurate and faster than the current default > security policy in MoinMoin. I started to work on it and have something > that seems to be working on the SpamBayes side of things, but I can't get > the MoinMoin side of the equation to balance. > > My messages to the moin-user mailing list have so far fallen on blind eyes, > so I'm broadening my search for a MoinMoin expert who would like to help me > finish off this demonstration. If you're interested in pursuing this idea > here are a couple URLs: > > * The current code: > > http://spambayes.cvs.sourceforge.net/spambayes/spambayes/spambayes/Mo... > > * My messages to moin-user: > > http://article.gmane.org/gmane.comp.web.wiki.moin.general/4381/match=... > http://article.gmane.org/gmane.comp.web.wiki.moin.general/4488/match=... > > The motivation for the concept is in the docstring of the module as well as > in the messages, so I won't belabor the point here. As one of the current > "editors" of the Python wiki I can tell you the current scheme of using > lists of "naughty words" to identify potential wiki spam is far from > perfect. There's also the motivation found here: > > http://www.publicradio.org/columns/futuretense/ > > Scroll down and listen to the February 1st episode. > You could also try akismet which is designed for finding spam 'comments' in blogs, a similar problem area. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > Thanks, > > Skip From mccredie at gmail.com Thu Feb 8 13:40:56 2007 From: mccredie at gmail.com (Matimus) Date: 8 Feb 2007 10:40:56 -0800 Subject: Functions, parameters In-Reply-To: References: Message-ID: <1170960056.183860.113580@h3g2000cwc.googlegroups.com> >>> Poll.objects.filter(question__startswith='What') That is an example of a keyword argument. You can read about it in the Python Tutorial: http://docs.python.org/tut/node6.html#SECTION006720000000000000000 -Matt From eh at mad.scientist.com Wed Feb 21 11:33:57 2007 From: eh at mad.scientist.com (Eirikur Hallgrimsson) Date: Wed, 21 Feb 2007 11:33:57 -0500 Subject: Creating a daemon process in Python In-Reply-To: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> References: <1172073944.018809.198830@q2g2000cwa.googlegroups.com> Message-ID: <45DC7475.8030508@mad.scientist.com> Sakagami Hiroki wrote: > Hi, > > What is the easiest way to create a daemon process in Python? I find that this works great. I just pasted my copy, I think you can find it via Google. Eirikur # Daemon Module - basic facilities for becoming a daemon process # By Coy Krill # Combines ideas from Steinar Knutsens daemonize.py and # Jeff Kunces demonize.py """Facilities for Creating Python Daemons""" import os import time import sys class NullDevice: def write(self, s): pass def daemonize(): if (not os.fork()): # get our own session and fixup std[in,out,err] os.setsid() sys.stdin.close() sys.stdout = NullDevice() sys.stderr = NullDevice() if (not os.fork()): # hang around till adopted by init ppid = os.getppid() while (ppid != 1): time.sleep(0.5) ppid = os.getppid() else: # time for child to die os._exit(0) else: # wait for child to die and then bail os.wait() sys.exit() From troy.melhase at gmail.com Fri Feb 23 17:39:03 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Fri, 23 Feb 2007 13:39:03 -0900 Subject: Having multiple instances of a single application start a single instance of another one In-Reply-To: <45df6400$0$489$cc7c7865@news.luth.se> References: <45df6400$0$489$cc7c7865@news.luth.se> Message-ID: > The first time A starts, it should open a B process and start > communicating with it. All other times an A instance starts it should > simply talk with the B that already is open. B should write its process id to a location known by both applications. When A starts, it should read that PID from the file and attempt to communicate with the process having that PID. When B starts, it should also check for the file. If it's found and if the PID in it is present in the process table, then B should exit. Otherwise, it should start normally and write its own PID to the file. From steveo at syslang.net Wed Feb 21 17:30:26 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 21 Feb 2007 17:30:26 -0500 (EST) Subject: Question about classes and possible closure. Message-ID: This is all an intro learning experience for me, so please feel free to explain why what I'm trying to do is not a good idea. In the Cookbook, they have a recipe for how to create global constants. ----------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__[name]=value import sys sys.modules[__name__]=_const() ---------------- I'd like to be able to create constants within a class. (Yes I understand that uppercase names is a far better and easier convention but this is a learning experience for me.) I can't get this to work, but my idea is that MyClass is defined thusly: class ConstError(TypeError): pass class Myclass: def mprint(self): print "C1 = ", self._C1 # Define a subclass to create constants. It refs upself to access # the uplevel copy of self. class _const: class ConstError(TypeError): pass def __setattr__(_upself,name,value): if upself.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name else: print "Just set something" upself.__dict__[name]=value # I want the const instance to be contained in this class so I # instantiate here in the constructor. def __init__(self): upself = self upself.consts = const() upself.consts._C1 = 0 setattr(upself.consts, "_C1", 44) self = upself Then the call in another file is this: #! /usr/bin/python from c2 import Myclass foo = Myclass() foo.mprint() # end Is it possible to nest a class in another class and is it possible to make this work? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From buzzard at urubu.freeserve.co.uk Sun Feb 11 20:28:40 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 12 Feb 2007 01:28:40 +0000 Subject: Generating pdf files in epydoc on Windows In-Reply-To: References: Message-ID: <45cfc90f.0@entanet> Don Taylor wrote: > Does anyone know what is needed to install to get epydoc to generate pdf > files on Windows. Besides epydoc itself of course. > > Maybe there is a more appropriate forum to ask newbie questions about > epydoc? > As I remember, LaTeX and ghostscript. Duncan From joanne.matthews at bbsrc.ac.uk Tue Feb 20 07:29:10 2007 From: joanne.matthews at bbsrc.ac.uk (joanne matthews (RRes-Roth)) Date: Tue, 20 Feb 2007 12:29:10 -0000 Subject: Weird result returned from adding floats depending on order I add them Message-ID: I'm getting different results when I add up a list of floats depending on the order that I list the floats. For example, the following returns False: def check(): totalProp=0 inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1] for each in inputs: totalProp+=each print "totalProp=",totalProp if totalProp != 1: print "Your proportions must add up to 1" return False return True However, if I swap, the 4th and 5th list items like this: totalProp=0 inputs=[0.2,0.2,0.2,0.2,0.1,0,0.1] for each in inputs: totalProp+=each print "totalProp=",totalProp if totalProp != 1: print "Your proportions must add up to 1" return False return True I get True returned. Can anyone tell me whats going on and how I can avoid the problem. Thanks Joanne Matthews From skip at pobox.com Fri Feb 2 16:07:00 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 2 Feb 2007 15:07:00 -0600 Subject: Python does not play well with others In-Reply-To: <7xtzy48jg3.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <17859.42996.963042.688428@montanaro.dyndns.org> Paul> Why should the hosting provider need to devote attention to Paul> something like that? MySQLdb or something like it should be Paul> included with Python, ... What about Firebird? Oracle? Sybase? Who maintains them in the core? MySQLdb is quite stable outside the core. What would adding it to the core do other than adding a lot of maintenance overhead to the developers' group? How many versions of MySQL should the Python developers test with? How many versions of Python? How many different platforms? Who decides? If *all* you're talking about are relational database adaptors I see the obvious candidates: database: Sybase, Oracle, MySQL, SQLite, ODBC, Firebird database versions: who knows? assume two per database python versions: 2.4, 2.5, 2.6, 3.0? platforms: windows, pick two linux flavors, solaris Those numbers give me 6 * 2 * 4 * 4 == 192 combinations to test. Ignore Python 2.4. That brings it down to 144. Only test on one linux variant and skip solaris. Now you're at 72. Leave Firebird and Sybase out of the mix. Now you're down to 48. That's still a fair sized burden. Now extend the problem to non-database packages. It seems to me that the PyBots project would be a better way to address the combinatorial explosion caused by supporting multiple versions of multiple packages on multiple platforms with multiple versions of Python: http://www.pybots.org/ Do you have a favorite third-party package? A favorite platform? A preferred version of your package? Set up one or more buildbots for it. Whenever checkins occur on active Python branches occur (currently 2.5 and SVN head, but easily extended to newer versions) your bots get built. You can note the problem and either encourage a change to Python or to your favorite package. This sort of solution has a couple advantages: * Presence of a buildbot implies some level of interest by the community at large. When the guy maintaining the HPUX-10 buildbot for the OpenView widget set takes it down and nobody steps in to pick up the slack, it suggests nobody cares enough about that combination anymore. * It scales, both in people and compute resources. Skip From sjmachin at lexicon.net Fri Feb 2 10:30:41 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 Feb 2007 07:30:41 -0800 Subject: division by 7 efficiently ??? In-Reply-To: <1170417838.602781.96220@s48g2000cws.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170417838.602781.96220@s48g2000cws.googlegroups.com> Message-ID: <1170430241.042052.138150@h3g2000cwc.googlegroups.com> On Feb 2, 11:03 pm, "Bart Ogryczak" wrote: > On Feb 1, 3:42 am, krypto.wiz... at gmail.com wrote: > > > How to divide a number by 7 efficiently without using - or / operator. > > We can use the bit operators. I was thinking about bit shift operator > > but I don't know the correct answer. > > It?s quiet simple. x == 8*(x/8) + x%8, so x == 7*(x/8) + (x/8 + x%8) > x/8 == x>>3, x%8 == x&7 > And there you have it, function rounds upwards for numbers not > divisible by 7. Gotta change int(x>0) to int(x>3) to round normally, > or int(x>6) to round downwards. > > def d7(x): > if(x>>3 == 0): return int(x>0) > return (x>>3)+d7((x>>3)+(x&7)) I doubt that a recursive function call (even a tail-recursive one) comes near what the OP and his interrogators mean by "efficiently". Nicko has already given the answer for the case where a 31-bit non- negative dividend is required. Here are some examples of the technique for cases where smaller numbers are found e.g. in date arithmetic. def div7a(N): assert 0 <= N <= 684 r = (N << 3) + N r = (r << 3) + N r = (r << 2) + N r >>= 11 return r def div7b(N): assert 0 <= N <= 13109 r = (N << 3) + N r = (r << 3) + N r = (r << 3) + N r = (r << 3) + N r = (r << 1) + N r >>= 16 return r What's going on there? Well, using the first example, (2 ** 11) // 7 and rounded to the higher integer is 293. So 293 / 2048 is an approximation to 1 / 7. Dividing by 2048 is a doddle. The shift-left- add stuff is doing the multiplication by 293, unrolled loop, one cycle per line when implemented as a SHLnADD instruction from the HP PA-RISC architecture. Unsigned division otherwise would take 32 DS (divide step) instructions. FWIW, gcc emits code for the Intel IA32 architecture that gloriously "misuses" the LEAL instruction to get the same reg1 = (reg2 << n) + reg3 effect. Any relevance to this newsgroup? Yes, there's a lot of pre-computation involved there. Python is an excellent language for debugging such stuff and generating include files for a production code. Cheers, John From tdelaney at avaya.com Wed Feb 21 18:21:29 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 22 Feb 2007 10:21:29 +1100 Subject: f---ing typechecking Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ECAF@au3010avexu1.global.avaya.com> Nick Craig-Wood wrote: > Which appears to support my point, x (and a for that matter) are the > same for both methods wheter you do x = x + a or x += a. > > The mechanism is different certainly, but the result should be the > same otherwise you are breaking the basic rules of arithmetic the > programmer expects (the rule of least suprise). No - for a mutable object, x may be bound to the original, but *modified* object after augmented assignment. Any name also bound to that object will therefore refer to the modified object. For an immutable object, augmented assignment will not ever modify the original object. The two operations may have *very* different effects. >>> a = [1] >>> b = [2] >>> c = a >>> d = a >>> c = a + b >>> a, b, c ([1], [2], [1, 2]) >>> id(a), id(b), id(c) (11082528, 11271104, 11082328) >>> a += b >>> a, b, c ([1, 2], [2], [1, 2]) >>> id(a), id(b), id(c), a is d (11082528, 11271104, 11082328, True) Tim Delaney From info at wingware.com Fri Feb 9 14:04:35 2007 From: info at wingware.com (Wingware Announce) Date: Fri, 09 Feb 2007 14:04:35 -0500 Subject: ANN: Wing IDE 2.1.4 Released Message-ID: <1171047875.7665.19.camel@localhost> Hi, I'm happy to announce version 2.1.4 of Wing IDE, an integrated development environment for the Python programming language. This is a bug fix release that among other things fixes handling of UTF-8 byte order marks, improves auto-completion for PyQt 4, reports exceptions correctly in Python < 2.2, fixes some problems with Subversion 1.4, does better adaptive scrolling on OS X, and displays menus correctly in Hebrew locales. The release can be downloaded from: http://wingware.com/downloads A detailed list of all changes is available here: http://wingware.com/pub/wingide/2.1.4/CHANGELOG.txt Wing IDE provides powerful debugging, editing, code intelligence, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Highlights of Wing IDE 2.1: * Professional quality code editor * Visual Studio, VI/Vim, Emacs, and Brief key bindings * Auto-completion, call tips, and source browser * Graphical debugger for Python, Zope, and Plone * Subversion, CVS, and Perforce integration * Powerful search interface * User-extensible with Python scripts * Templates (code snippets), bookmarks, folding, macros, and more Some features are available in Wing IDE Pro only -- for details see http://wingware.com/wingide/features This release is available for Windows (2000+), Linux, and Mac OS X (10.3+ with X11 installed) and can be compiled from sources on *BSD, Solaris, and other Posix operating systems. For more information see: Product Info: http://wingware.com/products Sales: http://wingware.com/store/purchase Sincerely, The Wingware Team From dimitri.pater at gmail.com Tue Feb 13 08:44:05 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Tue, 13 Feb 2007 14:44:05 +0100 Subject: favourite editor In-Reply-To: <51ed8$45cf0d6e$d443bb3a$7257@news.speedlinq.nl> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> <51ed8$45cf0d6e$d443bb3a$7257@news.speedlinq.nl> Message-ID: You could try SPE, > but that's really unstable, > and no help manual to read ;-) But, there is a tutorial on SPE here: www.serpia.org/spe regards, Dimitri -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Tue Feb 27 06:55:41 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 27 Feb 2007 11:55:41 GMT Subject: Python Source Code Beautifier In-Reply-To: References: Message-ID: <1%UEh.4287$8U4.2480@news-server.bigpond.net.au> Franz Steinhaeusler: > Hello, I did not find any reasonable pyhton source code beautifier > program (preferable gui). > ... > convert: > ... > from "is" to "==" and "is not" to "!=" (ok a find replace could do that > easily also), but in a program that would be more comfortable. That's an unsafe conversion. I don't think it is possible for a reasonable program to determine statically that "is" is equivalent to "==" except for trivial pieces of code. Neil From http Wed Feb 14 16:37:28 2007 From: http (Paul Rubin) Date: 14 Feb 2007 13:37:28 -0800 Subject: threading and multicores, pros and cons References: <7xodnx2vir.fsf@ruckus.brouhaha.com> <7x7iulqlvx.fsf@ruckus.brouhaha.com> <1171488267.433565.228110@a75g2000cwd.googlegroups.com> Message-ID: <7xejosctev.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" writes: > Java has historically had no support at all for real multiple process > solutions (akin to fork() or ZwCreateProcess() with NULL > SectionHandle), which should make up the vast majority of parallel > programs (basically all of those except where you don't want memory > protection). I don't know what ZwCreateProcess is (sounds like a Windows-ism) but I remember using popen() under Java 1.1 in Solaris. That at least allows launching a new process and communicating with it. I don't know if there was anything like mmap. I think this is mostly a question of library functions--you could certainly write JNI extensions for that stuff. > Has this changed in recent Java releases? Is there a way to use > efficient copy-on-write multiprocess architectures? I do think they've been adding more stuff for parallelism in general. From hg at nospam.org Sat Feb 10 04:54:10 2007 From: hg at nospam.org (hg) Date: Sat, 10 Feb 2007 10:54:10 +0100 Subject: Hacking in python References: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> Message-ID: Calvin Spealman wrote: > http://en.wikipedia.org/wiki/Hacker_%28disambiguation%29 > > Educate yourself on what hacking actually is. We're all hackers, > because it just means we get the most out of code, enjoy pushing our > technology to the limit, and generally love programming. The term has > been abused by the media and you don't do much more than show your own > naiveness by asking such a question. You also do a great job of > insulting everyone on this list. > > On 2/10/07, enes naci wrote: >> >> i would like to know about hacking in python too whether its illegal >> or not is not the point and anyway it doesn't mean i'm gong to use it. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > Read my blog! I depend on your acceptance of my opinion! I am interesting! > http://ironfroggy-code.blogspot.com/ So that was that weird feeling I felt ... insulted hg From bearophileHUGS at lycos.com Wed Feb 21 14:09:12 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Feb 2007 11:09:12 -0800 Subject: builtin set literal In-Reply-To: References: <1171589112.890990.147030@h3g2000cwc.googlegroups.com> <1171592265.316602.234820@s48g2000cws.googlegroups.com> <1171612923.145381.220960@p10g2000cwp.googlegroups.com> <1171988959.628359.260710@l53g2000cwa.googlegroups.com> Message-ID: <1172084952.261314.4700@v33g2000cwv.googlegroups.com> Steven Bethard: > take a look at the current state of tuples: > 1, 2 > 1, > () That's not a good situation. I presume the situation/syntax of tuples in Python 2.x can't be improved. But can it be improved for Py 3.0? Notes: - I think in Matlab a single element is seen as the same thing as an array with len = 1. - I think Ruby solves the problem of the list/tuple with a freezing function/operator (like I suggested some time ago). Bye, bearophile From deets at nospam.web.de Wed Feb 28 08:59:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Feb 2007 14:59:24 +0100 Subject: pyopengl vs directpython References: Message-ID: <54lg5sF20rdnnU2@mid.uni-berlin.de> Gigs_ wrote: > can someone tell me which is better for making 3d game in python. > something like tennis simulation OpenGL is platform-agnostic. If you ever want to reach people on linux or macs, use that. Beyond that I've got no idea which is technically superior - but John Carmack seems to favor OpenGL :) Diez From devicerandom at gmail.com Thu Feb 15 18:10:47 2007 From: devicerandom at gmail.com (massimo s.) Date: 15 Feb 2007 15:10:47 -0800 Subject: Pep 3105: the end of print? In-Reply-To: References: Message-ID: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Isn't the very concept of major releases (1.x, 2.x, 3.x) that they *can* be not backwards-compatible with previous releases? m. From joncfoo at gmail.com Mon Feb 26 11:34:54 2007 From: joncfoo at gmail.com (joncfoo at gmail.com) Date: 26 Feb 2007 08:34:54 -0800 Subject: message processing/threads In-Reply-To: <45d7976f$0$327$e4fe514c@news.xs4all.nl> References: <45d7976f$0$327$e4fe514c@news.xs4all.nl> Message-ID: <1172507693.989025.95530@j27g2000cwj.googlegroups.com> Thank you all for your input. I now have some new ways that I need to look into and see what fits best. Thanks once again, Jonathan From robert.kern at gmail.com Thu Feb 8 19:02:25 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 08 Feb 2007 16:02:25 -0800 Subject: Re-installing Numeric and PIL Files In-Reply-To: <45CBB3CA.7010501@invalid.com> References: <14Jyh.16927$ji1.13695@newssvr12.news.prodigy.net> <45CBB3CA.7010501@invalid.com> Message-ID: W. Watson wrote: > Here's the program I ran. > > ### begin > #!/usr/bin/python > > # Check mysys > > import sys > print sys.executable > > ### end > > It put up a black screen in a flash and disappeared. Run it from the terminal or execute those lines in the interactive interpreter in IDLE. Also, you may want to use the Tutor list, instead of comp.lang.python. It is more geared towards the questions you are asking. http://mail.python.org/mailman/listinfo/tutor -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tiedon_jano at hotmail.com Thu Feb 22 13:53:42 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 22 Feb 2007 18:53:42 GMT Subject: Possible to set cpython heap size? In-Reply-To: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> References: <1172163966.925291.50190@t69g2000cwt.googlegroups.com> Message-ID: Andy Watson kirjoitti: > I have an application that scans and processes a bunch of text files. > The content I'm pulling out and holding in memory is at least 200MB. > > I'd love to be able to tell the CPython virtual machine that I need a > heap of, say 300MB up front rather than have it grow as needed. I've > had a scan through the archives of comp.lang.python and the python > docs but cannot find a way to do this. Is this possible to configure > the PVM this way? > > Much appreciated, > Andy > -- > Others have already suggested swap as a possible cause of slowness. I've been playing with my portable (dual Intel T2300 @ 1.66 GHz; 1 GB of mem ; Win XP ; Python Scripter IDE) using the following code: #======================= import datetime ''' # Create 10 files with sizes 1MB, ..., 10MB for i in range(1,11): print 'Writing: ' + 'Bytes_' + str(i*1000000) f = open('Bytes_' + str(i*1000000), 'w') f.write(str(i-1)*i*1000000) f.close() ''' # Read the files 5 times concatenating the contents # to one HUGE string now_1 = datetime.datetime.now() s = '' for count in range(5): for i in range(1,11): print 'Reading: ' + 'Bytes_' + str(i*1000000) f = open('Bytes_' + str(i*1000000), 'r') s = s + f.read() f.close() print 'Size of s is', len(s) print 's[274999999] = ' + s[274999999] now_2 = datetime.datetime.now() print now_1 print now_2 raw_input('???') #======================= The part at the start that is commented out is the part I used to create the 10 files. The second part prints the following output (abbreviated): Reading: Bytes_1000000 Size of s is 1000000 Reading: Bytes_2000000 Size of s is 3000000 Reading: Bytes_3000000 Size of s is 6000000 Reading: Bytes_4000000 Size of s is 10000000 Reading: Bytes_5000000 Size of s is 15000000 Reading: Bytes_6000000 Size of s is 21000000 Reading: Bytes_7000000 Size of s is 28000000 Reading: Bytes_8000000 Size of s is 36000000 Reading: Bytes_9000000 Size of s is 45000000 Reading: Bytes_10000000 Size of s is 55000000 Reading: Bytes_9000000 Size of s is 265000000 Reading: Bytes_10000000 Size of s is 275000000 s[274999999] = 9 2007-02-22 20:23:09.984000 2007-02-22 20:23:21.515000 As can be seen creating a string of 275 MB reading the parts from the files took less than 12 seconds. I think this is fast enough, but others might disagree! ;) Using the Win Task Manager I can see the process to grow to a little less than 282 MB when it reaches the raw_input call and to drop to less than 13 MB a little after I've given some input apparently as a result of PyScripter doing a GC. Your situation (hardware, file sizes etc.) may differ so that my experiment does not correspond it, but this was my 2 cents worth! HTH, Jussi From maric at aristote.info Tue Feb 13 23:07:51 2007 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Feb 2007 05:07:51 +0100 Subject: threading and multicores, pros and cons Message-ID: <200702140507.52868.maric@aristote.info> This is a recurrent problem I encounter when I try to sell python solutions to my customers. I'm aware that this problem is sometimes overlooked, but here is the market's law. I've heard of a bunch of arguments to defend python's choice of GIL, but I'm not quite sure of their technical background, nor what is really important and what is not. These discussions often end in a prudent "python has made a choice among others"... which is not really convincing. If some guru has made a good recipe, or want to resume the main points it would be really appreciated. regards, -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 Mobile: +33 632 77 00 21 From jonathansamuel at geocities.com Sun Feb 18 18:51:13 2007 From: jonathansamuel at geocities.com (Jonathan Mark) Date: 18 Feb 2007 15:51:13 -0800 Subject: Is there any way to automatically create a transcript of an interactive Python session? Message-ID: <1171842673.363336.121080@l53g2000cwa.googlegroups.com> Some languages, such as Scheme, permit you to make a transcript of an interactive console session. Is there a way to do that in Python? From rshepard at nospam.appl-ecosys.com Wed Feb 28 15:40:29 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 28 Feb 2007 20:40:29 GMT Subject: Extract String From Enclosing Tuple Message-ID: I'm a bit embarrassed to have to ask for help on this, but I'm not finding the solution in the docs I have here. Data are assembled for writing to a database table. A representative tuple looks like this: ('eco', "(u'Roads',)", 0.073969887301348305) Pysqlite doesn't like the format of the middle term: pysqlite2.dbapi2.InterfaceError: Error binding parameter 1 - probably unsupported type. I want to extract the 'Roads', part from the double-quoted enclosing tuple. The unicode part should be automatically removed when the string is printed, but I suspect it's the double quotes and extra parentheses that are the problem. I know that tuples are immutable, but I thought that I could slice it. If so, I'm not doing it correctly, because each attempt results in TypeError: unsubscriptable object Even when I assign that middle term to a variable before assembling the tuple for insertion in the database, I just cannot get the job done. Whether in the tuple of three terms or by itself, I haven't applied the proper technique. Insight appreciated. Rich From irmen.NOSPAM at xs4all.nl Mon Feb 19 15:14:50 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 19 Feb 2007 21:14:50 +0100 Subject: Forking SocketServer daemon -- updating state In-Reply-To: References: Message-ID: <45da053a$0$324$e4fe514c@news.xs4all.nl> Reid Priedhorsky wrote: > Another possibility is that the signal handler simply sets a needs_update > flag, which I could check for in a handle_request() loop. The disadvantage > here is that the update wouldn't happen until after the next request is > handled, and I would like the state to be available for that next request. > A solution might be to send a signal followed by a dummy request, which > seems a bit awkward. > > Any other ideas or suggestions? Just send a special type of request that signifies that an update is wanted, and act on that? Basically you need to find a way to let two processes talk to each other. There are a lot of possibilities here (IPC). The simplest would be to reuse the one you already have (the request handler!). Another solution might be to use Pyro. Or just open a custom socket yourself to send messages. Or stick with your idea of using a signal handler. But I don't know if you can let a signal handler run for a long time (as you already asked yourself), and it won't be portable to Windows for instance. You could maybe use threads instead, and then use some form of thread synchronization primitives such as threading.Event (threads would remove the need to do IPC). Hope this helps a bit, --Irmen From thinker at branda.to Mon Feb 5 07:54:48 2007 From: thinker at branda.to (Thinker) Date: Mon, 05 Feb 2007 20:54:48 +0800 Subject: subprocess stdin encoding In-Reply-To: <1170659429.228953.52200@q2g2000cwa.googlegroups.com> References: <1170659429.228953.52200@q2g2000cwa.googlegroups.com> Message-ID: <45C72918.4040603@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 yc wrote: > I have a encoding problem during using of subprocess. The input is > a string with UTF-8 encoding. > > the code is: > > tokenize = > subprocess.Popen(tok_command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,close_fds=True,shell=True) > > > (tokenized_text,errs) = tokenize.communicate(t) > > the error is: File "/usr/local/python/lib/python2.5/subprocess.py", > line 651, in communicate return self._communicate(input) File > "/usr/local/python/lib/python2.5/subprocess.py", line 1115, in > _communicate bytes_written = os.write(self.stdin.fileno(), > input[:512]) UnicodeEncodeError: 'ascii' codec can't encode > character u'\xa9' in position 204: ordinal not in range(128) > > > How I change the default encoding from "ascii" to "utf-8"? > > Ying Chen > find code like def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "ascii" # Default value set by _PyUnicode_Init() if 0: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] in site.py . and change if 0: to if 1: to enable string encoding. Now, you can execute python interpreter with LC_CTYPE='UTF-8'. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFFxykX1LDUVnWfY8gRAseRAKCjAksq22bD2YoOt5IEOIcwOB2KiQCbBvvw lEccSfEaeOhzAUbvulnDoDk= =y4Jj -----END PGP SIGNATURE----- From pablo at sigex.com Sat Feb 24 09:51:58 2007 From: pablo at sigex.com (pablo at sigex.com) Date: 24 Feb 2007 06:51:58 -0800 Subject: Performance project for the SigEx Foundry In-Reply-To: <1172173230.420259.123190@l53g2000cwa.googlegroups.com> References: <1172060154.122555.190330@k78g2000cwa.googlegroups.com> <1172173230.420259.123190@l53g2000cwa.googlegroups.com> Message-ID: <1172328718.340627.199870@k78g2000cwa.googlegroups.com> On Feb 22, 8:40 pm, pierre_marie_dur... at yahoo.fr wrote: > On Feb 21, 1:15 pm, p... at sigex.com wrote: > > > have been testing performances of different scripting languages > > fordatabase access, text processing and client application data > > transfer. So far, I am getting better performance from PHP, but I > > don't have any hard data to back it up compared to others. > > > This is a large project for theSigExFoundryand it involves hundreds > > of servers. I am looking for articles/studies/benchmarks on the > > subject. > > > Thank you, > > > Pablo > > Server Side Developer > > Student for theSigExFoundry, > > bySigExVentures > > Hi Pablo, > > It's a good question. You want to really understand what you are doing > this benchmark for. In my opinion, you should go for the language that > fits your needs and focus on performance optimization for that > language. I would be more inclined to go with PHP, but that's a > personal choice. I'm sure you can search performance for these > languages and come up with lots of ressources on the web. > > Pierre-Marie Durand Pierre-Marie, Thanks for the feedback. You are right, for now, I am sticking to PHP, but I would like to read more about this subject. Bearophile's link is a good start. Thanks, Pablo Server Side Developer Student for the SigEx Foundry, SigEx Ventures From kavithapython at yahoo.co.in Mon Feb 26 05:38:47 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Mon, 26 Feb 2007 10:38:47 +0000 (GMT) Subject: newbie question(file-delete trailing comma) Message-ID: <860807.3780.qm@web7805.mail.in.yahoo.com> hi, i have a file which has the contents as follows: a,b,c,d, a1,b1,c1,d1, a2,b2,c2,d2, i would like to delete all the trailing commas,, if someoneknows pls help me,, kavitha --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Feb 28 05:13:57 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 28 Feb 2007 10:13:57 +0000 Subject: Python, SOAP & SSL In-Reply-To: <5B59870CA143DD408BD6279374B74C8B053F40DC@MAIL02.austin.utexas.edu> References: <5B59870CA143DD408BD6279374B74C8B053F40DC@MAIL02.austin.utexas.edu> Message-ID: <8c7f10c60702280213g2528d43frefee02a350906317@mail.gmail.com> On 2/28/07, Barker, CJ wrote: > Was this ever solved? You might get more feedback about this on the Python web services list at . -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning MSN: small_values From troy at gci.net Sun Feb 18 23:38:13 2007 From: troy at gci.net (Troy Melhase) Date: Sun, 18 Feb 2007 19:38:13 -0900 Subject: ANN: java2python 0.2 Message-ID: <200702181938.27415.troy@gci.net> java2python - Java to Python Source Code Translator --------------------------------------------------- java2python 0.2 Released 18 February 2007 What is java2python? ------------------------------------------------------------------------------ java2python is a simple but effective tool to translate Java source code into Python source code. It's not perfect, and does not aspire to be. What's new in this release? ------------------------------------------------------------------------------ Small enhancement: added converstion of "public static void main" method into module "if __name__ == '__main__' block. Better classmethod support: fixed class/instance member formatting strings to account for classmethods. Slightly more pythonic: replace "x == None" expressions with "x is None" in output code, also replace "x != None" with "x is not None". Bugfix: Fixed dotted type identifiers. Better exception translation: added support for mapping java exception types to python exception types. Support for non-local base class members: added support for base class members via config modules. Bugfix: changed single % characters to %% in expression format strings. Small enhancement: added support for 'methodPreambleSorter' configuration item. With this value, config modules can specify how to sort method preambles (typically decorators). Where can I get java2python? ------------------------------------------------------------------------------ java2python is available for download from Google code: http://code.google.com/p/java2python/downloads/list Project page: http://code.google.com/p/java2python/ How do I use java2python? ------------------------------------------------------------------------------ Like this: $ j2py -i input_file.java -o output_file.py The command has many options, and supports customization via multiple configuration modules. What are the requirements? ------------------------------------------------------------------------------ java2python requires Python 2.5 or newer. Previous versions may or may not work. java2python requires ANTLR and PyANTLR to translate code, but translated code does not require ANTLR. What else? ------------------------------------------------------------------------------ java2python is installed with distutils. Refer to the Python distutils documentation for more information. The digest version is: $ tar xzf java2python-0.2.tar.gz $ cd java2python-0.2 $ python setup.py install java2python is licensed under the GNU General Public License 2.0. No license is assumed of (or applied to) translated source. I'm very interested in your experience with java2python. Please drop me an note with any feedback you have. Troy Melhase mailto:troy at gci.net -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From pythonnews at nospam.jmbc.fr Mon Feb 5 16:00:29 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Mon, 05 Feb 2007 22:00:29 +0100 Subject: wxPython: TextCtrl delayed update when using TE_RICH(2) In-Reply-To: References: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> <45c5aa41$0$21142$7a628cd7@news.club-internet.fr> <45c7533d$0$21148$7a628cd7@news.club-internet.fr> Message-ID: <45c79b14$0$21151$7a628cd7@news.club-internet.fr> > > This is almost totally wrong. There is no "new event loop" involved. > The OP is running a long task in the main thread, which is blocking > the event loop. When the event loop is blocked, the application will > not update and cannot be interacted with. It's that simple. The event > loop in a gui application doesn't "finish" until the application > exits. I appreciate the fact that it is not *completely* wrong... Try to get out of your point of view, maybe you'll find something interesting. Maybe the 'true' part of mine. Regards jm From duncan.booth at invalid.invalid Tue Feb 27 04:21:40 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Feb 2007 09:21:40 GMT Subject: How can I disable a device in windows using python References: <1172559034.411958.173670@v33g2000cwv.googlegroups.com> Message-ID: "Phoe6" wrote: > Hi all, > I am trying to disable the NIC card (and other cards) enabled in my > machine to test diagnostics on that card. > I am trying to disable it programmatic using python. I checked python > wmi and i could not find ways to disable/enable, (listing is however, > possible). > > Where should I look for to enable/disable devices in python. > Assuming you mean windows: If you don't mind doing it by spawning an external program try downloading devcon.exe from Microsoft's website (http://support.microsoft.com/kb/311272). Using devcon you can enumerate devices, enable or disable them and a variety of other things. For example, on my current machine I can disable or enable my wireless card with: C:\>devcon find *DEV_4222* PCI\VEN_8086&DEV_4222&SUBSYS_10418086&REV_02\4&214CFA8C&1&00E2: Intel(R) PRO/Wireless 3945ABG Network Connection 1 matching device(s) found. C:\>devcon disable *DEV_4222* PCI\VEN_8086&DEV_4222&SUBSYS_10418086&REV_02\4&214CFA8C&1&00E2: Disabled 1 device(s) disabled. C:\>devcon enable *DEV_4222* PCI\VEN_8086&DEV_4222&SUBSYS_10418086&REV_02\4&214CFA8C&1&00E2: Enabled 1 device(s) enabled. The most tricky bit is finding the correct id in the first bit, just do a wildcard find command and look for something appropriate. The enable and disable are exactly the same as the equivalent commands from the network connections window or the device manager. Oh, and don't forget if you want to use the full id for a device you'll have to escape the & characters or quote the argument. From rschroev_nospam_ml at fastmail.fm Sat Feb 3 19:12:06 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 04 Feb 2007 00:12:06 GMT Subject: confused about resizing array in Python In-Reply-To: References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: Dongsheng Ruan schreef: > "Roel Schroeven" wrote in message > news:vc8xh.325172$Au6.6345787 at phobos.telenet-ops.be... >> Ruan schreef: >>> Then how about Python's list? >>> >>> What is done exactly when list.append is executed? >>> >>> For list, is there another larger list initialized and the contents from >>> the old list is copied to it together with the new appended list? >> I'm not sure, but I think each time the list needs to grow, it doubles in >> size. That leaves room to add a number of elements before the allocated >> space needs to grow again. It's a frequently used approach, since it is >> quite efficient and the memory needed is never double the amount of memory >> strictly needed for the elements of the list. > You mentioned "it doubles in size". > > Are you saying that a new double sized array is allocated and the > contents of the old list is copied there? > > Then the old list is freed from memory? > > It seems to be what is called amortized constant. > > Say the list size is 100, before it is fully used, the append takes > O(1) time. But for the 101th element, the time will be O(100+1), and > then from then on, it is O(1) again. Like John Machin said in the > previous post? > > But on average, it is O(1). I guess this is the amortized constant. > Isn't it? I think so, more or less, but as I said I'm not entirely sure about how Python handles lists. One thing to keep in mind is that the list (like any other Python data structure) doesn't store the objects themselves; it only stores references to the objects. If the list needs to be copied, only the references are copied; the objects themselves can stay where they are. For small objects this doesn't make much difference, but if the objects grow larger it gets much more efficient if you only have to move the references around. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From bignose+hates-spam at benfinney.id.au Sat Feb 3 16:03:31 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 04 Feb 2007 08:03:31 +1100 Subject: Determining encoding of a file References: Message-ID: <87k5yzrm1o.fsf@benfinney.id.au> Tony Houghton writes: > In Linux it's possible for filesystems to have a different encoding > from the system's setting. Given a filename, is there a (preferably) > portable way to determine its encoding? If there were, PEP 263 would not be necessary. It's possible to *guess*, with no guarantee of getting the right answer; but it's far better to be explicitly *told* what the encoding is. -- \ "If we don't believe in freedom of expression for people we | `\ despise, we don't believe in it at all." -- Noam Chomsky | _o__) | Ben Finney From chris.peressotti at gmail.com Tue Feb 13 15:35:56 2007 From: chris.peressotti at gmail.com (chris.peressotti at gmail.com) Date: 13 Feb 2007 12:35:56 -0800 Subject: Undo os.remove Message-ID: <1171398956.060378.215530@q2g2000cwa.googlegroups.com> Hi. I just used os.remove to get rid of some files -- unfortunately, I realized afterward that I didn't really want to get rid of them. It isn't life-or-death, here, but is there any way for me to get these files back? - Chris From gerry at mxp.com Sat Feb 3 19:40:48 2007 From: gerry at mxp.com (Gerard White) Date: Sun, 4 Feb 2007 00:40:48 -0000 Subject: Modified BitTorrent site Message-ID: <000f01c747f5$1dbf89c0$1eda2d52@hometao> London based start up web services company. Looking for programmer(s) to build a modified BitTorrent e-commerce site. Knowledge of Python, PHP5, JavaScript, AJAX, DHTML Java Applets and MySQL. P2P framework with modified version of BitTorrent client, modern website "sales platform" interface, managed download, tracking, secure transactions and analysis tools. Remuneration negotiable. Contact gerry at mxp.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Tue Feb 6 09:05:09 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 6 Feb 2007 09:05:09 -0500 Subject: when will python 2.5 take in mainstream? In-Reply-To: <1170765935.772254.101930@q2g2000cwa.googlegroups.com> Message-ID: <20070206140509.25807.1440190216.divmod.quotient.11782@ohm> On 6 Feb 2007 04:45:35 -0800, Ben Sizer wrote: >On Feb 5, 4:15 pm, Jean-Paul Calderone wrote: >> It's very easy to maintain compatibility in the C API. I'm much more >> interested in compatibility at the Python layer, which is changed >> incompatibly much, much more frequently than is the C layer. > >Really? In all cases I've found, pure-Python extensions written for >2.4 work with 2.5. The same was true for 2.3 to 2.4 as well. And even >if I found one that didn't, it's highly likely I could fix it myself. If you have to fix it yourself, then it's broken, wouldn't you say? Huge amounts of my pure Python code was broken by Python 2.5. So yes, it happens. The same _wasn't_ true for 2.3 to 2.4 though. Python 2.5 was pretty unusual in this regard. > >The same doesn't apply to any C compiled extensions. Updating Python >breaks these, every time, and users typically have to wait months for >the library developer to compile a new version, every time. Or maybe >they can wade through the morass of "how do I compile this library on >Windows" threads here. Perhaps the C API remains the same but the real >issue is the binary API between extensions and Python changes every >couple of years or so. That's why I run 2.4 anywhere that needs >extensions. Sure, this happens too. I didn't suggest it doesn't, I just pointed out that I was less interested in it. :) Jean-Paul From citronelu at yahoo.com Sat Feb 3 05:43:44 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 3 Feb 2007 02:43:44 -0800 Subject: wxPython: TextCtrl delayed update when using TE_RICH(2) Message-ID: <1170499424.357462.36230@l53g2000cwa.googlegroups.com> I made a small wxPython app that retrieves web data; for visual logging I use a TextCtrl widget, and stdout is redirected to it, something like this: class RedirectOutput: def __init__(self, objectTxtCtrl): self.out = objectTxtCtrl def write(self, string): self.out.WriteText(string) [...] messages = wx.TextCtrl(panel, -1, "", size = (-1, 200), style = wx.TE_MULTILINE | wx.TE_RICH, name = "messages") myout = RedirectOutput(messages) sys.stdout = myout The web query is inside a function (def Execute), binded to a button. To simplify the story, consider the function looks like this: def Execute(self, evt): print "Start query" time.sleep(5) The "Start query" message should show in the *messages* box when I press the button. Instead, it shows only after the time.sleep(5) delay. If I don't use the wx.TE_RICH / wx.TE_RICH2 style on *messages*, the text shows before the time.sleep(5) I want to use wx.TE_RICH / wx.TE_RICH2 because of the 64k limitation of the standard TextCtrl. I'm using python 2.4.3 and wxpython 2.8.1.1 unicode, on WinXP SP2. Windows extensions are also installed. From rganesan at myrealbox.com Wed Feb 21 22:33:52 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Thu, 22 Feb 2007 09:03:52 +0530 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172103048.160783.309470@l53g2000cwa.googlegroups.com> Message-ID: >>>>> "Harlin" == Harlin Seritt writes: > I tried doing this: > text = 'supercalifragilisticexpialidocius' > open('sambleb.conf', 'wb').write(text) > Afterwards, I was able to successfully open the file with a text > editor and it showed: > 'supercalifragilisticexpialidocius' > I am hoping to have it show up some weird un-readable text. And then > of course be able to convert it right back to a string. Is this even > possible? Looks like you just want to obfuscate the string. How about this? import base64 text = 'supercalifragilisticexpialidocius' open('sambleb.conf', 'w').write(base64.encodestring(text)) print base64.decodestring(open('sambleb.conf', 'r').read()) Ganesan -- Ganesan Rajagopal From kooch54 at gmail.com Thu Feb 8 08:44:52 2007 From: kooch54 at gmail.com (Kooch54) Date: 8 Feb 2007 05:44:52 -0800 Subject: Group Membership in Active Directory Query In-Reply-To: <1170895960.022698.299500@h3g2000cwc.googlegroups.com> References: <1170858142.921674.130590@a75g2000cwd.googlegroups.com> <1170859017.416570.247920@v33g2000cwv.googlegroups.com> <1170872824.710879.272830@v45g2000cwv.googlegroups.com> <1170895960.022698.299500@h3g2000cwc.googlegroups.com> Message-ID: <1170942292.620399.102000@m58g2000cwm.googlegroups.com> On Feb 7, 7:52 pm, "alex23" wrote: > On Feb 8, 4:27 am, kooc... at gmail.com wrote: > > > First and foremost thanks for the feedback. Although I don't > > appreciate the slight dig at me. > > dummy = ldap_obj.simple_bind...... > > I _really_ don't think Uwe was intending any slight, 'dummy' generally > means 'dummy variable' ie it's just there to catch the value but it's > never used after that :) > > If you're doing a lot of AD work, I highly recommend Tim Golden's > active_directory module:http://timgolden.me.uk/python/ > active_directory.html > > His WMI module has also been a godsend on a number of occasions. > > - alex23 Alex- Thanks for your response and Uwe I apologize if I misunderstood and misinterpreted your comments. I am sorry. I have tried Tim's module called active_directory and it works really well. But I can't figure out how to connect to a specific group is I know the common name for it but not the DN and then return it's members. Example.... I know the group name is domain1\sharedaccess. How do I bind to that group and get the members. The domain isn't necessarily the defaultnamingcontext. It could be another domain in the forest. I need to be able to connect to any domain group and get it's members. Thanks again. From exarkun at divmod.com Mon Feb 12 09:40:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 12 Feb 2007 09:40:20 -0500 Subject: Help with Optimization of Python software: real-time audio controller In-Reply-To: <1171290098.998292.228980@v45g2000cwv.googlegroups.com> Message-ID: <20070212144020.25807.1403887471.divmod.quotient.19184@ohm> On 12 Feb 2007 06:21:39 -0800, Ross Ridge wrote: > >Paul Rubin wrote: >> I think you can't really do that, not just because of Python but also >> as a result of using a multitasking OS that's not especially designed >> for real time. You have to rely on some buffering in the audio >> hardware, so you don't have to be sample-accurate with the timings. > >For his application you don't need "sample-accurate" timings. Between >MIDI and synthesizer latency a few milliseconds of delay are inherent >in what he's trying to do, regardless of operatings system, and a >latency of 20 milliseconds or more is probably acceptable. Assuming >he's not trying to write his own synthesizer, he might just be able to >write his application in Python under Mac OS X. Yep. There are even some existing Python applications which deal with sound and manage to work with ~20ms samples. Jean-Paul From solrick51 at hotmail.com Thu Feb 1 08:43:37 2007 From: solrick51 at hotmail.com (solrick51 at hotmail.com) Date: 1 Feb 2007 05:43:37 -0800 Subject: Python design project Message-ID: <1170337417.236975.44070@l53g2000cwa.googlegroups.com> Dear community, I dont really know if this is the right way to do, otherwise my excuses for that. I'm a Dutch student, and graduating this year on my graphic design study. For my graduating study, I want to do some Python work and i'm lokking for a partner wich can help/ cooperate me in programming python. The project In short: The project subject is type, and i want to create a self generating type. I hope there are some interests, otherwist, thank you all.. Bye.. Rick From marco.giusti at gmail.com Sat Feb 10 09:16:08 2007 From: marco.giusti at gmail.com (Marco Giusti) Date: Sat, 10 Feb 2007 15:16:08 +0100 Subject: How to find all the same words in a text? In-Reply-To: <1171116005.380549.73690@l53g2000cwa.googlegroups.com> References: <1171114163.781621.263210@s48g2000cws.googlegroups.com> <1171116005.380549.73690@l53g2000cwa.googlegroups.com> Message-ID: <20070210141608.GD25935@localhost> On Sat, Feb 10, 2007 at 06:00:05AM -0800, Johny wrote: >On Feb 10, 2:42 pm, Marco Giusti wrote: >> On Sat, Feb 10, 2007 at 05:29:23AM -0800, Johny wrote: >> >I need to find all the same words in a text . >> >What would be the best idea to do that? >> >I used string.find but it does not work properly for the words. >> >Let suppose I want to find a number 324 in the text >> >> >'45 324 45324' >> >> >there is only one occurrence of 324 word but string.find() finds 2 >> >occurrences ( in 45324 too) >> >> >>> '45 324 45324'.split().count('324') >> 1 >> >>> >> >> ciao >Marco, >Thank you for your help. >It works perfectly but I forgot to say that I also need to find the >possition of each word's occurrence.Is it possible that >>> li = '45 324 45324'.split() >>> li.index('324') 1 >>> play with count and index and take a look at the help of both ciao marco -- reply to `python -c "print 'moc.liamg at itsuig.ocram'[::-1]"` -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tinaweb at bestemselv.com Sat Feb 10 12:55:43 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sat, 10 Feb 2007 18:55:43 +0100 Subject: Hacking in python In-Reply-To: References: Message-ID: zefciu wrote: > enes naci wrote: >> i would like to know about hacking in python too whether its illegal or >> not is not the point and anyway it doesn't mean i'm gong to use it. >> > > If you mean hacking as modyfying the code of interpreter of libraries - > it is perfectly legal, as Python is Open Source. > > If you mean hacking as cracking into computer systems, then what's the > difference if it's with Python or anything else. > > If you mean hacking as gaining excellency in programming - then why > should it be? > > Greets > zefciu It's really sad. I saw this poor schmuck on "Want to be a millionaire" once. His second question was "What is a hacker?" I don't remember all of the alternatives but two of them was "A computer programmer" and "Someone illegally using a computer". He answered 'computer programmer'... guess what was the 'correct one'. I guess he was lucky though... it could have been the one million question. From Mark.Geyzer at gmail.com Sun Feb 11 07:13:16 2007 From: Mark.Geyzer at gmail.com (volcano) Date: 11 Feb 2007 04:13:16 -0800 Subject: How to access an absolute address through Python? Message-ID: <1171195996.734380.126580@l53g2000cwa.googlegroups.com> Can it be done, and if yes - how? From bj_666 at gmx.net Tue Feb 27 01:07:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 27 Feb 2007 07:07:23 +0100 Subject: How to use cmp() function to compare 2 files? References: <1172549378.641948.17710@p10g2000cwp.googlegroups.com> <1172550136.069527.103600@t69g2000cwt.googlegroups.com> <1172551987.182502.94000@p10g2000cwp.googlegroups.com> <1172553141.665287.65280@8g2000cwh.googlegroups.com> Message-ID: In <1172553141.665287.65280 at 8g2000cwh.googlegroups.com>, yinglcs at gmail.com wrote: > File "./scripts/regressionTest.py", line 30, in getSnapShot > if (difflib.context_diff(f1.readlines(), f2.readlines()).len() == > 0): > # no difference > else: > # files are different > AttributeError: 'generator' object has no attribute 'len' > > Can you please help? The function returns a generator/iterator over the differences which has no `len()` method. If you just want to know if two files are equal or not use `filecmp.cmp()`. Read the docs about the `shallow` argument of that function. Ciao, Marc 'BlackJack' Rintsch From michele.simionato at gmail.com Sun Feb 18 03:17:41 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Feb 2007 00:17:41 -0800 Subject: cmd all commands method? In-Reply-To: <53per7F1t12jjU1@mid.individual.net> References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> <53per7F1t12jjU1@mid.individual.net> Message-ID: <1171786661.599128.234300@k78g2000cwa.googlegroups.com> On Feb 17, 11:44 pm, Bjoern Schliessmann wrote: > placid wrote: > > if i want to treat every cmdloop prompt entry as a potential > > command then i need to overwrite the default() method ? > > Excuse me, what's a cmdloop prompt? What's the "default() method"? > > > What i want to achieve is to be able to support global variable > > creation for example; > > > res = sum 1 2 > > > this would create a variable res with the result of the method > > do_sum() ? > > > then would i be able to run; > > > sum a 5 > > > this would return 8 or an error saying that res is not defined > > Are you sure you're talking about Python here? Yes, he is talking about the cmd module: http://docs.python.org/dev/lib/Cmd-objects.html. However that module was never intended as a real interpreter, so defining variables as the OP wants would require some work. Michele Simionato From cyberco at gmail.com Thu Feb 8 17:50:21 2007 From: cyberco at gmail.com (cyberco) Date: 8 Feb 2007 14:50:21 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1170975021.463670.130620@h3g2000cwc.googlegroups.com> Go for BOA if you're going to use wxPython, whose python text editor is excellent as well. From http Fri Feb 9 11:14:10 2007 From: http (Paul Rubin) Date: 09 Feb 2007 08:14:10 -0800 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> <1170872694.018720.301410@m58g2000cwm.googlegroups.com> <52vdp2F1qp2n6U2@mid.individual.net> <45CB99DB.1080102@mvista.com> Message-ID: <7xodo3e2b1.fsf@ruckus.brouhaha.com> "S.Mohideen" writes: > Suppose I split my Net application code using parallel python into > several processes based upon the number of CPU available. That means a > single socket descriptor is distributed across all processes. Is > parallelity can be acheived using the processes send/recv on the > single socket multiplexed across all the processes.. I haven't tried > it yet - would like to have any past experience related to this. In Linux, you can open the socket before forking and then use it in the child processes; there is also a way to pass open sockets from one process to another, but the Python lib currently does not support that feature. It's worth adding and there's an open RFE for it, but it hasn't been important enough that anyone's bothered coding it so far. From gandalf at designaproduct.biz Tue Feb 13 09:43:46 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 13 Feb 2007 15:43:46 +0100 Subject: _ssl.pyd is buggy? Message-ID: <45D1CEA2.7070009@designaproduct.biz> Hello, I wrote a small program that uses xmlrpc over https. It should work as a win32 application and as a win32 service too. There is a file called Processor.py that contains the main thread of the program. It is called from two files: win32_Application.py and win32_Service.py. The application works perfectly. The service does not. I can start it from the services mmc console, but it does not created logfiles, and does nothing. It cannot be stopped and I have to kill pythonservice.exe. The event log shows this: Information: The AmazonOfferDownloaderService service has started. Application error: Faulty application: python.exe, version: 0.0.0.0, faulty modul: _ssl.pyd, version: 0.0.0.0, memory address: 0x00019b87. Is it possible that my _ssl.pyd is faulty? Please help me. Python version: 2.4.3 (#69, Mar 29 2006) Windows version: Windows XP Professional, service pack 2, Hungarian (I translated the above messages from the event log....) Thanks, Laszlo >>> Here is the code for the application: import thread,threading,time from Processor import * from servicelog import * from win32_Config import * stopped = threading.Event() stopped.clear() processor = Processor(stopped) thread.start_new_thread(processor.Process,()) logger = getLogger('win32_Application') logger.info("Staring as application. Please press CTRL+C to stop service.") while 1: try: time.sleep(1) except: break logger.info("Stopping application " + SERVICE_NAME) stopped.set() while not processor.stopped.isSet(): logger.debug("Waiting for the processor to finish...") time.sleep(1) logger.info("Application stopped.") >>> Here is the code for the service: from win32_Config import * from Processor import * from servicelog import * import win32serviceutil, win32service import pywintypes, win32con, winerror from win32event import * from win32file import * from win32pipe import * from win32api import * from ntsecuritycon import * import traceback import thread,threading class Service(win32serviceutil.ServiceFramework): _svc_name_ = SERVICE_NAME _svc_display_name_ = SERVICE_DISPLAY def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.stopped = threading.Event() self.stopped.clear() self.logger = getLogger(SERVICE_NAME) def SvcStop(self): self.logger.info("Got SvcStop, trying to stop service...") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.stopped.set() def SvcDoRun(self): """Write an event log record - in debug mode we will also see this message printed.""" try: import servicemanager servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '') ) self.logger.info("Started.") self.logger.debug("Creating processor instance") processor = Processor(self.stopped) self.logger.debug("Starting processor thread") thread.start_new_thread(processor.Process,()) self.logger.debug("Waiting for the processor thread to finish") self.stopped.wait() self.logger.debug("Stopping") time.sleep(1) while not processor.stopped.isSet(): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) time.sleep(5) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, "") ) self.logger.info("Stopped") except: self.logger.error('',exc_info = sys.exc_info()) if __name__=='__main__': win32serviceutil.HandleCommandLine(Service) From bearophileHUGS at lycos.com Fri Feb 16 18:24:05 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Feb 2007 15:24:05 -0800 Subject: Help Required for Choosing Programming Language In-Reply-To: <45d624f7$0$10573$426a74cc@news.free.fr> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <45d624f7$0$10573$426a74cc@news.free.fr> Message-ID: <1171668245.231959.213730@j27g2000cwj.googlegroups.com> Bruno Desthuilliers: > Iftikhar: > > i have read about Python, Ruby and Visual C++. but i want to go > > through with GUI based programming language > > "GUI based programming languages" ? What's that ? Maybe a language like Gui4cli :-) http://users.hol.gr/~dck/g4c/ Bye, bearophile From ironfroggy at gmail.com Sat Feb 10 12:36:35 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sat, 10 Feb 2007 12:36:35 -0500 Subject: What does "del" actually do? In-Reply-To: <8bnzh.74754$qO4.52439@newssvr13.news.prodigy.net> References: <8bnzh.74754$qO4.52439@newssvr13.news.prodigy.net> Message-ID: <76fd5acf0702100936l2e6db946k8891d7ee0ab83c65@mail.gmail.com> del simply removes the name in the current scope. if that happens to be the last non-cyclic reference to the object it was bound to, then it will remove the objec to, but thats a seperate matter. if you remove the class and there are instances out there, they can only exist if there are some other references to them, so no, they arent deleted. del wont just delete a bunch of objects and leave broken names. i has nothing to do with deleting objects, only names. On 2/10/07, John Nagle wrote: > The Python "reference manual" says, for "del", "Rather that spelling it out > in full details, here are some hints." That's not too helpful. > > In particular, when "del" is applied to a class object, what happens? > Are all the instance attributes deleted from the object? Is behavior > the same for both old and new classes? > > I'm trying to break cycles to fix some memory usage problems. > > John Nagle > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From irnyad at gmail.com Sun Feb 18 06:56:44 2007 From: irnyad at gmail.com (Jason Ward) Date: Sun, 18 Feb 2007 13:56:44 +0200 Subject: Dlls Message-ID: <1ea031080702180356p2c1a8167jd5470832b5c6315f@mail.gmail.com> Hi. I am interested to know why python can't access DLL files directly. It seems to me that because python can't access DLL's directly we have to waste our time and write wrappers around libraries that have already been written. So if the python developers were to implement say this. import MYDLL.dll Then we would be able to do everything with that library that we can do in other languages. For eg. I want to use PyOpenGL. But the problem is the library hasn't got all the opengl functions implemented. So I can either develop quickly with an incomplete library or develop slowly in assembler. I mean really, in asm we just call the dll function directly. Why must python be different? -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at cosc.canterbury.ac.nz Tue Feb 27 01:45:44 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 27 Feb 2007 19:45:44 +1300 Subject: how to call os.path.join() on a list ... In-Reply-To: <1172549038.422389.296920@q2g2000cwa.googlegroups.com> References: <1172549038.422389.296920@q2g2000cwa.googlegroups.com> Message-ID: <54i2h2F20k001U1@mid.individual.net> funkyj wrote: > What is the python idiom for callling a function like os.path.join() > that takes a variable number of arguments when you currently have the > arguements in a list variable? os.path.join(*list_of_args) This is preferable to joining it yourself with os.path.sep, because it will do the right thing for the platform, which might not be so simple in all cases. -- Greg From faulkner891 at gmail.com Sat Feb 10 16:30:13 2007 From: faulkner891 at gmail.com (faulkner) Date: 10 Feb 2007 13:30:13 -0800 Subject: Something like the getattr() trick. In-Reply-To: References: Message-ID: <1171143013.403008.186920@a75g2000cwd.googlegroups.com> On Feb 10, 3:34 pm, Ayaz Ahmed Khan wrote: > I'm working with the following class heirarchy (I've snipped out the code > from the classes): > > class Vuln: > def __init__(self, url): > pass > > def _parse(self): > pass > > def get_link(self): > pass > > class VulnInfo(Vuln): > pass > > class VulnDiscuss(Vuln): > pass > > def main(url): > vuln_class = ['Info', 'Discuss'] > vuln = Vuln(url) > vuln._parse() > for link in vuln.get_link(): > i = VulnInfo(link) > i._parse() > d = VulnDiscuss(link) > d._parse() > > Is there a way to get references to VulnInfo and VulnDiscuss objects using > something like the getattr trick? For example, something like: > > for _class in vuln_class: > class_obj = getattr('Vuln%s' % (_class,) ..) > a = class_obj(link) > a._parse() > > getattr() takes an object as its first argument. I can't seem to figure > out how to make it work here. > > -- > Ayaz Ahmed Khan > > A witty saying proves nothing, but saying something pointless gets > people's attention. eval('Vuln' + _class) or, Vuln.Discuss = VulnDiscuss getattr(Vuln, _class) From tjreedy at udel.edu Wed Feb 14 03:02:36 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Feb 2007 03:02:36 -0500 Subject: python not returning true References: <1171430119.604777.226820@v45g2000cwv.googlegroups.com><1171431443.737052.183960@j27g2000cwj.googlegroups.com><1171435541.291367.299290@j27g2000cwj.googlegroups.com> <1171437351.206085.236450@q2g2000cwa.googlegroups.com> Message-ID: "John Machin" wrote in message news:1171437351.206085.236450 at q2g2000cwa.googlegroups.com... | On Feb 14, 5:45 pm, "agent-s" wrote: | > btw Steven you are so witty I hope to one day pwn noobs on newsgroups | > too. Sorry, but you are 'pwning' yourself here ;-) | Wit has nothing to do with it. The fact that you are a Python noob is | also irrelevant. Your problem statement was unintelligible, as is your | response. What does "pwn" mean? I believe that it is a misspelling of 'own' used by pvp (person versus person, as opposed to person versus monster) gamers to demonstrate their in-ness. But perhaps agent-s can enlightenment us further. Terry Jan Reedy (occasional, non-elite gamer) From deets at nospam.web.de Thu Feb 22 08:00:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 14:00:43 +0100 Subject: plugin development best practices References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> Message-ID: <545ifrF1v049oU1@mid.uni-berlin.de> Flavio wrote: > Hi, > > Nowadays the addition of functionality to programs by means of > plugins is very frequent. > > I want to know the opinions of experienced Python developers about the > best practices when it comes to developing a plugin system for a > Python package. > > Should plugins be modules in a separate package? > Should there be a registry of available plugins? how would such a > registry be implemented? etc. There have been a gazillion discussions about this on this newsgroup/mailing list. Searching the archives will get you to them. The dynamic nature of python makes a whole range of options available. Depending on what you want to do (how are the plugins made available and so on), one or the other might be preferable. One relatively current development is the usage of setuptools "entry-points" feature, which is precisely made for discovering installed plugins: http://peak.telecommunity.com/DevCenter/setuptools#dynamic-discovery-of-services-and-plugins Diez From thinker at branda.to Tue Feb 27 05:28:50 2007 From: thinker at branda.to (Thinker) Date: Tue, 27 Feb 2007 18:28:50 +0800 Subject: spawnl and waitpid In-Reply-To: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> References: <1172571568.571217.51980@p10g2000cwp.googlegroups.com> Message-ID: <45E407E2.50704@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 naima.mans at gmail.com wrote: > hello, > > I run a python cgi script under Apache... > > and while the script is running i want to display a "please wait" > message until the script finish. > > I have tried to do this but the "please wait" message appears at > the script end (which is useless at this time! ) > You should flush sys.stdout after you print messages, or the message will keep in buffer untill buffer is full or process terminated. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF5Afi1LDUVnWfY8gRAgaoAJ9fccAjo00QupE7SRFqgbmOUGZMugCgjvdH cFoxm+jiZiIpKOfd+fHCt/M= =9COv -----END PGP SIGNATURE----- From gagsl-py at yahoo.com.ar Fri Feb 23 19:00:22 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Feb 2007 21:00:22 -0300 Subject: Question about idiomatic use of _ and private stuff. References: Message-ID: En Fri, 23 Feb 2007 13:12:20 -0300, Steven W. Orr escribi?: > I understand that two leading underscores in a class attribute make the > attribute private. But I often see things that are coded up with one > underscore. Unless I'm missing something, there's a idiom going on here. > > Why do people sometimes use one leading underscore? Just a single leading underscore means "not for public usage". Double leading underscore (without trailing underscores), means that Python will "mangle" the name in an attempt to make the name unique along the class hierarchy (so two classes in the same hierarchy may use the same attribute name without conflicting). Double leading and trailing underscores are used by the Python interpreter itself. __names have some pitfalls so better avoid them except on the specific use case for which they were designed. http://docs.python.org/ref/atom-identifiers.html -- Gabriel Genellina From skip at pobox.com Sat Feb 10 08:31:24 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 10 Feb 2007 07:31:24 -0600 Subject: pygame and python 2.5: switch to linux? In-Reply-To: References: <1171042743.035355.135700@p10g2000cwp.googlegroups.com> Message-ID: <17869.51500.779901.538800@montanaro.dyndns.org> Siggi> ... I conclude now that I will be better off to drop Windows and Siggi> install Linux on my next PC, to be able to reap the full benefits Siggi> of Python. Darn tootin'... (*) Skip (*) http://en.wikipedia.org/wiki/You're_Darn_Tootin' From steve at REMOVE.THIS.cybersource.com.au Thu Feb 22 16:04:54 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Feb 2007 08:04:54 +1100 Subject: Convert to binary and convert back to strings References: <1172101853.183586.317170@m58g2000cwm.googlegroups.com> <1172105179.708565.201600@v33g2000cwv.googlegroups.com> Message-ID: On Thu, 22 Feb 2007 11:55:22 +0000, Jussi Salmela wrote: >> For extra security, you can encode the string with rot13 twice. >> >> >> > > Like this? ;) > > >>> s = "Python" ; u = unicode(s, "ascii") ; u > u'Python' > >>> u.encode('rot13') > 'Clguba' > >>> u.encode('rot13').encode('rot13') > 'Python' Exactly! People will think that you're using some terribly advanced encryption algorithm that looks like plain text, and think "anything that clever is way too clever for me" and just give up. -- Steven. From bjourne at gmail.com Fri Feb 16 10:49:05 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 16 Feb 2007 16:49:05 +0100 Subject: Pep 3105: the end of print? In-Reply-To: <20070216152707.25807.1058387555.divmod.quotient.23949@ohm> References: <20070216152707.25807.1058387555.divmod.quotient.23949@ohm> Message-ID: <740c3aec0702160749m7586f102u218374c31d7792df@mail.gmail.com> On 2/16/07, Jean-Paul Calderone wrote: > I was just pointing out that some people might be confused. I didn't make > any judgement about that fact. You seem to be suggesting that because there > are other confusing things, it's okay for Python to be confusing too. I'm > not making any judgements about that, either. Does not change always cause confusion? The confusion in Python land is pretty minor in comparison to the one caused Java 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1, 2, 4, 5, 6 SE/ME/EE. I think that people are just complaining to much. The python-devvers are managing the transition extraordinarily well. > >Even in the Python world, nobody expects to run the same code base under > >C Python and Jython and IronPython and PyPy. > > > > I wonder if the fact that Jython and IronPython can't run most Python programs > is one of the reasons they are generally only used in special circumstances? Or maybe it is because Jython requires Java and IronPython a CLR? -- mvh Bj?rn From simon at brunningonline.net Thu Feb 1 07:00:12 2007 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 1 Feb 2007 12:00:12 +0000 Subject: Python module for the IPod shuffle ... In-Reply-To: <4ccf86300701310900g2b642847s5d0dab31857f42a6@mail.gmail.com> References: <4ccf86300701310900g2b642847s5d0dab31857f42a6@mail.gmail.com> Message-ID: <8c7f10c60702010400v22ff980ey9ec05c92b5829214@mail.gmail.com> On 1/31/07, Analog Kid wrote: > Hi all: > Im looking for a python module thatll let me do simple reads/writes from and > to an iPod shuffle similar to iTunes ... I read about the gPod module ... > but Im not sure whether it will work in Windows ... This any good? -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From danielkleinad at gmail.com Wed Feb 28 14:12:17 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Wed, 28 Feb 2007 19:12:17 GMT Subject: Question about raise and exceptions. References: Message-ID: On Wed, 28 Feb 2007 13:48:54 -0500 (EST), "Steven W. Orr" wrote: >When I run it I get this: > >884 > ./t_fsm.py >Traceback (most recent call last): > File "./t_fsm.py", line 3, in ? > from fsm import * > File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76 > raise TransitionError, self.curr_state, newstate, "Going to error >state %d from state %d" % (self.curr_state, newstate) > ^ >SyntaxError: invalid syntax The arguments for TransitionError must be a tuple, eg: msg = "Going to error state %d from state %d" % (self.curr_state, newstate) raise TransitionError(self, curr_state, newstate, msg) Dan From jeff.templon at gmail.com Tue Feb 20 16:04:44 2007 From: jeff.templon at gmail.com (Jeff Templon) Date: Tue, 20 Feb 2007 22:04:44 +0100 Subject: Python 3.0 unfit for serious work? In-Reply-To: <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> Message-ID: <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> yo, Bjorn, I am not sure I see why my post is bull crap. I think all you are doing is agreeing with me. My post was entitled "Python 3.0 unfit for serious work", you just indicated that the Linux distros will agree with me, in order to be taken seriously, the distros will have to include 2.x python for a very long time. If 3.0 and 2.x have any serious degree of incompatibility, python will be a favorite subject for religious rants and heated arguments for many people. And if we don't manage to restrain our developers from using features that force us prematurely to move to 3.0 ... and don't underestimate what this means, because this means other things will have to move as well, which may have dependencies on yet other things like C++ library versions ... then I would have to, for reasons of maintainability, argue against continuing to allow python code development in the project. I love python, but not enough to make 20+ people's lives difficult. There are already people making this sort of argument in our project. JT On 2/20/07, BJ?rn Lindqvist wrote: > What a load of bull crap. Python is one of the simplest packages to > have multiple version of installed. When Python 3.0 is released, all > Linux distros will acquire a symlink at /usr/bin/python2 pointing to > the latest Python 2.x version installed. Or something equivalent. > Rest assured that Linux distributors will not drop Python 2.x support > in the nearest decade. They are not stupid. From emami at knmi.nl Mon Feb 26 10:27:02 2007 From: emami at knmi.nl (Nader Emami) Date: Mon, 26 Feb 2007 16:27:02 +0100 Subject: ez_setup.py Message-ID: <79559$45e2fc46$9117fe9b$10365@news1.tudelft.nl> L.S., I have installed locally Python-2.4.4 without any problem. Then I would install the "ez_setup.py" to be able using of "easy_install" tool, but I get the next error: %python ez_setup.py Traceback (most recent call last): File "ez_setup.py", line 223, in ? main(sys.argv[1:]) File "ez_setup.py", line 155, in main egg = download_setuptools(version, delay=0) File "ez_setup.py", line 111, in download_setuptools import urllib2, shutil File "/usr/people/emami/lib/python2.4/urllib2.py", line 108, in ? import cookielib File "/usr/people/emami/lib/python2.4/cookielib.py", line 35, in ? from calendar import timegm File "/usr/people/emami/calendar.py", line 23, in ? import pygtk ImportError: No module named pygtk I don't understand what is the problem! Could somebody tell me what I have to do to solve it? Regards, Nader From chadrik at gmail.com Fri Feb 16 16:07:40 2007 From: chadrik at gmail.com (chadrik at gmail.com) Date: 16 Feb 2007 13:07:40 -0800 Subject: IOError: [Errno 4] Interrupted system call In-Reply-To: References: <1171594649.279210.139470@l53g2000cwa.googlegroups.com> Message-ID: <1171660060.302688.101070@k78g2000cwa.googlegroups.com> i don't have any signal handlers in my code, but i have no idea what is going on in the internals of the pyQt framework that i'm using for the GUI. as far as simply ignoring the exception, that does not seem to work. for instance, here's some code i've tried: p = subprocess.Popen('mycommand', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) output = '' tries = 0 while tries < 12: try: tries = tries+1 print "retrieving results" output = p.stdout.readlines() except IOError: print "IOError! try %s" % tries print "output:", output #time.sleep(1) else: print "Great Success" print "output:", output break --printout: successful run-- retrieving results Great Success output: [] --printout: IOError run-- retrieving results IOError! try 1 output: retrieving results Great Success output: [] if the first try raises an error output does not get set and then the second try succeeds but returns an empty list when it should return results. moving the Popen inside the loop isn't an option either, because, in addition to returning results, the command performs an action which should only run once. sorry if i'm missing something obvious here, i'm a python newb. -chad From rpmuller at gmail.com Tue Feb 27 15:08:46 2007 From: rpmuller at gmail.com (RickMuller) Date: 27 Feb 2007 12:08:46 -0800 Subject: book for a starter In-Reply-To: <1172603326.853903.315620@z35g2000cwz.googlegroups.com> References: <54j9qfF20cqgnU1@mid.individual.net> <1172603326.853903.315620@z35g2000cwz.googlegroups.com> Message-ID: <1172606926.215944.227660@v33g2000cwv.googlegroups.com> On Feb 27, 12:08 pm, "Sriram" wrote: > Hi, > > If you have experience programming, just read the online tutorial athttp://docs.python.org/tut/tut.html > Seconded. It really is a wonderful introduction to Python. Once you've digested that, the Python Library Reference in the docs is your best friend. The nice thing about getting familiar with the official python documentation is that it's always available to you. From karoly.kiripolszky at gmail.com Sat Feb 3 08:47:39 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 3 Feb 2007 05:47:39 -0800 Subject: strange test for None Message-ID: <1170510459.804204.311760@v33g2000cwv.googlegroups.com> in my server i use the following piece of code: ims = self.headers["if-modified-since"] if ims != None: t = int(ims) and i'm always getting the following error: t = int(ims) ValueError: invalid literal for int(): None i wanna know what the hell is going on... first i tried to test using is not None, but it makes no difference. sorry i forgot, it's interpreter 2.4.4. From silovana.vjeverica at com.gmail Fri Feb 23 09:12:47 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Fri, 23 Feb 2007 15:12:47 +0100 Subject: Module trouble [newbie] References: <54830uF1ukj2kU1@mid.uni-berlin.de> <54879mF1ukp6jU2@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > I use it sometimes myself, to avoid otherwise circular imports. Circular imports are the reason why I have module issues. Last question: if I put modules in some package and then try to import one I get "AttributeError: 'module' object has no attribute 'a' Code is: a.py A = 756 import someFolder.b as b print "A printing" print "B is %s" % b.B b.py B = 2000 import someFolder.a as a print "B printing" print "A is %s" % a.A How can I do circular imports if I use packages? Darn. I don't remeber this module gothcas when reading Learning Python. -- http://www.nacional.hr/articles/view/23894/23 From luismgz at gmail.com Wed Feb 28 13:36:51 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Feb 2007 10:36:51 -0800 Subject: PyCon blogs? In-Reply-To: References: Message-ID: <1172687811.719428.203920@p10g2000cwp.googlegroups.com> On Feb 27, 9:36 pm, s... at pobox.com wrote: > Was anybody blogging about PyCon (talks and/or sprints)? Got any pointers? > > Thanks, > > Skip http://blogsearch.google.com/blogsearch?hl=en&tab=wb&q=pycon&btnG=Search+Blogs From bdesth.quelquechose at free.quelquepart.fr Mon Feb 5 15:25:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Feb 2007 21:25:10 +0100 Subject: Calling J from Python In-Reply-To: References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: <45c78b8f$0$29725$426a74cc@news.free.fr> Alexander Schmolck a ?crit : > Larry Bates writes: > > >>And why is that superior to this: >> >>def avg(l): >> return float(sum(l))/len(l) >> >> >>>>>avg([1,2,3,4]) >> >>2.5 > > > Apart from being less to type and it is superior in that it's generalizes much > better, e.g: > > avg&.^. NB. geomtric mean > avg&.% NB. harmonic mean > avg M NB. column mean of matrix M > avg"1 M NB. row mean of matrix M > 'as Would my beloved wife's life depend on it, I just couldn't say what all this garbage is supposed to mean. If that's supposed to be "superior", I'm quite happy with my inferior favorite languages... From laurent.pointal at wanadoo.fr Tue Feb 6 12:41:04 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Tue, 06 Feb 2007 18:41:04 +0100 Subject: Python cheatsheets References: <1170762374.981099.22010@v45g2000cwv.googlegroups.com> Message-ID: <45c8bcdc$0$27369$ba4acef3@news.orange.fr> Bart Ogryczak wrote: > On Jan 7, 10:03 pm, gonzlobo wrote: >> Curious if anyone has a python cheatsheet* published? I'm looking for >> something that summarizes all commands/functions/attributes. Having >> these printed on a 8" x 11" double-sided laminated paper is pretty >> cool. >> >> * cheatsheet probably isn't the right word, but you get the idea. :) > > http://www.onlamp.com/python/excerpt/PythonPocketRef/ If you have a good color printer, try PQRC http://www.limsi.fr/Individu/pointal/python/pqrc/ But... it use more than a double-sided 8" x 11"... From gagsl-py at yahoo.com.ar Mon Feb 5 23:09:08 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 01:09:08 -0300 Subject: Decimating Excel files References: <1170539530.683231.302950@a34g2000cwb.googlegroups.com> <1170725490.828444.138230@v33g2000cwv.googlegroups.com> Message-ID: En Mon, 05 Feb 2007 22:31:30 -0300, John Machin escribi?: > On Feb 6, 10:46 am, "Gabriel Genellina" wrote: >> I'd try the "xlrd" package - it is capable of reading Excel files on any >> platform. > > Thanks for the plug, Gabriel. However xlrd is not the panacea for all > evils and all idiocies :-) But is rather tolerant on what it reads, and ignores gracefully what it doesn't understand - you have a satisfied user here :) BTW, sorry for the previous message being out-of-order (or irrelevant, after some other posts); somehow all my messages got "on hold" during a few days and were delivered until today. -- Gabriel Genellina From deets at nospam.web.de Mon Feb 19 03:17:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Feb 2007 09:17:38 +0100 Subject: How to test if one dict is subset of another? In-Reply-To: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> Message-ID: <53t4plF1u4sk4U1@mid.uni-berlin.de> Jay Tee schrieb: > Hi, > > I have some code that does, essentially, the following: > > - gather information on tens of thousands of items (in this case, jobs > running on a > compute cluster) > - store the information as a list (one per job) of Job items > (essentially wrapped > dictionaries mapping attribute names to values) > > and then does some computations on the data. One of the things the > code needs to do, very often, is troll through the list and find jobs > of a certain class: > > for j in jobs: > if (j.get('user') == 'jeff' and j.get('state')=='running') : > do_something() > > This operation is ultimately the limiting factor in the performance. > What I would like to try, if it is possible, is instead do something > like this: > > if j.subset_attr({'user' : 'jeff', 'state' : 'running'}) : > do_something() > > > where subset_attr would see if the dict passed in was a subset of the > underlying attribute dict of j: This would still need to run over all items in jobs. No gain. > > j1's dict : { 'user' : 'jeff', 'start' : 43, 'queue' : 'qlong', > 'state' : 'running' } > j2's dict : { 'user' : 'jeff', 'start' : 57, 'queue' : 'qlong', > 'state' : 'queued' } > > so in the second snippet, if j was j1 then subset_attr would return > true, for j2 the answer would be false (because of the 'state' value > not being the same). If you're jobs dictionary is immutable regarding the key-set (not from it's implementation, but from its usage), the thing you can do to enhance performance is to create an index. Take a predicate like def p(j): return j.get('user') == 'jeff' and build a list jeffs_jobs = [j for j in jobs if p(j)] Then you can test only over these. Alternatively, if you have quite a few of such predicate/action-pairs, try and loop once over all jobs, applynig the predicates and actions accordingly. Diez From bob at passcal.nmt.edu Thu Feb 1 14:16:13 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 1 Feb 2007 12:16:13 -0700 Subject: Tkinter Scrolling References: <1170333328.141317.275130@q2g2000cwa.googlegroups.com> Message-ID: <2007020112161316807-bob@passcalnmtedu> On 2007-02-01 05:35:30 -0700, "D" said: > I'm sure this is a simple question to the Tkinter experts - I have a > very basic Tkinter application that consists of 1 master window and > buttons within that window. My problem is that, I need to be able to > scroll (up and down) when I get to the point that the buttons go off > the screen. What's the easiest way to do this? Thanks in advance. The super-easiest way is to make the "background" a Text() widget, add its scrollbars, then add the buttons and whatever else to it. Of course you are then limited to the 'typewriter layout' of widget placement. The typical way to do it is to make a scrolling canvas and pack the buttons and other stuff into an empty Frame() and then pack the frame on to the canvas, which I haven't had to do yet. Bob From reid at umn.edu Mon Feb 19 14:36:25 2007 From: reid at umn.edu (Reid Priedhorsky) Date: Mon, 19 Feb 2007 13:36:25 -0600 Subject: Forking SocketServer daemon -- updating state Message-ID: Hi folks, I am implementing a forking SocketServer daemon that maintains significant internal state (a graph that takes ~30s to build by fetching from a SQL database, and eventually further state that may take up to an hour to build). I would like to be able to notify the daemon that it needs to update its state. Because it forks for each new request, a request handler can't update the state because then only the child would have the new state. One idea I had was to use signals. Is it safe to write a signal handler that does extensive work (several seconds)? Seems like even so, it might be tricky to do this without race conditions. Another possibility is that the signal handler simply sets a needs_update flag, which I could check for in a handle_request() loop. The disadvantage here is that the update wouldn't happen until after the next request is handled, and I would like the state to be available for that next request. A solution might be to send a signal followed by a dummy request, which seems a bit awkward. Any other ideas or suggestions? Thanks in advance, Reid p.s. This group's help on A* search was very much appreciated -- just the ticket! From maxerickson at gmail.com Wed Feb 28 09:53:30 2007 From: maxerickson at gmail.com (Max Erickson) Date: Wed, 28 Feb 2007 14:53:30 +0000 (UTC) Subject: PyCon blogs? References: <17892.52858.798903.806121@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > Was anybody blogging about PyCon (talks and/or sprints)? Got any > pointers? > > Thanks, > > Skip In no particular order: http://www.nedbatchelder.com/blog/20070226T075948.html http://www.oreillynet.com/onlamp/blog/2007/02/pycon_day_1_1.html http://wamber.net/PyCon-2007/ max From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 2 06:20:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 02 Feb 2007 12:20:38 +0100 Subject: Inconsistent list/pointer problem In-Reply-To: References: Message-ID: <45c31e25$0$31426$426a74cc@news.free.fr> Eduardo "EdCrypt" O. Padoan a ?crit : >> def myFunc(listA): >> listB = listA >> work on & modify listB >> return(listB) > > def my_func(listA): > listB = listA[:] > #work on & modify listB > return listB Won't do for the OP's needs - he wants to modify the objects contained in listB without impacting the ones in listA (or at least that's what I understand). From http Tue Feb 13 23:49:48 2007 From: http (Paul Rubin) Date: 13 Feb 2007 20:49:48 -0800 Subject: threading and multicores, pros and cons References: Message-ID: <7xodnx2vir.fsf@ruckus.brouhaha.com> Maric Michaud writes: > If some guru has made a good recipe, or want to resume the main points it > would be really appreciated. Basically Python applications are usually not too CPU-intensive; there are some ways you can get parallelism with reasonable extra effort; and for most of Python's history, multi-CPU systems have been rather exotic so the GIL didn't create too big a problem. Right now it is starting to become more of a problem than before, but it's not yet intolerable. Obviously something will have to be done about it in the long run, maybe with PyPy. From ronrsr at gmail.com Sun Feb 11 23:26:49 2007 From: ronrsr at gmail.com (ronrsr) Date: 11 Feb 2007 20:26:49 -0800 Subject: how to store and still search special characters in Python and MySql Message-ID: <1171254409.379444.183000@h3g2000cwc.googlegroups.com> I have an MySQL database called zingers. The structure is: zid - integer, key, autoincrement keyword - varchar citation - text quotation - text I am having trouble storing text, as typed in latter two fields. Special characters and punctuation all seem not to be stored and retrieved correctly. Special apostrophes and single quotes from Microsoft Word are causing a special problem, even though I have ''ed all 's perhaps the encoding of the database itself should be different? it is currenlty latin_swedish_ci Input and output is through a browser. I think my problem may be that I need to encode the string before saving it in the databse. Can anyone point me in the right direction here? here's the error message: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 95: ordinal not in range(128) args = ('ascii', "update zingers set keywords = 'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal not in range(128)') encoding = 'ascii' end = 96 object = "update zingers set keywords = 'a;Action;b;Religi... \n \n \n ' where zid = 422" reason = 'ordinal not in range(128)' start = 95 the characters I am trying to add are startquote and endquote copied and pasted from Microsoft Word. Can anyone help me on this? bests, -rsr- From gagsl-py at yahoo.com.ar Mon Feb 12 13:18:27 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 15:18:27 -0300 Subject: Exception References: <854284.81743.qm@web54505.mail.yahoo.com> Message-ID: En Mon, 12 Feb 2007 10:37:52 -0300, Navid Parvini escribi?: > Would you please tell me if there is a pysignal or method that called > when an exception is occurred? No > (I don't want to use "try" method) Why not? -- Gabriel Genellina From mdfranz at gmail.com Wed Feb 28 12:15:13 2007 From: mdfranz at gmail.com (Matthew Franz) Date: Wed, 28 Feb 2007 11:15:13 -0600 Subject: Curious UnboundLocalError Behavior Message-ID: <33acb3db0702280915s12c1df60j31961bca1fd75068@mail.gmail.com> I'm probably fundamentally misunderstanding the way the interpreter works with regard to scope, but is this the intended behavior... franz-macbook:~ mdfranz$ python unboundlocal.py ('Darwin', 'franz-macbook.local', '8.8.5', 'Darwin Kernel Version 8.8.5: Mon Dec 11 19:39:17 PST 2006; root:xnu-792.16.5.obj~1/RELEASE_I386', 'i386') 2.4.3 (#1, Feb 24 2007, 23:01:32) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] {'__builtins__': , '__file__': 'unboundlocal.py', 'SOMEGLOBAL': 1, 'sys': , '__name__': '__main__', 'foo': , 'os': , '__doc__': None} SOMEGLOBAL: Traceback (most recent call last): File "unboundlocal.py", line 15, in ? foo() File "unboundlocal.py", line 11, in foo print "SOMEGLOBAL:",SOMEGLOBAL UnboundLocalError: local variable 'SOMEGLOBAL' referenced before assignment Where unboundlocal.py is... import os,sys SOMEGLOBAL=1 def foo(): dome=False if dome: SOMEGLOBAL = 0 print globals() print "SOMEGLOBAL:",SOMEGLOBAL print os.uname() print sys.version foo() Is SOMEGLOBAL is some weird in-between state, since it is referenced within foo() but not actually assigned? If I set dome to True SOMEGLOBAL gets overriden (as I would have expected) franz-macbook:~ mdfranz$ python unboundlocal.py ('Darwin', 'franz-macbook.local', '8.8.5', 'Darwin Kernel Version 8.8.5: Mon Dec 11 19:39:17 PST 2006; root:xnu-792.16.5.obj~1/RELEASE_I386', 'i386') 2.4.3 (#1, Feb 24 2007, 23:01:32) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] {'__builtins__': , '__file__': 'unboundlocal.py', 'SOMEGLOBAL': 1, 'sys': , '__name__': '__main__', 'foo': , 'os': , '__doc__': None} SOMEGLOBAL: 0 -- Matthew Franz http://www.threatmind.net/ From mathiasDOTfranzius at webDELETEME.de Tue Feb 13 13:42:34 2007 From: mathiasDOTfranzius at webDELETEME.de (Mathias) Date: Tue, 13 Feb 2007 19:42:34 +0100 Subject: Segmentation faults using threads In-Reply-To: References: Message-ID: PS: setting sys.setcheckinterval(1) reduces the probablilty of a failure as well, but definetely at a performance cost. From funkyj at gmail.com Mon Feb 26 23:03:58 2007 From: funkyj at gmail.com (funkyj) Date: 26 Feb 2007 20:03:58 -0800 Subject: how to call os.path.join() on a list ... Message-ID: <1172549038.422389.296920@q2g2000cwa.googlegroups.com> I want to call os.path.join() on a list instead of a variable list of arguments. I.e. [scr-misc] (186:0)$ python iPython 2.4 (#2, Feb 18 2005, 16:39:27) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. m>>> >>> import os >>> import string >>> p = os.environ['PWD'] >>> p '/tmp/a/b/c/d' >>> os.path.join(string.split(p, os.sep)) ['', 'tmp', 'a', 'b', 'c', 'd'] >>> the value returned by os.path.join() is obviously not the desired result ... Sure, I can hack my own version of os.path.join() by using os.sep but that does not seem very pythonic. In lisp one would do something like (funcall #'os.path.join (string.split p os.sep)) What is the python idiom for callling a function like os.path.join() that takes a variable number of arguments when you currently have the arguements in a list variable? I'm curious about the answer to the question above but in the meantime I'll hack "my.path.join()' that takes a single list as an argument and move on with my little project. Regards, fj From bignose+hates-spam at benfinney.id.au Sat Feb 3 03:58:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Feb 2007 19:58:14 +1100 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> Message-ID: <87odobsjmh.fsf@benfinney.id.au> Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: > Since Python is being touted as good for web apps as a competitor to > PHP Python is being touted as a good language for *many* purposes, not just web applications. Python is also a "competitor" to Java, to Ruby, to Perl, to many other languages. They all have strengths and weaknesses. > it should offer the same db connectivity in its stdlib that PHP > offers in its. That doesn't follow at all. Many consider the humungous function library of PHP to be a significant downside of the system, which criterion leaves Python ahead. More is not necessarily better. > I'm paying the hosting company for access to a computer that's > connected to electricity and to the internet and which has a > straightforward OS, language package, web server, and db installed. In which case, there should be no problem with *you* installing whatever software you need to use the system for what you want. > They shouldn't have to deal with dozens of interdependent modules > downloaded from different places just to support one language. Either they are providing far more than the minimal set you describe above, or this is entirely outside their domain. Make up your mind. You can't claim both that the hosting company should have to maintain a comprehensive set of functionality, *and* that they should not have to. -- \ "Don't worry about what anybody else is going to do. The best | `\ way to predict the future is to invent it." -- Alan Kay | _o__) | Ben Finney From sjmachin at lexicon.net Sun Feb 11 17:38:40 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Feb 2007 14:38:40 -0800 Subject: Regexps and lists In-Reply-To: <1171231704.605194.169960@l53g2000cwa.googlegroups.com> References: <1171231704.605194.169960@l53g2000cwa.googlegroups.com> Message-ID: <1171233520.340096.275920@v45g2000cwv.googlegroups.com> On Feb 12, 9:08 am, "Paddy" wrote: > I don't know enough to write an R.E. engine so forgive me if I am > being naive. > I have had to atch text involving lists in the past. These are usually > comma separated words such as > "egg,beans,ham,spam,spam" > you can match that with: > r"(\w+)(,\w+)*" You *can*, but why do that? What are you trying to achieve? What is the point of distinguishing the first element from the remainder? See if any of the following do what you want: | >>> s = "egg,beans,ham,spam,spam" | >>> s.split(',') | ['egg', 'beans', 'ham', 'spam', 'spam'] | >>> import re | >>> re.split(r",", s) | ['egg', 'beans', 'ham', 'spam', 'spam'] | >>> re.split(r"(,)", s) | ['egg', ',', 'beans', ',', 'ham', ',', 'spam', ',', 'spam'] > and when you look at the groups you get the following > >>> import re > >>> re.match(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups() > ('egg', ',spam') > > Notice how you only get the last match as the second groups value. > > It would be nice if a repeat operator acting on a group turned that > group into a sequence returning every match, in order. (or an empty > sequence for no matches). > > The above exaple would become: > > >>> import re>>> re.newmatch(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups() > > ('egg', ('beans', 'ham', 'spam', ',spam')) And then what are you going to do with the answer? Something like this, maybe: | >>> actual_answer = ('egg', ('beans', 'ham', 'spam', ',spam')) | >>> [actual_answer[0]] +list(actual_answer[1]) | ['egg', 'beans', 'ham', 'spam', ',spam'] > 1, Is it possible? Maybe, but I doubt the utility ... > do any other RE engines do this? If your Google is not working, then mine isn't either. > 2, Should it be added to Python? No. HTH, John From gagsl-py at yahoo.com.ar Mon Feb 12 00:48:50 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 02:48:50 -0300 Subject: searching a list of lists as a two-dimensional array? References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 02:24:54 -0300, Samuel Karl Peterson escribi?: > James Stroud on Sun, 11 Feb 2007 16:53:16 -0800 > didst step forth and proclaim thus: > >> agent-s wrote: >> > Basically I'm programming a board game and I have to use a list of >> > lists to represent the board (a list of 8 lists with 8 elements each). >> > I have to search the adjacent cells for existing pieces and I was >> > wondering how I would go about doing this efficiently. Thanks > Wow, maybe it's just me (I'm a pretty bad programmer) but this is > where list comprehensions begin to look unreadable to me. Here's a > C-like way to do it, (warning, untested in python): Just for fun, and to add one more way. This is a generator for adjacent indexes, that can be used to search for occupied cells, for locating a suitable next move, or whatever: py> def adj(i, j): ... for ni in (i-1, i, i+1): ... if ni not in range(8): continue ... for nj in (j-1, j, j+1): ... if nj not in range(8): continue ... if ni!=i or nj!=j: ... yield ni,nj ... py> py> print list(adj(4,3)) [(3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3), (5, 4 py> print list(adj(7,3)) [(6, 2), (6, 3), (6, 4), (7, 2), (7, 4)] py> print list(adj(4,7)) [(3, 6), (3, 7), (4, 6), (5, 6), (5, 7)] py> print list(adj(0,7)) [(0, 6), (1, 6), (1, 7)] -- Gabriel Genellina From gagsl-py at yahoo.com.ar Mon Feb 19 19:12:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 21:12:26 -0300 Subject: Building Python Pagage for Newer Python Version References: <1171875440.938807.165340@l53g2000cwa.googlegroups.com> <53toriF1tr6efU1@mid.uni-berlin.de> Message-ID: En Mon, 19 Feb 2007 11:00:18 -0300, Diez B. Roggisch escribi?: >> I have just downloaded the source for PyXML-0.8.4, which I would like >> to build for Python 2.5. How exactly do I go about doing this? > > python2.5 setup.py install usually does the trick. Beware of this message, from the project front page: "PyXML is no longer maintained" -- Gabriel Genellina From roy at panix.com Sun Feb 18 18:54:33 2007 From: roy at panix.com (Roy Smith) Date: Sun, 18 Feb 2007 18:54:33 -0500 Subject: Is there any way to automatically create a transcript of an interactive Python session? References: <1171842673.363336.121080@l53g2000cwa.googlegroups.com> Message-ID: In article <1171842673.363336.121080 at l53g2000cwa.googlegroups.com>, "Jonathan Mark" wrote: > Some languages, such as Scheme, permit you to make a transcript of an > interactive console session. Is there a way to do that in Python? I don't know of any way *inside* of python, but it's easy enough to run your interactive python session inside of something like "script", an emacs shell buffer, etc. From jeff at kalikstein.com Tue Feb 6 17:34:01 2007 From: jeff at kalikstein.com (jeff) Date: 6 Feb 2007 14:34:01 -0800 Subject: Help reading binary data from files In-Reply-To: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> References: <1170799280.837201.131640@a75g2000cwd.googlegroups.com> Message-ID: <1170801241.730109.23110@h3g2000cwc.googlegroups.com> On Feb 6, 4:01 pm, "jeff" wrote: > I am stumped trying to read binary data from simple files. Here is a > code snippet, where I am trying to simply print little-endian encoded > data from files in a directory. > > for name in os.listdir(DOWNLOAD_DIR): > filename = s.path.join(DOWNLOAD_DIR, name) > if os.path.isfile(filename): > f = open(filename, 'rb') > while True: > ele = unpack(' print ele > > When the code runs, 0 is always the data printed, but the data files > are not all zero. > > Any quick tips? > > thanks Wow, supreme stupidity on my part. It turns out that there were a lot of zeros at the beginning of the file, and the slowness of the console just showed me the zero data during the test time of ~ 10 seconds. If I throw away the zeros, I see my real data....sorry for the time waste From arkanes at gmail.com Thu Feb 1 13:33:59 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 1 Feb 2007 12:33:59 -0600 Subject: mysqldb duplicate entry error handling In-Reply-To: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> References: <1170353851.142292.71420@v33g2000cwv.googlegroups.com> Message-ID: <4866bea60702011033q4e12de04v25a0bcb30e5b57a5@mail.gmail.com> On 1 Feb 2007 10:17:31 -0800, baur79 wrote: > Hi guys > > > i try to run this code in loop and to pass even the entry is > duplicated > > def email_insert_in_db(email): > sql="INSERT INTO emails (email) values ('%s') "%(email) > db=_mysql.connect(host = "localhost", user = db_user, passwd = > db_pass, db = db_name) > > try: > db.query(sql) > except IndentationError: > print "duplicate" > pass > > also try to (raise, continue) > but can't continue in loop > > error output is: > File "inser_in_db.py", line 85, in email_insert_in_db > db.query(sql) > IntegrityError: (1062, "Duplicate entry 'email at domain.com' for key 1") > > thanks for your help > > Baurzhan Zhakashev > Kazakhstan / Shymkent city > > -- If you want to catch IntegrityError, why are you actually catching IndentationError? From google at mrabarnett.plus.com Wed Feb 14 18:30:36 2007 From: google at mrabarnett.plus.com (MRAB) Date: 14 Feb 2007 15:30:36 -0800 Subject: threading and multicores, pros and cons In-Reply-To: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> References: <1171466685.664825.167940@j27g2000cwj.googlegroups.com> Message-ID: <1171495836.015329.231010@v45g2000cwv.googlegroups.com> On Feb 14, 3:24 pm, garri... at gmail.com wrote: > On Feb 13, 9:07 pm, Maric Michaud wrote: > > > I've heard of a bunch of arguments to defend python's choice of GIL, but I'm > > not quite sure of their technical background, nor what is really important > > and what is not. These discussions often end in a prudent "python has made a > > choice among others"... which is not really convincing. > > Well, INAG (I'm not a Guru), but we recently had training from a Guru. > When we brought up this question, his response was fairly simple. > Paraphrased for inaccuracy: > > "Some time back, a group did remove the GIL from the python core, and > implemented locks on the core code to make it threadsafe. Well, the > problem was that while it worked, the necessary locks it made single > threaded code take significantly longer to execute." > > He then proceeded to show us how to achieve the same effect > (multithreading python for use on multi-core computers) using popen2 > and stdio pipes. > Hmm. I wonder whether it would be possible to have a pair of python cores, one for single-threaded code (no locks necessary) and the other for multi-threaded code. When the Python program went from single- threaded to multi-threaded or multi-threaded to single-threaded there would be a switch from one core to the other. From mizipzor at gmail.com Sun Feb 4 11:45:04 2007 From: mizipzor at gmail.com (Mizipzor) Date: Sun, 4 Feb 2007 17:45:04 +0100 Subject: Parameter lists Message-ID: Consider the following snippet of code: ========================== class Stats: def __init__(self, speed, maxHp, armor, strength, attackSpeed, imagePath): self.speed = speed self.maxHp = maxHp self.armor = armor self.strength = strength self.attackSpeed = attackSpeed self.originalImage = loadTexture(imagePath) ========================== I little container for holding the stats for some rpg character or something. Now, I dont like the looks of that code, there are many function parameters to be sent in and if I were to add an attribute, i would need to add it in three places. Add it to the function parameters, add it to the class and assign it. Is there a smoother way to do this? There usually is in python, hehe. I recall when reading python tutorials that you could do something like this: foo(*list_of_parameters): To send many parameters as a list or a tuple. Then I could assign them like this: class Stats: def __init__(self, *li): self.speed = li[0] self.maxHp = li[1] (...) Or maybe there is an even niftier way that lets me iterate through them? Hmm... but that may lead to that I need to store them in a way that makes it cumbersome to access them later. Any comments and/or suggestions are welcome! :) From hq4ever at gmail.com Mon Feb 5 17:06:57 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Tue, 6 Feb 2007 00:06:57 +0200 Subject: lambda functions ? Message-ID: Hello, I'm new on this list and in python. It seems python has some interesting concept of "ad hoc" function which I'm trying to understand without much success. Take the following code for example: """ >>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43 """ I really don't understand whats going on here. On the first instantiating of the object "f" where does "x" gets it's value? Or is it evaluated as 0? ie "x: 0 + 42" And what is the "f" object? An integer? a pointer? an Object? I'm coming from the C world... Could some please try (if even possible) to implement the above code without using "lambda" I believe it would help me grasp this a bit faster then. Thank you, Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From stj911 at rock.com Sat Feb 3 02:39:28 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 2 Feb 2007 23:39:28 -0800 Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. In-Reply-To: References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170482833.643671.254640@s48g2000cws.googlegroups.com> Message-ID: <1170488368.634755.138920@m58g2000cwm.googlegroups.com> On Feb 2, 10:32 pm, "John Barrett" wrote: > wrote in message > >> > [snip] > >> > Run your "experiment" again but add some pure oxygen such as was > >> > escaping from the on-board breathing oxygen tanks on the > >> > airplanes that were crashed into the WTC. > > > No need to do it. We have the pictures of live humans waving from the > > gaping holes in the towers where the planes crashed. We have the > > testimonies of the fire fighters that the fires were not that hot and > > minor. The fuel of the plane which is mainly in the wings were severed > > outside the netting and much of them burnt outside in the fireball > > that is visible in all the videos. Futhermore, the black soot that was > > visible to the naked eye is indicative of bloody cold flame. Also, the > > probability of the oxygen tanks oriented in such a way to inject > > oxygen onto the steel as in a oxygen cutting torch is extremely low. > > These cylinders have a 1000-3000psi of pressure which makes them into > > a rocket or an explosive under uncontrolled gas release. And they > > would not contaminate the molten metal with any sulfur. Either the > > atmosphere inside was oxidising or reducing. If it was oxidising, how > > did the sulfur in huge quantities contaminate the molten metal pools? > > The official lies to explain sulfur is from the plaster wall. But that > > requires a reducing atmosphere with finely divided and intimately > > mixed reactants in a calciner where they are continuously rotated and > > run for several hours. Yet the fires ran not even for an hour before > > the building collapsed. > > OK - given all that -- you are left with only one conclusion (or at least I > am) -- progressive structural failure, the loss of support where the plane > hit was sufficient to put excessive stress on the remaining structural > members, resulting in a catastrophic sequential failure I dont think you have seen any actual structural failures, esp progressive. That happens often in earthquake and they have stacked floors. There is famous picture of an earthquake on these websites and in the videos. Futhermore due to erratic stops and goes in the progressive failure, the structure falls on the side esp a big bldg like WTC1&2 should have fallen from the tipping torque to one side. That did not happen. only controlled demolition bldgs fall down straight. > -- it doesnt take > exotic chemical mixes to put excessive mechanical stress on a system... just > chop out enough supports.. it may take time for the remaining supports to > deform enough to reach the failure point.. but they will get there, as > demonstrated -- occams razor dude -- the least hypothesis is usually the > right one -- and I get enough conspiracy theory crap out of my dad -- makes > a good movie -- but doesnt pan out in real life -- too many whistle-blowers > around !! Occams razor is applicable to nature's works. human works are not amenable to it. Besides, the official fairy tale is the conspiracy theory. > The city I live in is installing those red-light cameras to catch > light-runners -- my dad likes to claim that they manipulate the yellow time > to catch people in the intersection and increase revenue from traffic > tickets -- I told him to shut up until he got out there with a stop watch > and proved it -- and I say the same to you -- PROVE it -- then make some > noise -- conjecture and conspiracy theories without proof are a waste of > everyones time. -- how do you know the sulphur was in large quantities ?? > did you do a chemical analysis ?? or can you produce one done by a reputable > metalurgy company ?? These pillars are not machinable steel. the sulfur here was excessive. we are talking about intergranular corrosion, not that teeny amount used for imparting machinability and that is not nowadays needed. It only for cheap and rough chinese type crap and i am not sure even there if someone would ruin their steel mills by adding this kind of corrosive sulfur shit. come on dude ... dont mix categories. > Ohhh and by the way -- high sulphur steels are regularly used for machined > components -- was the amount of sulphur detected incosistent with what may > have been present due to the use of high sulphur steels ?? (where is that > metalurgy report again ??) yeah a damn fool would put sulfur in the bolts and load bearing elements such as the bolts of aircrafts and space shuttle. Besides how do you explain the completely pulverized building ?????? if not for explosives. From jstroud at mbi.ucla.edu Fri Feb 2 00:06:49 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 01 Feb 2007 21:06:49 -0800 Subject: Python, readline and OS X In-Reply-To: References: Message-ID: Ron Garret wrote: > In article , > James Stroud wrote: > >>Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib? > > > It wasn't, but changing it so it did didn't fix the problem. (I didn't > try recompiling Python, just running it. I'll try rebuilding later.) You must re-compile python, starting with configure so that configure can identify the readline libraries. Otherwise it will compile with no readline, which is your current situation >>Bash (OSX default) and similar shells use this silly 2 part syntax: >> >> LD_LIBRARY_PATH=/sw/lib >> export LD_LIBRARY_PATH > > Actually you can do it in one line: export LD_LIBRARY_PATH=whatever Ok. Now I'll switch to bash. James From gagsl-py at yahoo.com.ar Sun Feb 18 17:27:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Feb 2007 19:27:17 -0300 Subject: window opens with os.system() References: <1171757251.224765.171800@s48g2000cws.googlegroups.com> <200702181609.23862.inq1ltd@verizon.net> Message-ID: En Sun, 18 Feb 2007 18:09:23 -0300, jim-on-linux escribi?: > I have a simple module that sends text files to a > printer. Then, it moves the file to the 'Fprtd' > directory. The module contains the following > code; > > > ##### > > for n in PrtList: > os.system('type '+n+ ' > prn' > os.system('move '+n+ ' Fprtd') > > ##### > > os.system opens and closes a window for each file > it sends to the printer and again for each time > it moves a file to the Fprtd directory. If there > were only a few files, this wouldn't be so bad. > But, when the files number 300 to 400 it becomes > objectionable. Just code the above in Python itself. type xxx > prn == copy xxx prn == shutil.copyfile(xxx,prn) move xxx Fprtd == shutil.move(xxx, Fprtd) -- Gabriel Genellina From jm.suresh at gmail.com Mon Feb 5 03:11:01 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 5 Feb 2007 00:11:01 -0800 Subject: Steiner Tree Message-ID: <1170663061.700803.231460@s48g2000cws.googlegroups.com> Hi, I am looking for links to any implementation of Steiner Tree ( http://en.wikipedia.org/wiki/Steiner_tree ) construction in Python. I could find GeoSteiner ( http://www.diku.dk/geosteiner/ ) which is implemented as a C program. Anybody know python wrapper for this? Anybody tried this program in a python program? - Suresh From gagsl-py at yahoo.com.ar Fri Feb 9 14:06:25 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Feb 2007 16:06:25 -0300 Subject: Can't import Stackless in Pythonwin References: <1171039856.077320.163610@s48g2000cws.googlegroups.com> Message-ID: En Fri, 09 Feb 2007 13:50:56 -0300, escribi?: > I am getting started in Python, and I have looked on both the > stackless page and python.org and cannot find the answer to what I > think is a simple problem. > > If I start the python command line or idle, i can >>>> import stackless > > If I start pythonwin I get the following error > ...No Module named Stackless > > Any help? > Maybe they are different versions, or installed on different places. In those three environments, execute: import sys print sys.version print sys.executable All should report the same version. The executables for both python and IDLE should reside on the same directory; for pythonwin, you should get the *same* directory plus "Lib\site-packages\pythonwin\Pythonwin.exe" -- Gabriel Genellina From gagsl-py at yahoo.com.ar Mon Feb 19 19:02:16 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 21:02:16 -0300 Subject: cmd all commands method? References: <1171718965.417009.305220@p10g2000cwp.googlegroups.com> <53per7F1t12jjU1@mid.individual.net> <1171786661.599128.234300@k78g2000cwa.googlegroups.com> <1171792183.564570.307940@m58g2000cwm.googlegroups.com> <1171792793.211346.163520@p10g2000cwp.googlegroups.com> <1171854525.360276.178080@l53g2000cwa.googlegroups.com> Message-ID: En Mon, 19 Feb 2007 00:08:45 -0300, placid escribi?: > If anyone can provide a suggestion to replicate the following Tcl > command in Python, i would greatly appreciate it. > > namespace eval foo { > variable bar 12345 > } > > what this does is create a namespace foo with the variable bar set to > 12345. Python namespaces are simple dictionaries. See the eval function. py> s = "3+x**2" py> freevars = {"x": 2} py> eval(s, {}, freevars) 7 -- Gabriel Genellina From jura.grozni at gmail.com Fri Feb 9 06:13:56 2007 From: jura.grozni at gmail.com (azrael) Date: 9 Feb 2007 03:13:56 -0800 Subject: unique elements from list of lists In-Reply-To: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> References: <1171017232.792294.81780@a75g2000cwd.googlegroups.com> Message-ID: <1171019636.020023.274770@s48g2000cws.googlegroups.com> try something else. im posting the code from a kiosk which has no python, sooo..... no code. only explanation if my memory works well there is a function in python that takes a multidimensional list and returns its values as a one-dimension list. def main(): list =unknownFunction([['a', 'b', 'd'], ['b', 'c'], ['a', 'c', 'd']) # =a, b, d, b, c, a, c, d temp = [] for i in list: check(i, temp, list) sort(list) def check(pos, temp, list ): for i in temp: if temp[i]== list[pos] del list[pos] check(pos, temp, list) temp.append(list[pos]) im not sure if this should work but the meaning is: the first three elements will be appended into the list directly because there was no like this in the temp while there are elements in the list take a pivot value and check if they are unique in the list. check: while there are elements in the temporary list check if the pivot exists in the temp. if false then append it to temp. if true delete the element and go into the recursion on the same index why? temp a, b, d list a, b, d, (b), c, a, c, d temp a, b, d list a, b, d, (c) a, c, d temp a, b, d, c list a, b, d, c, (a) c, d temp a, b, d, c list a, b, d, c, (c), d temp a, b, d, c list a, b, d, c, (d) temp a, b, d, c list a, b, d, c list a, b, c, d one way to do it. this works well if you need the list in the order they appear. sort it and it works well but i think that there is the possibility to do it somthing like the merge sort. maybee it would work. try it. Merge the sublists and remove the duplicates. (L1,L2,L3) -> (L12, L3) -> (L123) this should work pretty well Tekkaman je napisao/la: > I have a list of lists and I want to define an iterator (let's call > that uniter) over all unique elements, in any order. For example, > calling: > > sorted(uniter([['a', 'b', 'd'], ['b', 'c'], ['a', 'c', 'd']])) > > must return ['a', 'b', 'c', 'd']. I tried the following > implementations: > > from itertools import chain > def uniter1(listOfLists): > for item in set(chain(*listOfLists)): yield item > > def uniter2(listOfLists): > for item in reduce( > lambda x,y: x|y, > [set(list_) for list_ in listOfLists] > ): yield item > > speed test with timeit says the first one is slightly faster. What > bothers me is that it builds a set from an iterator and then another > iterator from the set. Is there a way to implement this using only > iterators? I also tried a "full python" implementation (by that I mean > one that does not use the built-in set and keeps track of previously > yielded items in a list) but the one I pulled out is about 180 times > slower. Here it is: > > def uniter3(listOfLists): > done = [] > for list_ in listOfLists: > for item in list_: > if not item in done: > done.append(item) > yield item > > Thanks in advance for any contribution. > > -- Simone From rdmoores at gmail.com Sat Feb 10 10:41:26 2007 From: rdmoores at gmail.com (Dick Moores) Date: Sat, 10 Feb 2007 07:41:26 -0800 Subject: Unicode is confusing me In-Reply-To: References: Message-ID: I'm the OP, and answering my own question. I received excellent advice from the developer of Ulipad, Limodou. On 2/10/07, Dick Moores wrote: > ============================ > a = [u'\u91cd', u'\u8981', u'\u6027'] > for x in range(3): > print a[x] > =========================== The script should be ======================= # -*- coding: utf-8 -*- a = [u'\u91cd', u'\u8981', u'\u6027'] for x in range(3): print a[x].encode('utf-8'), ======================== When output is redirected to a text file, this give a very pretty ? ? ? Also, it turns out that I didn't need that sitecustomize.py . -- my configuration: Win XP Pro SP2 Python 2.5 wxPython 2.8.1.1 Unicode Python IDE: Ulipad 3.6 From michele.simionato at gmail.com Tue Feb 27 08:39:15 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Feb 2007 05:39:15 -0800 Subject: Curses sorely lacking an event loop? In-Reply-To: References: Message-ID: <1172583555.352109.258520@m58g2000cwm.googlegroups.com> On Feb 27, 1:27 pm, James Stroud wrote: > Hello, > > Is curses really lacking an event loop? Do I have to write my own? I > infer from the docs that this is the case. For example, I want the > screen to be updated with resize but I find myself waiting for getch() > if I want user input, and so the screen must remain ugly until the user > presses a key. What am I missing? > > Also, does anyone have boilerplate for handling mouse events? getmouse() > returns an "ERR" of no particular description and also appears to > require a preceding getch() and hence does not seem to be wired at all > for clicks, although allusion to clicks is found in the descriptions for > mouseinterval() and mousemask(). > > Here is the error message for getmouse() in case anyone wants details: > "_curses.error: getmouse() returned ERR". This is much less informative > than one might hope. > > Thanks in advance for any help. > > James Did you check Urwid? http://excess.org/urwid Michele Simionato From B.Ogryczak at gmail.com Thu Feb 15 08:45:46 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 15 Feb 2007 05:45:46 -0800 Subject: How much memory used by a name In-Reply-To: References: <45d36eea$0$24957$426a74cc@news.free.fr> Message-ID: <1171547146.343258.136780@m58g2000cwm.googlegroups.com> On Feb 14, 9:41 pm, "Bernard Lebel" <3dbern... at gmail.com> wrote: > This is taking a long time, and I'm looking for ways to speed up this > process. I though that keeping the list in memory and dropping to the > file at the very end could be a possible approach. It seems, that you're trying to reinvent wheel. Why don't you just use g'old mmap()? http://docs.python.org/lib/module-mmap.html From jstroud at mbi.ucla.edu Sat Feb 10 17:14:15 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 10 Feb 2007 14:14:15 -0800 Subject: Hacking in python In-Reply-To: References: <2D9AF153-2DF6-4BD0-A09B-34059E58F5AC@mac.com> Message-ID: Calvin Spealman wrote: > http://en.wikipedia.org/wiki/Hacker_%28disambiguation%29 > > Educate yourself on what hacking actually is. We're all hackers, > because it just means we get the most out of code, enjoy pushing our > technology to the limit, and generally love programming. The term has > been abused by the media and you don't do much more than show your own > naiveness by asking such a question. You also do a great job of > insulting everyone on this list. > > On 2/10/07, enes naci wrote: > >> >> i would like to know about hacking in python too whether its illegal >> or not is not the point and anyway it doesn't mean i'm gong to use it. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> Here is my favorite hacker how-to: http://www.datastronghold.com/content/view/555/27/ James From gagsl-py at yahoo.com.ar Tue Feb 6 13:45:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Feb 2007 15:45:37 -0300 Subject: How to prevent from race conditions to share data between many process and thread in python References: <1170755500.910477.37150@q2g2000cwa.googlegroups.com> <52r2njF1of0tpU1@mid.uni-berlin.de> <1170762238.532367.269120@l53g2000cwa.googlegroups.com> <52r8avF1oph0dU1@mid.uni-berlin.de> Message-ID: En Tue, 06 Feb 2007 08:49:51 -0300, Diez B. Roggisch escribi?: > mars wrote: > >> On 2?6?, ??6?14?, "Diez B. Roggisch" wrote: >>> mars wrote: >>> > I use TurboGears to do some web service. TurboGears use cherrypy. >>> When >>> > web browser access this site, the cherrypy will call my python >>> > program. So my program looks like a lib. When web browser access the >>> > site, the http server will fock a process or gerenate a thread. I >>> need >>> > share some data or operate some files. How can I prevent from race >>> > conditions. Is there any way can I lock this. >>> > Thank you in advance! >>> >>> There are the Lock and RLock objects available in the module threading. >> >> Can this also lock mutil-process? > > No. You have to use the syncronization tools provided by your OS in that case; maybe using a locked file (fcntl). -- Gabriel Genellina From silovana.vjeverica at com.gmail Thu Feb 1 14:43:47 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Thu, 1 Feb 2007 20:43:47 +0100 Subject: Sorting a list References: <45c240cf$0$10895$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Hi everyone. If I have a list of tuples, and each tuple is in the form: > > (year, text) as in ('1995', 'This is a citation.') > > How can I sort the list so that they are in chronological order L.sort() -- "kad ima? 7 godina glup si ko kurac, sve je predobro: auti?i i bageri u kvartu.. to je ?ivot" Drito Konj From robson.cozendey.rj at gmail.com Mon Feb 5 16:05:37 2007 From: robson.cozendey.rj at gmail.com (robson.cozendey.rj at gmail.com) Date: 5 Feb 2007 13:05:37 -0800 Subject: Unicode formatting for Strings In-Reply-To: References: <1170698147.606770.276590@v45g2000cwv.googlegroups.com> Message-ID: <1170709537.453424.103460@p10g2000cwp.googlegroups.com> On Feb 5, 7:00 pm, "Chris Mellon" wrote: > On 2/5/07, Kent Johnson wrote: > > > > > > > robson.cozendey... at gmail.com wrote: > > > Hi, > > > > I?m trying desperately to tell the interpreter to put an '?' in my > > > string, so here is the code snippet: > > > > # -*- coding: utf-8 -*- > > > filename = u"Ataris Aqu?ticos #2.txt" > > > f = open(filename, 'w') > > > > Then I save it with Windows Notepad, in the UTF-8 format. So: > > > > 1) I put the "magic comment" at the start of the file > > > 2) I write u"" to specify my unicode string > > > 3) I save it in the UTF-8 format > > > > And even so, I get an error! > > > > File "Ataris Aqu?ticos #2.py", line 1 > > > SyntaxError: Non-ASCII character '\xff' in file Ataris Aqu?ticos #2.py > > > on line 1 > > > It looks like you are saving the file in Unicode format (not utf-8) and > > Python is choking on the Byte Order Mark that Notepad puts at the > > beginning of the document. > > Notepad does support saving to UTF-8, and I was able to do this > without the problem the OP was having. I also saved both with and > without a BOM (in UTF-8) using SciTe, and Python worked correctly in > both cases. > > > > > Try using an editor that will save utf-8 without a BOM, e.g. jedit or > > TextPad. > > > Kent > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - I saved it in UTF-8 with Notepad. I was thinking here... It can be a limitation of file.open() method? Have anyone tested that? From mccredie at gmail.com Tue Feb 6 12:54:10 2007 From: mccredie at gmail.com (Matimus) Date: 6 Feb 2007 09:54:10 -0800 Subject: Module problem In-Reply-To: References: Message-ID: <1170784450.372250.17760@s48g2000cws.googlegroups.com> On Feb 6, 9:29 am, Boris Ozegovic wrote: > Hi > > I am writing some simple script, and when I start my script from command > line (python Imenik.py), everything works perfectly. If I double clik the > same script in my desktop I get the following error: > > "No module name import win32clipboard" > > -- > "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa > silovana" Do you have more than one version of Python installed? Is win32clipboard installed for both versions? It could be that the python in your PATH variable, used when calling from the command line, is different from the association in the registry. To see the association in the registry use: "reg query HKEY_CLASSES_ROOT \Python.File\shell\open\command" on the command line. Matt From webmaster at cacradicalgrace.org Mon Feb 12 18:08:23 2007 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Mon, 12 Feb 2007 16:08:23 -0700 Subject: Vim scripting with python References: <1170507774.793397.57370@a75g2000cwd.googlegroups.com> Message-ID: Stuart D. Gathman wrote: > On Sat, 03 Feb 2007 05:02:54 -0800, Tool69 wrote: > >> Does anyone have any advice, and more genraly how to script Vim with >> Python ? > > :py import sys > :py print sys.version > :help :py > >> I know I can put some python functions inside my vimrc file like >> this : >> >> function! My_function() >> python << EOF >> import vim, string >> ...blablabla >> EOF >> endfunction >> >> but I would like to use external ".py" files. > > :py import myfile > > Use :py inside your vimrc - don't run python externally. Which versions of vim is this valid for? I tried ":py print 'Hello'", and got "E319: Sorry, the command is not available in this version" Cheers, Cliff From ke5crp1 at verizon.net Sat Feb 3 03:20:23 2007 From: ke5crp1 at verizon.net (John Barrett) Date: Sat, 03 Feb 2007 08:20:23 GMT Subject: Can a jet fuel/hydrocarbon fire collapse a steel structure? An experiment. References: <1170188993.496222.20810@p10g2000cwp.googlegroups.com> <1170482833.643671.254640@s48g2000cws.googlegroups.com> <1170488368.634755.138920@m58g2000cwm.googlegroups.com> Message-ID: wrote in message news:1170488368.634755.138920 at m58g2000cwm.googlegroups.com... > On Feb 2, 10:32 pm, "John Barrett" wrote: >> wrote in message > >> >> > [snip] >> >> > Run your "experiment" again but add some pure oxygen such as was >> >> > escaping from the on-board breathing oxygen tanks on the >> >> > airplanes that were crashed into the WTC. >> >> > No need to do it. We have the pictures of live humans waving from the >> > gaping holes in the towers where the planes crashed. We have the >> > testimonies of the fire fighters that the fires were not that hot and >> > minor. The fuel of the plane which is mainly in the wings were severed >> > outside the netting and much of them burnt outside in the fireball >> > that is visible in all the videos. Futhermore, the black soot that was >> > visible to the naked eye is indicative of bloody cold flame. Also, the >> > probability of the oxygen tanks oriented in such a way to inject >> > oxygen onto the steel as in a oxygen cutting torch is extremely low. >> > These cylinders have a 1000-3000psi of pressure which makes them into >> > a rocket or an explosive under uncontrolled gas release. And they >> > would not contaminate the molten metal with any sulfur. Either the >> > atmosphere inside was oxidising or reducing. If it was oxidising, how >> > did the sulfur in huge quantities contaminate the molten metal pools? >> > The official lies to explain sulfur is from the plaster wall. But that >> > requires a reducing atmosphere with finely divided and intimately >> > mixed reactants in a calciner where they are continuously rotated and >> > run for several hours. Yet the fires ran not even for an hour before >> > the building collapsed. >> >> OK - given all that -- you are left with only one conclusion (or at least >> I >> am) -- progressive structural failure, the loss of support where the >> plane >> hit was sufficient to put excessive stress on the remaining structural >> members, resulting in a catastrophic sequential failure > > I dont think you have seen any actual structural failures, esp > progressive. > That happens often in earthquake and they have stacked floors. There > is > famous picture of an earthquake on these websites and in the videos. > Futhermore > due to erratic stops and goes in the progressive failure, the > structure falls on the side esp a big bldg like WTC1&2 should have > fallen from the tipping torque to one side. That did not happen. only > controlled demolition bldgs fall down straight. > >> -- it doesnt take >> exotic chemical mixes to put excessive mechanical stress on a system... >> just >> chop out enough supports.. it may take time for the remaining supports to >> deform enough to reach the failure point.. but they will get there, as >> demonstrated -- occams razor dude -- the least hypothesis is usually the >> right one -- and I get enough conspiracy theory crap out of my dad -- >> makes >> a good movie -- but doesnt pan out in real life -- too many >> whistle-blowers >> around !! > > Occams razor is applicable to nature's works. human works are not > amenable to it. Besides, the official fairy tale is the conspiracy > theory. > >> The city I live in is installing those red-light cameras to catch >> light-runners -- my dad likes to claim that they manipulate the yellow >> time >> to catch people in the intersection and increase revenue from traffic >> tickets -- I told him to shut up until he got out there with a stop watch >> and proved it -- and I say the same to you -- PROVE it -- then make some >> noise -- conjecture and conspiracy theories without proof are a waste of >> everyones time. -- how do you know the sulphur was in large quantities ?? >> did you do a chemical analysis ?? or can you produce one done by a >> reputable >> metalurgy company ?? > > These pillars are not machinable steel. the sulfur here was excessive. > we are talking about intergranular corrosion, not that teeny amount > used for imparting machinability and that is not nowadays needed. It > only for cheap and rough chinese type crap and i am not sure even > there if someone would ruin their steel mills by adding this kind of > corrosive sulfur shit. come on dude ... dont mix categories. > >> Ohhh and by the way -- high sulphur steels are regularly used for >> machined >> components -- was the amount of sulphur detected incosistent with what >> may >> have been present due to the use of high sulphur steels ?? (where is that >> metalurgy report again ??) > > yeah a damn fool would put sulfur in the bolts and load bearing > elements such as the bolts of aircrafts and space shuttle. > > Besides how do you explain the completely pulverized building ?????? > if not for explosives. > > I just proposed a theory -- structural failure -- as plausible as yours and much more likely completely pulverized -- I would expect so with god knows how many tons of steel and concrete falling from a height of 100s of feet -- lotsa energy there !! Do you have direct knowlege of the building techniques used in the 1960s that you can say they didnt use high sulphur steels ?? The stainless steel used in the chrysler building (also in New York but built 30 years earlier) was made from high sulphur pig iron, with chromium and nickel added -- so there was a time when high sulphur steels were used -- do the research, prove that it wasnt the steel itself contributing to the high sulphur -- what we use things for today says nothing about how they were used 40 years ago !! And occams razor applies to anything, there are no caveats limiting it to any specific field. !! Dont bother to post again until you can deliver some FACTS !!! From rds1226 at sh163.net Sat Feb 3 15:41:44 2007 From: rds1226 at sh163.net (Ruan) Date: Sat, 3 Feb 2007 15:41:44 -0500 Subject: confused about resizing array in Python References: <8I5xh.324951$zp2.6359166@phobos.telenet-ops.be> Message-ID: Then how about Python's list? What is done exactly when list.append is executed? For list, is there another larger list initialized and the contents from the old list is copied to it together with the new appended list? "Roel Schroeven" wrote in message news:8I5xh.324951$zp2.6359166 at phobos.telenet-ops.be... > Ruan schreef: > > My confusion comes from the following piece of code: > > > > memo = {1:1, 2:1} > > def fib_memo(n): > > global memo > > if not n in memo: > > memo[n] = fib_memo(n-1) + fib_memo(n-2) > > return memo[n] > > > > I used to think that the time complexity for this code is O(n) due to its > > use of memoization. > > > > However, I was told recently that in Python, dictionary is a special kind of > > array and to append new element to it or to resize it, it is in fact > > internally inplemented by creating another array and copying the old one to > > it and append a new one. > > That's not correct. Python dictionaries are highly optimized and I > believe the time complexity is amortized constant (i.e. O(1)) for both > insertions and lookups. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven From mail at timgolden.me.uk Tue Feb 27 16:32:08 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 27 Feb 2007 21:32:08 +0000 Subject: Importing WMI in a child Thread throws an error In-Reply-To: <1172602368.563302.160060@t69g2000cwt.googlegroups.com> References: <1172602368.563302.160060@t69g2000cwt.googlegroups.com> Message-ID: <45E4A358.1050805@timgolden.me.uk> kyosohma at gmail.com wrote: > The problem I have is that since I import WMI, it takes a long time > and we have users complaining about it. So I stuck the import > statement into a separate thread and set it to a daemon so it could do > its thing in the background and the rest of the script would finish > and exit. Two things: 1) If you run WMI in a thread, you'll need to call pythoncom.CoInitialize first: import pythoncom import wmi pythoncom.CoInitialize () c = wmi.WMI () # # do things # pythoncom.CoUninitialize () 2) If you need a bit of speed running WMI, see the post I sent a few days ago to someone else: http://mail.python.org/pipermail/python-win32/2007-February/005550.html TJG From sickcodemonkey at gmail.com Wed Feb 28 15:59:34 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 28 Feb 2007 15:59:34 -0500 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> Message-ID: <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> Here you are: >>> from win32com.client import GetObject >>> wmiObj = GetObject("winmgmts:\\\\MGW01641\\root\\cimv2") >>> diskinfo = wmiObj.ExecQuery("Select * from Win32_LogicalDisk") >>> for disk in diskinfo: ... print disk.Name, disk.FreeSpace ... A: None C: 16978259968 D: None >>> On 28 Feb 2007 12:26:31 -0800, kevinliu23 at gmail.com wrote: > > HI, > > I am new to Python and wanted to know how to check for the remaining > disk space on my Windows machine using Python? I was thinking of using > the command line "dir" and trying to extract the output from there. > But I'm not sure how to extract command line strings using Python > either. > > Anyway help would be appreciated. :) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kosh at aesaeion.com Fri Feb 2 04:37:38 2007 From: kosh at aesaeion.com (William Heymann) Date: Fri, 2 Feb 2007 02:37:38 -0700 Subject: asyncore DoS vulnerability In-Reply-To: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> References: <1170357512.033356.139820@j27g2000cwj.googlegroups.com> Message-ID: <200702020237.38195.kosh@aesaeion.com> On Thursday 01 February 2007, billie wrote: > Here's the traceback: > > Traceback (most recent call last): > File "C:\Documents and Settings\root\Desktop\test.py", line 31, in ? > asyncore.loop(timeout=1) > File "C:\Python24\lib\asyncore.py", line 192, in loop > poll_fun(timeout, map) > File "C:\Python24\lib\asyncore.py", line 122, in poll > r, w, e = select.select(r, w, e, timeout) > ValueError: too many file descriptors in select() > I just tried this on 64bit kubuntu edgy and this is what I got 1019 1020 Exception in thread Thread-1021: Traceback (most recent call last): File "threading.py", line 442, in __bootstrap File "threading.py", line 422, in run File "client.py", line 5, in client File "socket.py", line 148, in __init__ error: (24, 'Too many open files') 1021 Exception in thread Thread-1022: Traceback (most recent call last): File "threading.py", line 442, in __bootstrap File "threading.py", line 422, in run File "client.py", line 5, in client File "socket.py", line 148, in __init__ error: (24, 'Too many open files') Exception in thread Thread-1020: Traceback (most recent call last): File "threading.py", line 442, in __bootstrap File "threading.py", line 422, in run File "client.py", line 12, in client error: (104, 'Connection reset by peer') 1022 1023 From gagsl-py at yahoo.com.ar Mon Feb 19 20:40:40 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Feb 2007 22:40:40 -0300 Subject: New-style classes (was Re: Checking for EOF in stream) References: <45DA39B0.7020403@gentlemail.com> <45DA4F53.90505@gentlemail.com> Message-ID: En Mon, 19 Feb 2007 22:30:59 -0300, GiBo escribi?: > Is there a reason why some classes distributed with Python 2.5 are not > new-style classes? For instance StringIO is apparently "old-style" class > i.e. not inherited from "object". Can I somehow turn an existing > old-style class to a new-style one? I tried for example: > class MyStreamIO(StreamIO, object): > pass > but got an error. Try again (and look carefully the error text) -- Gabriel Genellina From rw at smsnet.pl Sun Feb 4 05:05:34 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 04 Feb 2007 11:05:34 +0100 Subject: PYTHONPATH or any other way to set seachpath (winXP) ? References: <768f$45c4c577$d443bb3a$26126@news.speedlinq.nl> Message-ID: <87tzy2utjl.fsf@smsnet.pl> Stef Mientki writes: > Is it possible to change the searchpath for modules on the flight, > under winXP ? > Most preferred is some command to extend the searchpath. > (the environment variable PYTHONPATH needs a reboot) Do you mean something like that? >>> import some_module Traceback (most recent call last): File "", line 1, in ? ImportError: No module named some_module >>> import sys >>> sys.path.append("..") >>> import some_module http://docs.python.org/tut/node8.html#SECTION008110000000000000000 -- HTH, Rob From http Tue Feb 20 12:18:37 2007 From: http (Paul Rubin) Date: 20 Feb 2007 09:18:37 -0800 Subject: How to test if one dict is subset of another? References: <1171872462.648232.147310@a75g2000cwd.googlegroups.com> <7xy7mtz1q7.fsf@ruckus.brouhaha.com> <1171990539.710698.276050@v45g2000cwv.googlegroups.com> Message-ID: <7xwt2cpx1u.fsf@ruckus.brouhaha.com> "Jay Tee" writes: > it looks very cool, except that one of the constraints mentioned is > that the solution has to work properly on pythons 2.2 and 2.3. That thing doesn't really deeply depend on defaultdict, it's just convenient. You can add a few more lines of code in the preprocessing step to get around it. > Thanks ... I took the previous poster's suggestion (had also been > suggested earlier) and built cached versions of the job lists, indexed > on common queries, while building the master job list. You can also cache queries with the scheme I suggested, and it lets you make the cached lists for new queries quickly. From mmanns at gmx.de Fri Feb 23 15:25:48 2007 From: mmanns at gmx.de (Martin Manns) Date: Fri, 23 Feb 2007 15:25:48 -0500 Subject: Rational numbers References: <20070223103519.08f25af9@localhost> <-rSdnQOHzoJIkELYnZ2dnUVZ_oWdnZ2d@comcast.com> <20070223113911.05dcc555@localhost> <1172255683.114085.217310@m58g2000cwm.googlegroups.com> <1172260810.779025.135670@j27g2000cwj.googlegroups.com> Message-ID: <20070223152548.1ddfad27@localhost> On 23 Feb 2007 12:00:10 -0800 casevh at comcast.net wrote: > > I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex > has not updated cvs with the fix. > > gmpy 1.04a compiles cleanly with the latest releases of Python and > GMP, so I consider it stable. > > > > > Actually, gmpy is being maitained even if SourceForge isn't up to > > date. > > > > I got my gmpy 1.04a for Python 2.5 Windows binary from > > > > > > > > I haven't used the rationals all that much, but been very > > happy with them when I have. > > > > casevh > Thank you for all the replies. I think that I am going to switch to gmpy. Martin From bignose+hates-spam at benfinney.id.au Thu Feb 1 01:53:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 17:53:21 +1100 Subject: I uncover the secret of visual consciousness References: <1170311463.391041.174520@j27g2000cwj.googlegroups.com> Message-ID: <87ejpatllq.fsf@benfinney.id.au> mantaintai at yahoo.com.cn writes: > The electrochemical changes in the visual and cerebral cortex must be > firstly translated into an image. Then this image ought be changed > into the corresponding object. In comparison with image formation by a > plane mirror, we would elucidate the mechanisms and pathways of these > most unexpected transformations, with an effort to reveal the mystery > of visual consciousness . +1 QOTW. At least, I *think* this is telling me I need to see measurements of my program's performance before trying to optimised based on merely cerebral hunches. No? -- \ "I was stopped by the police for speeding; they said 'Don't you | `\ know the speed limit is 55 miles an hour?' I said 'Yeah I know, | _o__) but I wasn't going to be out that long.'" -- Steven Wright | Ben Finney From tech-hr at smartcharter.com Tue Feb 27 01:48:19 2007 From: tech-hr at smartcharter.com (Tech HR) Date: Mon, 26 Feb 2007 22:48:19 -0800 Subject: Jobs: Lisp and Python programmers wanted in the LA area References: <1172482314.598240.3440@j27g2000cwj.googlegroups.com> <7xy7mk3919.fsf@ruckus.brouhaha.com> Message-ID: In article <7xy7mk3919.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > You know about http://lispjobs.wordpress.com I presume. I did not. Thanks for the pointer. From bruno.desthuilliers at gmail.com Thu Feb 8 07:22:15 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 8 Feb 2007 04:22:15 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1170937335.190705.205610@l53g2000cwa.googlegroups.com> On 8 f?v, 13:03, "Srikanth" wrote: > Yes, > > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. > emacs +python-mode +ecb From richardjones at optushome.com.au Thu Feb 8 17:45:06 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 09 Feb 2007 09:45:06 +1100 Subject: distutils: different names in src and dist/build References: Message-ID: <45cba7f2$0$5747$afc38c87@news.optusnet.com.au> Anastasios Hatzis wrote: > is it possible to have different names between the original package name > and that which will be installed? > [snip] > Of course with-out changing the original src package name "sdk" to > "MySDK" (which likely would be the easiest way, hum). > > Any suggestion or link how I can achieve this? Two setup files? Richard From Eric_Dexter at msn.com Mon Feb 5 22:04:57 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 5 Feb 2007 19:04:57 -0800 Subject: Calling J from Python In-Reply-To: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> Message-ID: <1170731096.976076.173270@h3g2000cwc.googlegroups.com> On Feb 5, 8:48 am, "Gosi" wrote: > It is quite easy to call J from Python > > http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... There are a couple of issue that should be adressed. Am I going to jail if I write a program and then redistribute all the files required to run the program I write?? The second is how do I use the j stuff without learning all that much about j. I am just intrested in stealing graphics libraries and using what I have already written in python.. From joshbloom at gmail.com Sun Feb 4 22:58:01 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Sun, 4 Feb 2007 20:58:01 -0700 Subject: Recursive zipping of Directories in Windows In-Reply-To: <1170618143.449135.37580@v33g2000cwv.googlegroups.com> References: <1170360794.278566.159780@a75g2000cwd.googlegroups.com> <1170618143.449135.37580@v33g2000cwv.googlegroups.com> Message-ID: Hi Jandre, Your code is treating the directory as a file and trying to open it and read its bytes to zip them. You'll need to differentiate between files and directories. You'll need to check out the Zip module to see how it expects files that should be nested within folders. I believe you'll need to set the archive name for the nested files to something like \\temp\\file.ext etc. -Josh On 4 Feb 2007 11:42:23 -0800, Jandre wrote: > > On Feb 1, 9:39 pm, Larry Bates wrote: > > Jandre wrote: > > > Hi > > > > > I am a python novice and I am trying to write a python script (most of > > > the code is borrowed) to Zip a directory containing some other > > > directories and files. The script zips all the files fine but when it > > > tries to zip one of the directories it fails with the following > > > error: > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > > > > The script I am using is: > > > > > import zipfile, os > > > > > def toZip( directory, zipFile ): > > > """Sample for storing directory to a ZipFile""" > > > z = zipfile.ZipFile( > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > > ) > > > def walker( zip, directory, files, root=directory ): > > > for file in files: > > > file = os.path.join( directory, file ) > > > # yes, the +1 is hacky... > > > archiveName = file[len(os.path.commonprefix( (root, > > > file) ))+1:] > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > > > print file > > > os.path.walk( directory, walker, z ) > > > z.close() > > > return zipFile > > > > > if __name__ == "__main__": > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > > > > I have tried to set the permissions on the folder, but when I check > > > the directory permissions it is set back to "Read Only" > > > > > Any suggestions? > > > > > Thanks > > > Johan Balt > > > > Couple of quick suggestions that may help: > > > > 1) don't use 'file' as a variable name. It will mask > > the builtin file function. If it hasn't bitten you before > > it will if you keep doing that. > > > > 2) If you put the target .zip file in the directory you are > > backing what do you expect the program to do when it comes > > to the file you are creating as you walk the directory? You > > haven't done anything to 'skip' it. > > > > 3) Your commonprefix and +1 appears to result in same > > information that the easier to use os.path.basename() > > would give you. Double check me on that. > > > > I don't see anything that references C:\\aaa\temp in your > > code. Does it exist on your hard drive? If so does it > > maybe contain temp files that are open? zipfile module > > can't handle open files. You must use try/except to > > catch these errors. > > > > Hope info helps. > > > > -Larry > > Thank you Larry. > I've changed the code as epr your advice. The code is now: > > import zipfile, os > > def toZip( directory, zipFile ): > """Sample for storing directory to a ZipFile""" > z = zipfile.ZipFile( > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > ) > def walker( zip, directory, files, root=directory ): > for f in files: > f = os.path.join( directory, f ) > archiveName = os.path.basename(f) > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > print f > os.path.walk( directory, walker, z ) > z.close() > return zipFile > > > if __name__ == "__main__": > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > I still get the same error: > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Python24\Scripts\dirZip.py", line 20, in ? > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > File "C:\Python24\Scripts\dirZip.py", line 14, in toZip > os.path.walk( directory, walker, z ) > File "C:\Python24\lib\ntpath.py", line 329, in walk > func(arg, top, names) > File "C:\Python24\Scripts\dirZip.py", line 12, in walker > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > File "C:\Python24\lib\zipfile.py", line 405, in write > fp = open(filename, "rb") > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp' > > c:\\aaa\\temp is a directory in the directory I an trying to zip. I > want to use this script to back up my work once a day and would like > to > keep the directory structure as is. I can zip the files in c:\aaa\tem > fine so I guess that there aren't any open files in the directory. > Any more ideas? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hg at nospam.org Tue Feb 27 00:26:44 2007 From: hg at nospam.org (hg) Date: Tue, 27 Feb 2007 06:26:44 +0100 Subject: Is there a technic to avoid this bug Message-ID: Hi, In C/C++ I got used to write an expression like so: #define TEST 0 if (TEST == value) { } in order to avoid the usual bug: if (value = TEST) { } In a relatively similar domain, I spent a few hours find this bug: value == self.Get_Value() if value == WHATEVER: do this instead of value = self.Get_Value() if value == WHATEVER: do this Is there a way to avoid such a bug with some type of construct ? Thanks, hg From TheOneRedDragon at gmail.com Sat Feb 10 06:38:43 2007 From: TheOneRedDragon at gmail.com (TheOneRedDragon at gmail.com) Date: 10 Feb 2007 03:38:43 -0800 Subject: Wait for keypress In-Reply-To: <1171107349.967104.283080@j27g2000cwj.googlegroups.com> References: <1171107349.967104.283080@j27g2000cwj.googlegroups.com> Message-ID: <1171107523.903169.70510@v33g2000cwv.googlegroups.com> Sorry, accidental key presses before I finished... From J.Fine at open.ac.uk Thu Feb 22 12:14:32 2007 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Thu, 22 Feb 2007 17:14:32 -0000 Subject: [ANN] MathTran project Message-ID: MathTran is a JISC funded project to provide translation of mathematical content as a web service. MathTran will be using TeX to provide mathematical typography, and will use Python as its main programming language. http://www.open.ac.uk/mathtran/ http://www.jisc.ac.uk/ http://www.jisc.ac.uk/whatwedo/programmes/elearning_framework/toolkit_mathtran.aspx -- Jonathan Fine The Open University, Milton Keynes, England From edreamleo at charter.net Thu Feb 15 20:04:34 2007 From: edreamleo at charter.net (Edward K Ream) Date: Thu, 15 Feb 2007 19:04:34 -0600 Subject: Pep 3105: the end of print? References: <1171581046.974284.271750@q2g2000cwa.googlegroups.com> Message-ID: > Isn't the very concept of major releases (1.x, 2.x, 3.x) that they *can* > be not backwards-compatible with previous releases? Not at all. Backwards compatibility means that one can still run old code provided the code eschews new features. Python releases have generally been backwards compatible with previous releases, with a few minor exceptions. For example, my app runs fine on Python 2.2.2 through Python 2.5, and little work was required to make this happen. In fact, my app should run find on Python 3.x, but that's because it doesn't use print :-) In other words, the consequence of pep 3105 will be that *nobody* who wants their app to be portable will be able to use print until *everybody* has converted to Python 3.x. I doubt that is what Guido had in mind, but I may be mistaken :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From gigs at hi.t-com.hr Sat Feb 17 08:23:13 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Sat, 17 Feb 2007 14:23:13 +0100 Subject: Tkinter __call__ In-Reply-To: References: <65gBh.76610$qO4.45156@newssvr13.news.prodigy.net> Message-ID: James Stroud wrote: > Gigs_ wrote: >> James Stroud wrote: >>> Gigs_ wrote: >>>> def printit(self, name): >>>> print name, 'returns =>', demos[name]() >>>> >>>> >>>> I have tried but cant get it to work properly. >>>> I want to instead printit method to put __call__ and call it like that >>>> Can someone help me, please? > >> I understand lambda, and I know that code is working. But want to do >> for exercise with __call__. This coed is from programming python 2ed boo > > You want to use a function factory that itself defines "__call__"? This > requires creating a class and not a function. > > > class printit(object): > def __init__(self, name): > self.name = name > def __call__(self): > print self.name, 'returns =>', demos[self.name]() > > class Demo(Frame): > def __init__(self, parent=None): > Frame.__init__(self, parent) > self.pack() > Label(self, text="Basic demos").pack() > for (key, value) in demos.items(): > func = printit(key) > Button(self, text=key, command=func).pack(side=TOP, fill=BOTH) > > > However, the functional way (as with lambda) is the most widely used way > to do this. Another functional way is with closure: > > def printit(key): > def _f(): > print key, 'returns =>', demos[key]() > return _f > > Which behaves identically to the class above. Even more ways to do this > exist in python, including partial functions--which are also a > functional approach. > > James thanks man From mmanns at gmx.de Fri Feb 23 10:35:19 2007 From: mmanns at gmx.de (Martin Manns) Date: Fri, 23 Feb 2007 10:35:19 -0500 Subject: Rational numbers Message-ID: <20070223103519.08f25af9@localhost> Hi, I am starting to use rationals and since I found no batteries included, I tried out the mxNumber package. However, I get strange warnings on comparison operations (which however seem to yield correct results): --- $ python Python 2.4.3 (#1, Jan 15 2007, 15:46:19) [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from mx.Number import * >>> a=Rational(0,1) >>> a 0/1 >>> str(a) '0.0' >>> b=-5000000000000000000000000000000000000000000000000000000000 >>> b -5000000000000000000000000000000000000000000000000000000000L >>> a==b __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1 False >>> --- How do I get rid of these warnings? Is there any rational number library around that 1) is comparably fast for large denominators 2) allows deriving types from Rationals without wrapping? Regards Martin P.S. The respective mailing list does not like me, so that I try my luck here. From dimitri.pater at gmail.com Thu Feb 8 10:27:03 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 8 Feb 2007 16:27:03 +0100 Subject: python linux distro In-Reply-To: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: Hi, the world doesn't need another Linux distro, there are too many already... (> 100) I believe it's a better idea to spend your time contributing to an existing distro (e.g. http://www.ubuntu.com/developers/bounties) doing Python related stuff. Besides that, all distros I know of (4) already have a lot of Python packages ready for download. regards, Dimitri On 8 Feb 2007 06:44:22 -0800, azrael wrote: > > Hy guys > > last night i was lying in my bed and thinking about something. is > there any linux distro that is primary oriented to python. you know > what i mean. no need for php, java, or something like this. pure > python and containig all the funky modules like scipy, numpy, > boaconstructor (wx of course). something like the python enthought > edition, but all this on a distro included. maybe psql but persistant > predered, zope of course. everything a developer is ever going to > need. > So i stood up, sat down on my ugly acer notebook with a python stiker > on it and made a huge list of cool modles i would prefer. I would like > to make such a distro but i am not a linux pro. so this is going to > stay just a idea. i thouht it should be realy user fredly like sabayon > or ubuntu (without xgel). if this were a live distro it would be > amazing. > I know, dont expet someone else to do your work, but is there anyone > who likes the idea and has the knowledge i dont have. > I also know for quantian (cool distro), but for me, there is too much > other crap and not enough python. > > i even got the nam of it. maybee not the best but it fits the context. > PyTux > > > > ----------------------------------------------- > and no, I am not a junkee, I'm addicted to Python > > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From S.Mientki-nospam at mailbox.kun.nl Sun Feb 4 13:34:09 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 04 Feb 2007 19:34:09 +0100 Subject: "Subscribing" to topics? In-Reply-To: References: Message-ID: <5afab$45c6270c$d443bb3a$5292@news.speedlinq.nl> Mizipzor wrote: > Is there a way to "subscribe" to individual topics? im currently > getting bombarded with daily digests and i wish to only receive a mail > when there is activity in a topic that interests me. Can this be done? > > Thanks in advance. I'm relative new (couple of months), and although there seems already to be a few different categories, I see a lot of posts of experienced users, that completely ignore these differences (or perhaps I don't understand a bit of it ;-). [ANN] is this group, I thought we had: python-announce at python.org pycon-announce at python.org Scipy questions, I thought we had: scipy-user at scipy.org Delphi, I thought we had: pythonfordelphi at yahoogroups.com Probably there are a number of other groups (would be nice to have a list of these) here is the description list that I'm subscribed for many years, that uses good defined topics http://www.piclist.com/techref/piclist/index.htm It has one major disadvantage for newbies, if a message without the proper tag arrives, it is blocked and can be manual added to the list by the moderator. cheers, (and sorry for all the stupid newbie posts, which probably is not of your interest ;-) Stef Mientki From dimitri.pater at gmail.com Tue Feb 6 18:03:07 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 7 Feb 2007 00:03:07 +0100 Subject: Graphs, bar charts, etc In-Reply-To: <45c87a32@griseus.its.uu.se> References: <45c87a32@griseus.its.uu.se> Message-ID: Hi, check out chartdirector : http://www.advsofteng.com/ it's not free, but very easy to use right now I am testing it here: http://www.serpia.org/water a very simple barchart regards, Dimitri On 2/6/07, Jan Danielsson wrote: > > Hello all, > > I have some data in a postgresql table which I view through a web > interface (the web interface is written in python -- using mod_python > under apache 2.2). Now I would like to represent this data as graphs, > bar charts, etc. > > I know about matplotlib, and it seemed like exactly what I was > looking for. I tried importing it in my script, but it gave me some > error about a home directory not being writable. I'm not sure I like the > idea of it require to be able to write somewhere. Am I using it wrong? > > Is there something else I can use which can produce graphs easily? > > -- > Kind regards, > Jan Danielsson > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sat Feb 3 00:09:43 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Feb 2007 16:09:43 +1100 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> Message-ID: <87d54ru8rs.fsf@benfinney.id.au> Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: > Why should the hosting provider need to devote attention to > something like that? MySQLdb or something like it should be > included with Python, not added separately by the hosting provider. "Something like it" *is* included in Python. Python 2.5 includes SQLite in the standard library. Where do we draw the line? You want MySQL, I want PostgreSQL, he wants Firebird, they want an interface to something proprietary. The standard library is for modules that are *small* and/or *generally useful*. SQLite meets the former, and to some extent the latter, far more than does a MySQL interface. All the *extra* stuff is what you're paying the hosting company to take care of in the first place. -- \ "It's a small world, but I wouldn't want to have to paint it." | `\ -- Steven Wright | _o__) | Ben Finney From mantaintai at yahoo.com.cn Thu Feb 1 01:31:03 2007 From: mantaintai at yahoo.com.cn (mantaintai at yahoo.com.cn) Date: 31 Jan 2007 22:31:03 -0800 Subject: I uncover the secret of visual consciousness Message-ID: <1170311463.391041.174520@j27g2000cwj.googlegroups.com> I uncover the secret of visual consciousness Proof of visual consciousness >From image formation by a plane mirror to the generation of (human) visual consciousness image formation by a plane mirror , visual consciousness, transform, virtual image , overlap(superpose), dual identities, seeing an object How could an object become visible when observed by the eyes of the human beings, i.e., how could the electrochemical changes of the visual cortex and cerebral cortex be transformed into an object? Apparently, this transformation would never occur if we take the word "transformation" by the common sense. However, given the fact we could indeed see an object, the changes in the visual and cerebral cortex MUST have already been transformed into an object. Therefore, "transformation" here should have other implications more profound than commonly understood , and we ought to find out the mechanism and pathway involved in this process. The electrochemical changes in the visual and cerebral cortex must be firstly translated into an image. Then this image ought be changed into the corresponding object. In comparison with image formation by a plane mirror, we would elucidate the mechanisms and pathways of these most unexpected transformations, with an effort to reveal the mystery of visual consciousness . Does it hold true that the mirror itself produces the image (a virtual image) formed by a plane mirror? Definitely no. The virtual image is produced by the brains of human beings and animals, rather than by the mirror itself. Can it be more clearly demonstrated that the virtual image is generated via the brain, than analyzing the process during which the light enters into a plane mirror from the object, and then gets into the eyes and brain, thus leading to the visualization of the virtual image? Can we assume that there exists a virtual image before the light enters the eyes? Of course we cannot. The single role a plane mirror plays in the whole process is the reflection of light. However, after entering into the eyes, do not these reflected lights need further procession by the brain? The eventual result of this procession is seeing the virtual image. The reason why we are capable of taking photos of an object while taking pictures facing the plane mirror with a camer is NOT due to our capability to capture a virtual image, as there is no real light given out by the virtual image; rather, it lies in the fact that the reflected light is able to enter into the lens of the camera. As shown by Fig A, the convergence of the inverse expansion lines helps to explain the position of a virtual point. However, neither the virtual points nor the virtual images are produced by the convergence of the inverse expansion lines, as the latter are not actual entities while the former are existing facts. How could a non-existing inverse expansion line be used to explain the existing actual fact of a virtual image? In fact, it is exactly the mechanism of image generation in the brain that defines the laws(/rules) of image formation by a plane mirror. What is the ultimate role for the fact that the brain is capable of producing (/generating) an image( virtual image)? Actually, it is exactlly this capability that enables a human being to achieve the final results, i.e. , seeing an object, during the process of visual consciousness generation. In the following, we will explain how the brain sees an object when obseved by a human being. As shown by Fig B, when an object A is observed by the eyes and the brain O, a virtual image A' is fomed (/produced) in the first place, which possesses two unique characteristics. Firstly, it is exactlly identical to the object A itself. Secondly, and the most strikingly, it can be filled with the corresponding object, resulting in what we called the overlapping?superposing) of an object with its virtual image. Only the virtual image itself can be entirely overlapped(superposed) by the related object, and the space a virtual image occupys is called the virtual space , while the space of an object is defined as the physical space. Fig C shows that the virtual image A' and the object A are overlapped(superposed), leading to the presentation of both A' and A in the same position. Because the virtual image A' and the corresponding object A utilize an identical image after overlapping on each other,So, the image here has dual identities, with one as a virtual image and the other a physical object. The image has an extra character ,The image becomes the object A. Thus, as we see the virtual image A', we are actually observing the object A itself. It becomes apparent that the final result of visual consciousness is achieved via a two-step process, i.e., the formation of a virtual image in the first place, and secondly the overlapping(superposing) of this virtual image with the corresponding object. It is the process of overlapping(superposing) that turns a virtual image into a visible object. This unique character( of a virtual image) is best utilized in a most perfect and magic way during the final stage of visual consciousness. A A' ____|______|______0 ?the eyes and the brain ? B Fig A A' ____|_____________ 0 ?the eyes and the brain ? C Fig my email:mantaintai at yahoo.om.cn mantaintai From see at signature.invalid Fri Feb 2 22:27:12 2007 From: see at signature.invalid (Douglas Wells) Date: Fri, 2 Feb 2007 22:27:12 -0500 (EST) Subject: result of os.times() is different with 'time' command References: <1170441001.097986.294510@h3g2000cwc.googlegroups.com> <1170446796.156141.201960@v33g2000cwv.googlegroups.com> Message-ID: [various posting problems corrected and response interspersed in previous post for purposes of coherent response] In article <1170446796.156141.201960 at v33g2000cwv.googlegroups.com>, "aspineux" writes: > On 2 Feb, 19:30, kwa... at gmail.com wrote: > > Hi, > > > > I have a question about os.times(). > > os.times() returns a tuple containing user time and system time, > > but it is not matched to the result of 'time' command. > > For example, os.times() reports that user time is 39.85 sec, > > but 'time' command reports that user time is 28.55sec. > > (machine: Python2.5, MacOS X 10.4 Tiger, MacBook 1.83GHz intel core > > duo) > > > > [ source elided ] > > I dont see anything wrong ! > Did you try to measure time with your watch ? > Did you try a simple python test.py without the time command ? > Maybe python is 'disturbed' by the intel core > > can you try this ? > > # strace python test.py 2>&1 | grep time > times({tms_utime=1, tms_stime=1, tms_cutime=0, tms_cstime=0}) = > 430217777 > times({tms_utime=2238, tms_stime=2, tms_cutime=0, tms_cstime=0}) = 430220049 > write(1, "n=35, v=14930352\nutime=22.37, st"..., 41n=35, v=14930 52 > utime=22.37, stime=0.01 Note that this likely won't work. First, strace is not native to OS X; ktrace is the analogous native command. Second, OS X almost certainly implements the times system call in terms of getrusage. > > Result: > > ==================== > > $ python -V > > Python 2.5 > > $ time python ostimetest.py > > n=35, v=14930352 > > utime=39.85, stime=0.216666666667 > > real 0m28.554suser 0m23.938ssys 0m0.177s > > ==================== > > > > This shows that os.times() reports that user time is 39.85sec, > > but time command shows that user time is 23.938sec. > > Why os.times() reports wrong result? Do I have any mistake? > > > > -- > > kwatch Yes, I can reproduce this on my FreeBSD system. No, I do not believe that you have made a mistake. Yes, I believe that you have uncovered a bug in the Python os/posix modules. Here's my analysis (although I should note that I've not looked at the source of Python previously). I'm looking at Python 2.4.3, but this looks like a long existing bug: The following code exists in the source code module Modules/posixmodule.c @ posix_times: struct tms t; clock_t c; [ ... ] c = times(&t); [ ... ] return Py_BuildValue("ddddd", (double)t.tms_utime / HZ, (double)t.tms_stime / HZ, (double)t.tms_cutime / HZ, (double)t.tms_cstime / HZ, (double)c / HZ); This is incorrect. It should not be dividing by HZ, but by the result of the dynamic value 'sysconf (_SC_CLK_TCK)'. Even if it were to use a compile time value, the proper value would be CLK_TCK, not HZ. So here's what's happening. Neither my FreeBSD nor the OP's Mac defines HZ as a compile time variable, but the same source module also contains the following code: #ifndef HZ #define HZ 60 /* Universal constant :-) */ #endif /* HZ */ So, the Python posix module is using 60 instead of the proper value, which happens to be 128 on my FreeBSD, and 100 on the OP's OS X(*). (BTW, this sort of historic code is exactly why POSIX no longer defines HZ.) In support of this, I note that the following ratios exist: user time from os.times / user time from time command 39.85 / 23.938 => 1.665 CLK_TCK / HZ 100 / 60 => 1.667 which are in reasonably close agreement! - dmw [*] I've actually only looked at OS X for the PPC platform, not for the User's Intel platform, but I'm fairly certain that the CLK_TCK value is the same on both. -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From bernhard.voigt at gmail.com Mon Feb 19 06:07:36 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 19 Feb 2007 03:07:36 -0800 Subject: ipython shortcut to reload modules Message-ID: <1171883255.942996.270800@v33g2000cwv.googlegroups.com> Hey! I'm using ipython as my python shell and often run scripts with the magic command %run: In [1]: %run script.py If modules are loaded within the script these are not reloaded when I rerun the script. Hence, when I changed some of the modules loaded, I have to call In [2]: reload(module1) Out [2]: Message-ID: <288193.94087.qm@web31108.mail.mud.yahoo.com> > I have certain data in the default file format ( GADGET ) . Can you be more specific about the file format? what is the exact name, or the format specification? --------------------------------- It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Fri Feb 9 09:14:45 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 9 Feb 2007 08:14:45 -0600 Subject: TimedRotatingFileHandler() isn't rotating at midnight? In-Reply-To: <86tzxvwhjn.fsf@Bacalao.shenton.org> References: <1171021836.812953.183150@m58g2000cwm.googlegroups.com> <86tzxvwhjn.fsf@Bacalao.shenton.org> Message-ID: <17868.33237.648247.591305@montanaro.dyndns.org> >> Rotating should happen when the logging process creates the handler >> before midnight and makes a logging call destined for that handler >> after midnight. Chris> Ah, then maybe I'm expecting the wrong thing. The python code is Chris> invoked from cron every 10 minutes or so, it's not long-running. Chris> Each time it opens the same log file. Sounds like this isn't Chris> going to do what I want. Right. Check out the logrotate facility on your system. Skip From richard_l at latter.demon.co.uk Thu Feb 22 11:48:24 2007 From: richard_l at latter.demon.co.uk (richard_l at latter.demon.co.uk) Date: 22 Feb 2007 08:48:24 -0800 Subject: How can I track/monitor an application and system resources. Message-ID: <1172162904.289214.102750@q2g2000cwa.googlegroups.com> Hello All, I'm a newbie to Python! I am trying to develop a program that monitors the performance of an application. The kind of information I am interested in is the CPU/ Process/Thread and memory performance. Specifically, I would like to track the following CPU usage Used Memory on Phone Free Memory on Phone Number of Processes running Number of threads running Number of Filehandles currently open Memory used by a process/thread Process/Thread CPU activity. All this under Windows Can anyone help me, or direct me to the appriopriate API's so I can get the above information? Does anyone have any other sugestions on what else I could monitor for a running application? Does anyone have any example code they can direct me to? Many thanks in advance, Richard From fuzzyman at gmail.com Thu Feb 8 19:33:48 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 8 Feb 2007 16:33:48 -0800 Subject: Best Free and Open Source Python IDE In-Reply-To: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1170981228.353994.288330@v33g2000cwv.googlegroups.com> On Feb 8, 12:03 pm, "Srikanth" wrote: > Yes, > > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Please > recommend. > > Thanks, > Srikanth There's a new kid on the block (free and OSS) which doesn't get much press. I've only played with it - but it looks good: Ulipad I used Spe happily for a couple of years and PythonWin has a good following. (Windoze only of course.) I've used Eclipse plus the free PyDev a bit - it seemed very good. What was your problem with it? I personally use Wing, which I have a free license for as an OSS developer. It is commercial (we now use it at work as well) but I like it a great deal. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From michele.simionato at gmail.com Thu Feb 1 06:15:31 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 Feb 2007 03:15:31 -0800 Subject: how do I pipe two processes? In-Reply-To: <1170321143.287492.4300@k78g2000cwa.googlegroups.com> References: <1170321143.287492.4300@k78g2000cwa.googlegroups.com> Message-ID: <1170328530.957946.209990@v33g2000cwv.googlegroups.com> On Feb 1, 10:12 am, Bilgehan.Bal... at gmail.com wrote: > Hi, I want to pipe output of process A to B, and read output of B from > python. On Unix if I do the following: > > child_out, child_in = popen2("program_a | program_b") > > line = child_out.readline() > > I get "IOError: bad file descriptor" from Python, and broken pipe > error from program_b. How do I do this right? > > Thanks, > Bahadir Use the subprocess module, see the examples here: http://docs.python.org/dev/lib/node539.html Michele Simionato From gagsl-py at yahoo.com.ar Mon Feb 12 17:25:31 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 19:25:31 -0300 Subject: SystemError: _PyImport_FixupExtension: module _types not loaded References: <1171305876.030471.59470@s48g2000cws.googlegroups.com> Message-ID: En Mon, 12 Feb 2007 15:44:36 -0300, escribi?: > I'm trying to write some "C" code that will run a python script that > can in turn call some "C" functions. However I'm having a problem > getting started because although I can run a script from the python > ide that imports ctypes, when I execute that 'import ctypes' code from > the "C" code I get the following error: > > 'import site' failed; use -v for traceback You have to fix this first. Probably you can't import anything, not just ctypes. Quoting myself from a similar problem: Try this: PyRun_SimpleString("import sys; print sys.path"); to see where Python expects to find its library (or call the Py_GetPath function). You may need to call Py_SetProgramName (before Py_Initialize) so it can find where the standard library resides. At least for testing purposes, you can copy your executable into the same directory where Python is installed. -- Gabriel Genellina From uval at rz.uni-karlsruhe.de Mon Feb 19 12:48:01 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Mon, 19 Feb 2007 18:48:01 +0100 Subject: pylab, integral of sinc function In-Reply-To: <7xwt2d7g83.fsf@ruckus.brouhaha.com> References: <7xwt2d7g83.fsf@ruckus.brouhaha.com> Message-ID: [...] >> In [19]: def simple_integral(func,a,b,dx = 0.001): >> ....: return sum(map(lambda x:dx*x, func(arange(a,b,dx)))) > > Do you mean > > def simple_integral(func,a,b,dx = 0.001): > return dx * sum(map(func, arange(a,b,dx))) > yes, this should be faster :) From mail at microcorp.co.za Tue Feb 13 02:00:14 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 13 Feb 2007 09:00:14 +0200 Subject: Help with Optimization of Python software: real-time audiocontroller References: <20070212144020.25807.1403887471.divmod.quotient.19184@ohm> Message-ID: <021b01c74f4e$8955e660$03000080@hendrik> "Jean-Paul Calderone" wrote: > Yep. There are even some existing Python applications which deal with > sound and manage to work with ~20ms samples. I agree. Python is not *that* slow... I have written serial port communications that send and catch one character at a time (raw, unbuffered i/o) - and they seem to work well at 38400 baud, sending and receiving almost four characters a millisecond, continuously, back to back, without any stress So to "get there" every twenty millis should not be a problem, unless the machine is a real dog. (i.e. older than seven years) Would not try to handle individual samples at 44 KiloHerz in python though... - Hendrik From karoly.kiripolszky at gmail.com Sat Feb 3 08:48:40 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 3 Feb 2007 05:48:40 -0800 Subject: strange test for None In-Reply-To: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> References: <1170510427.981922.170100@m58g2000cwm.googlegroups.com> Message-ID: <1170510520.754880.313830@v33g2000cwv.googlegroups.com> forgot to mention my interpreter version: 2.4.4 From dieterv at optionexplicit.be Sat Feb 24 09:26:14 2007 From: dieterv at optionexplicit.be (Dieter Verfaillie) Date: Sat, 24 Feb 2007 15:26:14 +0100 Subject: Newbie in the deep - some PyGTK questions In-Reply-To: <45ded1a1$0$325$e4fe514c@news.xs4all.nl> References: <45ded1a1$0$325$e4fe514c@news.xs4all.nl> Message-ID: <1172327174.18829.17.camel@PO001> Hi, On Fri, 2007-02-23 at 11:36 +0000, nmp wrote: > First "problem": when I insert the glade file in my application the way > some tutorials have shown me: > > self.wTree = gtk.glade.XML("autostart.glade", "mainWindow") > > ... Python is consistently giving me this warning: > > /home/xxxx/Projecten/autostart/autostart.py:18: GtkWarning: > gtk_widget_grab_default: assertion `GTK_WIDGET_CAN_DEFAULT (widget)' > failed > self.wTree = gtk.glade.XML("autostart.glade", "mainWindow") I think you've set the "Has default" property to Yes on some widget, but you forgot to set the "Can default" property to Yes on that same widget. In short, you created a default widget that can't be the default and gtk happily complains about that. Check your glade file to fix it. > Now I want the user of my program to be able to just double click a row or > hit Enter to flip the boolean, so FALSE becomes TRUE and vice versa. See the answer to your third "problem" :) > The third "problem" (for now...) is really just a cosmetic thing. The > representation of the boolean in the list is fine for me, but in time I > would like to make it prettier by replacing it with a graphical checkbox. > Does anyone have an example of this that I can use? Use a CellRendererToggle. There's a tutorial on the pygtk website: http://pygtk.org/pygtk2tutorial/sec-CellRenderers.html (scroll all the way down that page to "Figure 14.6. Editable and Activatable Cells") > Thank you for your patience. I can already see how all this is going to > keep me busy for weeks and it will be fun ;) You'll probably get faster/better answers to you pygtk questions on the pygtk mailing list: http://www.daa.com.au/mailman/listinfo/pygtk Have fun, Dieter From fccoelho at gmail.com Thu Feb 22 09:21:55 2007 From: fccoelho at gmail.com (Flavio) Date: 22 Feb 2007 06:21:55 -0800 Subject: plugin development best practices In-Reply-To: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> References: <1172148782.249191.40410@v33g2000cwv.googlegroups.com> Message-ID: <1172154115.054296.214120@t69g2000cwt.googlegroups.com> On Feb 22, 10:53 am, "Flavio" wrote: > Hi, > > Nowadays the addition of functionality to programs by means of > plugins is very frequent. > > I want to know the opinions of experienced Python developers about the > best practices when it comes to developing apluginsystemfor a > Python package. > > Should plugins be modules in a separate package? > Should there be a registry of available plugins? how would such a > registry be implemented? etc. > > thanks, > > Fl?vio let me extend my original question with an example: Simple plugin system proposal: have a package (directory with __init__.py) called plugins where the actual plugins are modules in this directory. When the main script imports the plugins package, all plugin modules would be available as plugins.pluginA, plugins.pluginB , etc. A registry of available plugins would be available as a simple dir(plugins). code in the main script than wished to use a given plugin, would only have to look in the registry before calling any code from a given plugin. What is wrong/missing with this simple framework? I'd appreciate any comments. Fl?vio From steveo at syslang.net Wed Feb 28 16:49:08 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 28 Feb 2007 16:49:08 -0500 (EST) Subject: Question about raise and exceptions. In-Reply-To: <45e5e640$0$18215$426a74cc@news.free.fr> References: <45e5e640$0$18215$426a74cc@news.free.fr> Message-ID: On Wednesday, Feb 28th 2007 at 22:03 +0100, quoth Bruno Desthuilliers: =>Daniel Klein a ?crit : =>> On Wed, 28 Feb 2007 13:48:54 -0500 (EST), "Steven W. Orr" =>> wrote: =>> =>> =>>>When I run it I get this: =>>> =>>>884 > ./t_fsm.py =>>>Traceback (most recent call last): =>>> File "./t_fsm.py", line 3, in ? =>>> from fsm import * =>>> File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76 =>>> raise TransitionError, self.curr_state, newstate, "Going to error =>>>state %d from state %d" % (self.curr_state, newstate) =>>> ^ =>>>SyntaxError: invalid syntax =>> =>> =>> The arguments for TransitionError must be a tuple, => =>Err... => =>> eg: =>> =>> msg = "Going to error state %d from state %d" % (self.curr_state, =>> newstate) =>> raise TransitionError(self, curr_state, newstate, msg) => =>Where did you see a tuple here ? You're code is *calling* =>TransitionError, passing it the needed arguments. => =>Note that it's the correct syntax - but not the correct explanation !-) Ok. Now I'm potentially confused: 1. TransitionError takes 4 args 2. raise takes a tuple with four elements after the exception argument as its 2nd arg I take it you mean #2? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From gagsl-py at yahoo.com.ar Fri Feb 2 23:04:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Feb 2007 01:04:19 -0300 Subject: Numeric and PIL Files? References: Message-ID: En Sat, 03 Feb 2007 00:03:09 -0300, W. Watson escribi?: > I'm looking at some files that are related to Python: > > Python-2.4.2.msi This is the Windows installer for Python 2.4.2; you should instead use the 2.4.4 version (last one on the 2.4 series). There should be no compatibility issues, and latter releases have many bugs corrected. (extension modules must match the Python version up to the 2nd digit). You can get it from http://www.python.org/download/ > Numeric-24.2.win32-py2.4.exe This is version 24.2 of a numerical library for Python; this is the binary install matching Python 2.4 For new projects, the recommended library is NumPy. See http://numpy.scipy.org/ > PIL-1.1.5.win32-py2.4.exe This is Python Imaging Library, available from www.effbot.org. Either choose the 1.1.5 or 1.1.6 version, but make sure it matches your python version (filename ends in py2.4) -- Gabriel Genellina From tjreedy at udel.edu Fri Feb 2 15:22:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Feb 2007 15:22:44 -0500 Subject: Is Python Right for Me? References: Message-ID: "Mister Newbie" wrote in message news:Xns98CB9A2CC9C3Bn00b at 208.49.80.253... |I want to make small, 2D games. I have no programming experience. Is Python | a good choice? Possibly. There is an add-on package called pygame that is, I believe, 2d oriented. See www.pygame.org There is also an associated mailing list, which you can also read via news.gmane.org as newsgroup gmane.comp.python.pygame. tjr From deets at nospam.web.de Tue Feb 20 06:48:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Feb 2007 12:48:07 +0100 Subject: wxPython: non-GUI thread launching new frame? Delegates? References: <1171970385.863147.78290@t69g2000cwt.googlegroups.com> Message-ID: <5405fnF1upuuoU1@mid.uni-berlin.de> cyberco wrote: > In my wxPython app a non-GUI thread (that reads info from the network) > tries to open a frame to show the new info. This results in my app > hanging (which is not too surprising). Coming from a C# environment I > wonder if there is some sort of delegate mechanism in wxPython to do > this sort of thing. Not sure how wx deals with this, but one thing you might explore is the possibility to add a timer in the GUI-thread, that polls a thread-filled queue. Other toolkits as Qt have means to insert an extra event in the event queue of the gui-thread in a thread-agnostic way, maybe wx has that too. Googling... ... ... ... ... finished http://mail.python.org/pipermail/python-list/2005-August/335467.html """ You need another way to pass completion information between the downloader thread and the main thread; the simplest way is to define a custom wx Event, and wxPostEvent from the downloader thread when it completes ( and when the gauge should be updated). wxPostEvent is safe to call from non-eventloop threads. The main thread's wx event loop just spins, properly updating all other parts of the GUI, and receiving events from the downloader thread. ANother approach is to have a thread-safe Queue and have the main thread/event loop poll the queue with queue.get_nowait() periodically (typically 0.1-1 sec). The downloader thread shares the queue object and puts data structures (typically class instances, strings, or ints) that indicate status updates. """ So - both options a viable. And read to the end, the twisted-approach certainly is the most clean one. Diez From hg at nospam.org Sun Feb 4 04:51:21 2007 From: hg at nospam.org (hg) Date: Sun, 04 Feb 2007 10:51:21 +0100 Subject: "Subscribing" to topics? References: Message-ID: <5aoxh.7440$gJ1.6708@newsfe17.lga> Mizipzor wrote: > Is there a way to "subscribe" to individual topics? im currently > getting bombarded with daily digests and i wish to only receive a mail > when there is activity in a topic that interests me. Can this be done? > > Thanks in advance. Use a news reader and leave the mailing list hg From jfine at pytex.org Tue Feb 6 08:34:14 2007 From: jfine at pytex.org (Jonathan Fine) Date: Tue, 06 Feb 2007 13:34:14 +0000 Subject: Two mappings inverse to each other: f, g = biject() References: <45C856E4.6090307@pytex.org> <1170764593.777423.287240@h3g2000cwc.googlegroups.com> Message-ID: <45C883D6.2050203@pytex.org> Nick Vatamaniuc wrote: > If you need to get a short name, given a long name or vice-verse _and_ > the set of short names and long names is distinct (it would be > confusing if it wasn't!) then you can just have one dictionary, no > need to complicate things too much: > f[a]=b > f[b]=a > You won't know which is a short and which is a long based just on > this, so you need to keep track of it. But it will give you the > mapping. Thank you for this suggestion, Nick. It's not something I thought of. And I'm sure that in some cases it might be just the right thing. It would hold something like 'other-name' values. (Every cat should have at least two names ...) But for my application, I think it complicates the code that uses the bijection. For example, I want to say: # Write the font dictionary to a file for key in font_dict: # write the font # Does value already exist in the font dictionary? # If not, add it to the font dictionary. key = font_dict.inverse.get(value) if key is None: key = len(font_dict) font_dict[key] = value Following your suggestion, ingenious though it is, would make the above code much more complicated and error prone. Perhaps it helps to think of f, g = biject() as establishing a database, that has a consistency condition, and which has two views. There we are: biject() gives two views on a mapping (of a particular type). Thank you for you suggestion - it has clarified my thinking. -- Jonathan From steve at holdenweb.com Fri Feb 16 11:38:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Feb 2007 11:38:28 -0500 Subject: Pep 3105: the end of print? In-Reply-To: <20070216144903.25807.996277675.divmod.quotient.23913@ohm> References: <20070216144903.25807.996277675.divmod.quotient.23913@ohm> Message-ID: Jean-Paul Calderone wrote: > On Sat, 17 Feb 2007 01:32:21 +1100, Steven D'Aprano >> [snip] >> >> I don't think that follows at all. print is only a problem if you expect >> your code to work under both Python 2.x and 3.x. I wouldn't imagine >> that many people are going to expect that: I know I don't. > > I think some people are confused that the language "Python 3.x" has "Python" > in its name, since there is already a language with "Python" in its name, > with which it is not compatible. > Right. Let's call Python 3.0 something different but related. How about "snake oil"? ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From shanekwon at gmail.com Wed Feb 14 00:15:19 2007 From: shanekwon at gmail.com (agent-s) Date: 13 Feb 2007 21:15:19 -0800 Subject: python not returning true Message-ID: <1171430119.604777.226820@v45g2000cwv.googlegroups.com> I have a function, generally described as so: def function(args): if condition: if condition2: function(args+1) elif condition3: print "text" return True else: return False which is used in: if function(args): print "ok" so here basically "text" will print out when condition3 is true but it will not print out "ok" when condition3 is true. When it's true it should print out borth "text" and "ok" From gherron at digipen.edu Mon Feb 19 00:38:48 2007 From: gherron at digipen.edu (Gary Herron) Date: Sun, 18 Feb 2007 21:38:48 -0800 Subject: What is more efficient? In-Reply-To: References: Message-ID: <45D937E8.1040900@digipen.edu> Karlo Lozovina wrote: > Let's say I have a class with few string properties and few integers, and > a lot of methods defined for that class. > > Now if I have hundreds of thousands (or even more) of instances of that > class - is it more efficient to remove those methods and make them > separate functions, or it doesn't matter? > > Thanks... > It is not noticeably more or less efficient in either memory or execution speed. Both method and function code is compiled and stored once in either the class name space (for the method) or the module name space (for the function), and the lookup of either one is a single lookup in the appropriate name space. Actually the method lookup requires one extra step: First look for the method in the instance (which fails) and then look for it in the class (which succeeds). But that extra look up is highly optimized and probably not noticeable. The number of methods/functions may slow things up, but it will affect either name space equally. Gary Herron From http Mon Feb 19 20:47:08 2007 From: http (Paul Rubin) Date: 19 Feb 2007 17:47:08 -0800 Subject: pylab, integral of sinc function References: Message-ID: <7xwt2d7g83.fsf@ruckus.brouhaha.com> Sch?le Daniel writes: > In [19]: def simple_integral(func,a,b,dx = 0.001): > ....: return sum(map(lambda x:dx*x, func(arange(a,b,dx)))) Do you mean def simple_integral(func,a,b,dx = 0.001): return dx * sum(map(func, arange(a,b,dx))) From mbm at mediamonger.ch Mon Feb 12 13:10:02 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Mon, 12 Feb 2007 19:10:02 +0100 Subject: c++ for python programmers In-Reply-To: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> References: <1171303251.796306.79520@p10g2000cwp.googlegroups.com> Message-ID: <45D0AD7A.3010408@mediamonger.ch> SAMS "Teach yourself C in 21 days" by Bradley L. Jones and Peter Aitken Learning C++ is not worth is in my opinion, since you can get the OOP power from Python and use C if you need speed... Thomas Nelson schrieb: > I realize I'm approaching this backwards from the direction most > people go, but does anyone know of a good c/c++ introduction for > python programmers? > > Thanks, > > Thomas > From nathan.shair at gmail.com Thu Feb 15 10:57:39 2007 From: nathan.shair at gmail.com (nathan.shair at gmail.com) Date: 15 Feb 2007 07:57:39 -0800 Subject: output to console and to multiple files In-Reply-To: References: <1171492114.669067.71350@v33g2000cwv.googlegroups.com> Message-ID: <1171555059.735437.15750@v45g2000cwv.googlegroups.com> On Feb 14, 6:52 pm, "Gabriel Genellina" wrote: > En Wed, 14 Feb 2007 19:28:34 -0300, nathan.sh... at gmail.com > escribi?: > > > I'm looking for a way to output stdout/stderr (from a subprocess or > > spawn) to screen and to at least two different files. > > Look at the tee command. If you control the subprocess, and it's written > in Python, using the Python recipes would be easier and perhaps you have > more control. > But if you can't modify the subprocess, you'll have to use tee. > > -- > Gabriel Genellina Tee, the unix function? Or is there a tee that is python? From grante at visi.com Thu Feb 15 00:04:17 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Feb 2007 05:04:17 -0000 Subject: Method overloading? References: <1171515271.811324.218020@s48g2000cws.googlegroups.com> Message-ID: <12t7qehj9jm0a21@corp.supernews.com> On 2007-02-15, placid wrote: > Is it possible to be able to do the following in Python? > > class Test: > def __init__(self): > pass > > def puts(self, str): > print str > > def puts(self, str,str2): > print str,str2 > > if __name__ == "__main__": > t = Test() > t.puts("hi") > t.puts("hi","hello") You tell us: what happened when you tried it? And then what happens when you do this? class Test: def __init__(self): pass def puts(self, *args): print ' '.join(args) if __name__ == "__main__": t = Test() t.puts("hi") t.puts("hi","hello") Now an exercise for the gentle reader: change the puts method so that this call works: t.puts("hi",1,3.45) -- Grant Edwards grante Yow! Yow! I'm imagining at a surfer van filled with visi.com soy sauce! From bj_666 at gmx.net Fri Feb 16 12:07:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 16 Feb 2007 18:07:07 +0100 Subject: why I don't like range/xrange References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> Message-ID: In , Steven D'Aprano wrote: >> for (i = 0 ; i < 10 ; i++) >> i = 10; > > > This would be written in Python as: > > for i in xrange(10): > i = 10 Nope, in Python it's: for i in xrange(10): break I think his example should demonstrate that assigning to the loop variable has no effect on the "loop test". Which IMHO is a good thing. Ciao, Marc 'BlackJack' Rintsch From Eric.Gabrielson at gmail.com Tue Feb 6 19:11:47 2007 From: Eric.Gabrielson at gmail.com (Eric.Gabrielson at gmail.com) Date: 6 Feb 2007 16:11:47 -0800 Subject: Coordinate Grid Points In-Reply-To: References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> <1170727428.120082.47690@a75g2000cwd.googlegroups.com> <1170804943.418026.243480@q2g2000cwa.googlegroups.com> Message-ID: <1170807107.318148.210930@k78g2000cwa.googlegroups.com> On Feb 6, 4:08 pm, "Gabriel Genellina" wrote: > En Tue, 06 Feb 2007 20:35:43 -0300, escribi?: > > > > > Anyways heres my error: > > ************************************************************************************************************************ > > ***File "C:/Documents and Settings/Eric/Desktop/Python/2d guessing > > game.py", line 11, in *** > > *** randp = Point(random.randint(1, 20), random.randint(1, > > 20)) *** > > ***TypeError: default __new__ takes no > > parameters > > *** > > class Point(object): > > def _init_(self, x, y): > > self.x = x > > self.y = y > > > #generate random coordinate point > > randp = Point(random.randint(1, 20), random.randint(1, 20)) > > _init_ should be __init__ (two leading and trailing underscores) > That special method is used to initialize your newly constructed Point > instance. > See section 9.3.2 on the Python tutorial:http://docs.python.org/tut/node11.html#SECTION0011320000000000000000 > > -- > Gabriel Genellina WOW thank you so much I feel like a blind idiot *slaps self on forehead* From deets at nospam.web.de Thu Feb 22 10:13:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Feb 2007 16:13:54 +0100 Subject: plugin development best practices References: Message-ID: <545q9iF1ujiklU1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Thu, 22 Feb 2007 15:36:42 +0100, "Diez B. Roggisch" > wrote: >>> Simple plugin system proposal: >>> >>> have a package (directory with __init__.py) called plugins where the >>> actual plugins are modules in this directory. >>> >>> When the main script imports the plugins package, all plugin modules >>> would be available as plugins.pluginA, plugins.pluginB , etc. >>> >>> A registry of available plugins would be available as a simple >>> dir(plugins). >>> >>> code in the main script than wished to use a given plugin, would only >>> have to look in the registry before calling any code from a given >>> plugin. >>> >>> What is wrong/missing with this simple framework? >> >>Nothing wrong. > > Are you sure? Darn. You're right of course - I just got the basic idea, and formed in my mind the "get the modules filename, thus the path, glob over it for *py, and thus get the subsequent module names"-pattern. Which is trivial of course, but not as trivial as just dir(module) Diez From eh at mad.scientist.com Fri Feb 23 10:46:24 2007 From: eh at mad.scientist.com (Eirikur Hallgrimsson) Date: Fri, 23 Feb 2007 10:46:24 -0500 Subject: Creating a daemon process in Python In-Reply-To: <20070223150123.25807.87474186.divmod.quotient.30418@ohm> References: <20070223150123.25807.87474186.divmod.quotient.30418@ohm> Message-ID: <45DF0C50.90107@mad.scientist.com> I didn't actually write this module. I believe I found it in a discussion in ASPN at Active State. Thanks for the input, and when I get a chance I will try these alternate approaches. This module has been working fine for me as is--so far. Eirikur From mail at microcorp.co.za Wed Feb 14 00:33:07 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 14 Feb 2007 07:33:07 +0200 Subject: Segmentation faults using threads References: Message-ID: <00d601c74ff9$9c6d2c80$03000080@hendrik> "Mathias" wrote: > Does someone have experience with threading in python - are there > non-threadsafe functions I should know about? how do your threads communicate with one another - are there any globals that are accessed from different threads? strange this - you should get an exception, not a segment fault if its in the python bits.. - Hendrik From nejucomo at gmail.com Tue Feb 20 03:27:38 2007 From: nejucomo at gmail.com (Nathan) Date: Tue, 20 Feb 2007 01:27:38 -0700 Subject: Checking for EOF in stream In-Reply-To: References: <12tkgeh32duee72@corp.supernews.com> <45DA45C3.2000707@gentlemail.com> Message-ID: <13f991410702200027gb45f6b0pba8e8e192dabe497@mail.gmail.com> On 2/19/07, Gabriel Genellina wrote: > En Mon, 19 Feb 2007 21:50:11 -0300, GiBo escribi?: > > > Grant Edwards wrote: > >> On 2007-02-19, GiBo wrote: > >>> > >>> Classic situation - I have to process an input stream of unknown length > >>> until a I reach its end (EOF, End Of File). How do I check for EOF? The > >>> input stream can be anything from opened file through sys.stdin to a > >>> network socket. And it's binary and potentially huge (gigabytes), thus > >>> "for line in stream.readlines()" isn't really a way to go. > >>> > >>> For now I have roughly: > >>> > >>> stream = sys.stdin > >>> while True: > >>> data = stream.read(1024) > >> if len(data) == 0: > >> break #EOF > >>> process_data(data) > > > > Right, not a big difference though. Isn't there a cleaner / more > > intuitive way? Like using some wrapper objects around the streams or > > something? > > Read the documentation... For a true file object: > read([size]) ... An empty string is returned when EOF is encountered > immediately. > All the other "file-like" objects (like StringIO, socket.makefile, etc) > maintain this behavior. > So this is the way to check for EOF. If you don't like how it was spelled, > try this: > > if data=="": break > > If your data is made of lines of text, you can use the file as its own > iterator, yielding lines: > > for line in stream: > process_line(line) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > Not to beat a dead horse, but I often do this: data = f.read(bufsize): while data: # ... process data. data = f.read(bufsize) -The only annoying bit it the duplicated line. I find I often follow this pattern, and I realize python doesn't plan to have any sort of do-while construct, but even still I prefer this idiom. What's the concensus here? What about creating a standard binary-file iterator: def blocks_of(infile, bufsize = 1024): data = infile.read(bufsize) if data: yield data -the use would look like this: for block in blocks_of(myfile, bufsize = 2**16): process_data(block) # len(block) <= bufsize... From hg at nospam.org Mon Feb 5 05:02:50 2007 From: hg at nospam.org (hg) Date: Mon, 05 Feb 2007 11:02:50 +0100 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> Message-ID: <_qJxh.168051$jb3.61861@newsfe18.lga> Bjoern Schliessmann wrote: > Gosi wrote: > >> J is in many ways similar to Python. > > The only one I see at the moment is that they're both some kind of > programming languages. > >> J has very many advanced operations. > > Sure. > > Mh, just looking at some "advanced" J source taken from > wikipedia.org makes me feel sick: > > | Here's a J program to calculate the average of a list of numbers: > | avg=: +/ % # > | avg 1 2 3 4 > | 2.5 > > In the meantime, do you now have an answer to why we should care? > > Regards, > > > Bj?rn > > -- > BOFH excuse #314: > > You need to upgrade your VESA local bus to a MasterCard local bus. Be nice ! From google at orcon.net.nz Sat Feb 17 20:19:06 2007 From: google at orcon.net.nz (google at orcon.net.nz) Date: 17 Feb 2007 17:19:06 -0800 Subject: How do I save the contents of a text buffer In-Reply-To: References: <1171756040.841140.254230@t69g2000cwt.googlegroups.com> Message-ID: <1171761546.906729.95680@j27g2000cwj.googlegroups.com> On Feb 18, 1:14 pm, Steven D'Aprano wrote: > On Sat, 17 Feb 2007 15:47:20 -0800, google wrote: > > As a test, I tried to write the buffer back to a file with this code > > but did not work, > > Oooh, guessing games! I love guessing games! Good > Let me see... did it reboot your PC? No > Did Python crash? No - it runs on nix > Did you get an exception? Maybe something about not being able to open > the file for reading? Or perhaps disk full? File read ok for input, its the file write thats the problem > Did you get something unexpected in the file? Maybe an empty file? Yes, a rabbit popped out of the floppy slot - amazing! > I'm guessing... it erased your hard disk. Do I win? Sorry, you lose....are you a Windows user? > -- > Steven. From rdm at rcblue.com Mon Feb 12 09:13:22 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 12 Feb 2007 06:13:22 -0800 Subject: favourite editor In-Reply-To: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> References: <1171168901.630813.39270@v45g2000cwv.googlegroups.com> Message-ID: <20070212141326.C84381E4006@bag.python.org> At 08:41 PM 2/10/2007, azrael wrote: >Since i'm new on this forum, and first time meeting a python comunity, >i wanted to ask you for your python editors. > >Im looking for some good python editor, with integrated run function, >without having to set it up manualy like komodo. >I found the pyscripter, and it has all i need, but it's unsatble. >bloated. it crashes when i close an yplication window run by python >from pyscripter. please. tell me a good one with buil in run (<-very >important) and nice gui. if possible to suport projects, code >highlighting, code completition, class browser, python comand line >(>>>), traceback. UliPad. Dick Moores From xml0x1a at yahoo.com Mon Feb 19 22:52:43 2007 From: xml0x1a at yahoo.com (xml0x1a at yahoo.com) Date: 19 Feb 2007 19:52:43 -0800 Subject: exec "def.." in globals(), locals() does not work Message-ID: <1171943563.164204.313540@p10g2000cwp.googlegroups.com> How do I use exec? >python -V Python 2.4.3 ---- from math import * G = 1 def d(): L = 1 exec "def f(x): return L + log(G) " in globals(), locals() f(1) ---- How do I use exec() such that: 1. A function defined in exec is available to the local scope (after exec returns) 2. The defined function f has access to globals (G and log(x) from math) 3. The defined function f has access to locals (L) So far I have only been able to get 2 out of the 3 requirements. It seems that exec "..." in locals(), globals() only uses the first listed scope. Bottomline: exec "..." in globals(), locals(), gets me 1. and 3. exec "..." in locals(), globals() gets me 1. and 2. exec "..." in hand-merged copy of the globals and locals dictionaries gets me 2. and 3. How do I get 1. 2. and 3.? Thanks in advance From paul at boddie.org.uk Sat Feb 17 18:00:19 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 17 Feb 2007 15:00:19 -0800 Subject: Complex HTML forms In-Reply-To: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> References: <1171751411.443886.300200@a75g2000cwd.googlegroups.com> Message-ID: <1171753219.350198.145300@v33g2000cwv.googlegroups.com> George Sakkis wrote: > When the form is submitted, the selected options are passed in the server in some form > that preserves the hierarchy, i.e. not as a flat dict. Is there anything close to such a beast around ? Yes, I have a framework called XSLForms which generates hierarchical field names when rendering XML documents using XSL-based templates; these field names are then interpreted in order to build XML documents based on the encoded hierarchy information. When these activities are successfully combined, the outcome is some kind of serialisation of XML data in Web forms. Take a look at the XSLTools distribution (which contains XSLForms): http://www.python.org/pypi/XSLTools Using the framework is not as easy as I'd like it to be, but there are a few examples (as well as the code, of course) and that should give you some ideas. Paul From gagsl-py at yahoo.com.ar Wed Feb 14 00:42:08 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Feb 2007 02:42:08 -0300 Subject: calling php function from python References: Message-ID: En Tue, 13 Feb 2007 23:52:37 -0300, mark escribi?: > is it possible to call a php function from python and use a class from > php in python? i want to use mmslib which creates mms messages and the > only implementation is a php mmslib implementation. > thanks a lot! > mark I don't think so... But you could try to convert the php code into Python. Or write your own MM7 implementation and be the first one, I presume. -- Gabriel Genellina From mblume at socha.net Mon Feb 19 15:22:56 2007 From: mblume at socha.net (Martin Blume) Date: Mon, 19 Feb 2007 21:22:56 +0100 Subject: How to call a function defined in another py file References: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> Message-ID: <45da0720$0$3822$5402220f@news.sunrise.ch> schrieb > > I have a function called 'test' defined in A.py. > How can I call that function test in my another file B.py? > In B.py: import A A.test() HTH Martin From bignose+hates-spam at benfinney.id.au Fri Feb 2 01:47:11 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Feb 2007 17:47:11 +1100 Subject: Overloading the tilde operator? References: Message-ID: <873b5pukcw.fsf@benfinney.id.au> James Stroud writes: > Ben Finney wrote: > > The Python runtime parser is designed to parse Python, not some > > arbitrary language that someone chooses to implement in Python. > > You haven't addressed why the limitation isn't arbitrary. Good thing I wasn't trying to do that, then. I was pointing out the source of the limitation. The Python syntax parser must follow the rules of the Python language. If you accept that premise, it follows that the '~' operator is unary only. If you *don't* accept that premise, I have no help to offer. -- \ "I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ..." -- F. H. Wales, | _o__) 1936 | Ben Finney From riko at despammed.com Thu Feb 8 19:51:13 2007 From: riko at despammed.com (Enrico 'Mc Osten' Franchi) Date: Fri, 9 Feb 2007 01:51:13 +0100 Subject: Best Free and Open Source Python IDE References: <1170936212.884191.14460@h3g2000cwc.googlegroups.com> Message-ID: <1ht8vdu.kq6a9wmshtd2N%riko@despammed.com> Srikanth wrote: > All I need is a good IDE, I can't find something like Eclipse (JDT). > Eclipse has a Python IDE plug-in but it's not that great. Have you tried the 'full' plugin (you have to pay about 30 $ IIRC or something like that)? My favourite Python editor is TextMate a shareware (39 $) editor for the MacOS. Before that I used gvim and then for a short time Emacs. In my opinion an IDE is not necessary in Python. However, this may be dependent from the way I work. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Feb 16 14:54:42 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 16 Feb 2007 20:54:42 +0100 Subject: why I don't like range/xrange References: <1171639815.098304.319760@v33g2000cwv.googlegroups.com> <53m8p8F1sf1i1U1@mid.individual.net> Message-ID: <53mgg2F1t135eU1@mid.individual.net> Eduardo "EdCrypt" O. Padoan wrote: >> But this long int => int issue should not exist in a future >> python version any more, IIRC int and long int is scheduled to be >> merged somehow. (Or isn't it?) > > It is done. Thanks for the info. Please don't send mail copies! Regards, Bj?rn -- BOFH excuse #217: The MGs ran out of gas. From vatamane at gmail.com Tue Feb 6 07:25:55 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 6 Feb 2007 04:25:55 -0800 Subject: Repr or Str ? In-Reply-To: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> References: <1170758827.396931.80680@m58g2000cwm.googlegroups.com> Message-ID: <1170764755.779167.51600@p10g2000cwp.googlegroups.com> On Feb 6, 5:47 am, "Johny" wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences > Thanks > LL When you want to provide a representation of an object from which you can create another object if you had to. Use 'str' if you just want to print it nicely. From fuzzyman at gmail.com Tue Feb 20 14:11:05 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Feb 2007 11:11:05 -0800 Subject: PLY for standard library In-Reply-To: References: Message-ID: <1171998665.552523.5480@t69g2000cwt.googlegroups.com> On Feb 20, 6:29 pm, "Alan Isaac" wrote: > Is PLY destined for the standard library? I've never heard it suggested... but +1 Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > If not, what module providing substantially similar functionality is? > > Thank you, > Alan Isaac From nszabolcs at gmail.com Fri Feb 9 16:47:53 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 9 Feb 2007 13:47:53 -0800 Subject: python linux distro In-Reply-To: References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> <1170955617.478249.82460@m58g2000cwm.googlegroups.com> Message-ID: <1171057671.866940.269130@v33g2000cwv.googlegroups.com> > Now what would be interesting (and *really* crazy) would be Linux (or > BSD or whatever) distro written almost entirely *in* Python, with the > goal of eliminating as much bash/sh as possible. > > That would be fun. actually there was(is) an os whitch is written "almost entirely *in* Python": http://en.wikipedia.org/wiki/Unununium_(operating_system) (their main site http://unununium.org seems to be down) From horpner at yahoo.com Mon Feb 12 10:06:50 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 12 Feb 2007 16:06:50 +0100 Subject: Regular Expressions References: Message-ID: On 2007-02-10, Geoff Hill wrote: > What's the way to go about learning Python's regular > expressions? I feel like such an idiot - being so strong in a > programming language but knowing nothing about RE. A great way to learn regular expressions is to implement them. -- Neil Cerutti From bdesth.quelquechose at free.quelquepart.fr Sat Feb 17 13:38:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 17 Feb 2007 19:38:06 +0100 Subject: Help Required for Choosing Programming Language In-Reply-To: References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <14ee8$45d625cb$d443bb3a$3016@news.speedlinq.nl> <45d626f5$0$19811$426a74cc@news.free.fr> Message-ID: <45d74420$0$30359$426a74cc@news.free.fr> Stef Mientki a ?crit : > Bruno Desthuilliers wrote: > >> Stef Mientki a ?crit : >> >>> ifti_crazy at yahoo.com wrote: >>> >>>> I am VB6 programmer and wants to start new programming language but i >>>> am unable to deciced. >>>> >>>> i have read about Python, Ruby and Visual C++. but i want to go >>>> through with GUI based programming language like VB.net >>>> >>>> so will you please guide me which GUI based language has worth with >>>> complete OOPS Characteristics >>> >>> >>> Although the GUI of Python is not as good as VB, >> >> >> "the GUI of Python" ? What's that ? Python is a *programming >> language*, not a GUI toolkit. > > The final goal of programming language is (in most cases) > meant to create functional things, > that can assist people to perform their tasks. > The UI of that resulting thing should be optimal adapted to the final > audience (and task). > My audience is most comfortable with a intuitive GUI. > In most of my applications, > I need about 50% of the time for the GUI and 50% for the other > functional code. > These estimates are for Delphi (is about identical as VB, which I used > previous). Stef, I come from the Mac world, at a time where Windows didn't even exist. I learned programming on a Mac (by the System7 days), then, a few years later, became a professional Windows programmer - using VB, VisualC++, etc. My first steps with Python were about GUI apps on Windows. I've switched to Linux and web programming since, but I do know what Windows GUI programming with Python is. > For what I've seen until now from Python, > - designing the GUI will cost me about 2 .. 3 times as much in Python Bullshit. You don't design the GUI with Python, but with one of the GUI designers coming with your GUI toolkit (that's, mostly, wxGlade for wxWidgets, Glade for GTK, and QTDesigner for QT). All these tools have all the needed features. > - Python is not capable of doing everything I need > (almost all interactive actions are very primitive and crashes a lot) I've shipped some wxPython apps, and tehy were usually more stable than the VB ones. > - designing my other functional code in Python, > will reduce the development time with an estimated factor of 2 > So the combination of Delphi (or VB) and Python seems the optimal > combination for heavily GUI's. My experience is that you *dont* need Delphi nor VB at all. > - one of the big problems with Python is the version differences > (compatibility) By itself, Python is very carefully designed for backward compat - you'll find that much of the code written by the 1.5.2 days still work as is. True, there are some compat requirements wrt/ which version of wxPython works with which versions of wxWidgets and Python, but nothing unusual here. > Bruno, I think we've a different audience / target application, > and at the moment we'll never agree about GUI, cf above. When I was writing Windows GUI apps, my target audience was mostly people knowing how to use a professional app on Windows. Now I'm doing web apps, and my target audience may include my own mother - which is not specially computer savy (even MacOS is too complex for her...). From http Thu Feb 22 05:27:21 2007 From: http (Paul Rubin) Date: 22 Feb 2007 02:27:21 -0800 Subject: Finding a tuple in a tuple References: <1172134769.567746.18100@l53g2000cwa.googlegroups.com> <7xd5427ebd.fsf@ruckus.brouhaha.com> <1172138143.526067.208750@k78g2000cwa.googlegroups.com> Message-ID: <7x1wki7aie.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > A step further: use union to make a superset of t2-tN, then use & on > this superset. > > setlist = [t2,t3,t4,t5] > superset = reduce(set.union, map(set,setlist) ) > print bool(t1 & superset) Well you do have to convert them to sets. Also I thought each intersection was wanted separately. Otherwise if we're getting this fancy, I guess I'd use (untested, uses new 2.5 "any" function): s1 = set(t1) print any((s1 & set(tn)) for tn in (t2,t3,t4,t5)) which avoids creating a potentially big intermediate set, and which short-circuits (exits early) as soon as a match is found. From mail at microcorp.co.za Wed Feb 28 01:16:41 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 28 Feb 2007 08:16:41 +0200 Subject: Running Python scripts from BASH References: <1172616940.127300.54090@v33g2000cwv.googlegroups.com> Message-ID: <000201c75b2f$3e380e00$03000080@hendrik> "Ishpeck" wrote: 8<--------------- a bash problem --------------------- If it were Python, the advice would have been to use the print statement to figure out what the content of the variables were. As it is Bash, you may have to stoop to something like echo to see what is in $i... hth - Hendrik From robin at reportlab.com Mon Feb 12 08:03:18 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 12 Feb 2007 13:03:18 +0000 Subject: Formatting milliseconds to certain String In-Reply-To: References: Message-ID: <45D06596.2060808@chamonix.reportlab.co.uk> Deniz Dogan wrote: > Hello. > I need help with a small problem I'm having. > > I want to make a function which takes an integer representing some time > in milliseconds and returns the same time but formatted as > "hours:minutes:seconds,milliseconds" with leading zeros whenever possible. > > E.g. I input 185804 to the function and it returns 00:03:05,804. The > function I'm using now is defined as: ....... > > Note that I am very new to Python and the language I have been using > most prior to this is Java. > > --Deniz Dogan how about >>> def millis2str(millis): ... hours, x = divmod(int(millis),3600000) ... mins, x = divmod(x,60000) ... secs, x = divmod(x,1000) ... s = '%02d:%02d:%02d' % (hours, mins,secs) ... if x: s += ',%03d' % x ... return s ... >>> millis2str(185804) '00:03:05,804' >>> -- Robin Becker From bearophileHUGS at lycos.com Mon Feb 12 02:03:30 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Feb 2007 23:03:30 -0800 Subject: searching a list of lists as a two-dimensional array? In-Reply-To: References: <1171240042.434902.154730@l53g2000cwa.googlegroups.com> Message-ID: <1171263810.438847.4860@a75g2000cwd.googlegroups.com> James Stroud: > import operator > srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)] > is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]]) Or maybe (untested), Python V.2.5: srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)] is_adj = any(ary[row+i][col+j] for (i,j) in srch) Or: is_adj = any(ary[row+i][col+j] for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)) Bye, bearophile From __peter__ at web.de Fri Feb 2 03:10:43 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Feb 2007 09:10:43 +0100 Subject: A* search implementation in Python References: <1170382917.837428.247930@s48g2000cws.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Thu, 01 Feb 2007 18:21:57 -0800, bearophileHUGS wrote: > >> Reid Priedhorsky: >>> I'm looking for an open-source Python implementation of A* search for >>> use in a mapping application. >> >> You can try this one: >> http://aima.cs.berkeley.edu/python/search.html > > To paraphrase a wise saying: > > If you give a man a link, you satisfy his need for one day. > But if you teach a man to search, you satisfy his need forever. > > Given that Reid had problems formulating a good search (because * is an > operator in Google) what did you do? What he might have done: http://www.google.com/codesearch?hl=de&lr=&q=lang%3Apython+A%5B*%5D+search&btnG=Suche Peter From enleverlesX.XmcX at XmclaveauX.com Mon Feb 5 11:33:42 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 5 Feb 2007 17:33:42 +0100 Subject: Count nb call of a function, without global var or decorator References: <45c75b0f$0$5090$ba4acef3@news.orange.fr> Message-ID: <45c75c67$0$27378$ba4acef3@news.orange.fr> Re! I can do : def ff(): this=ff try: this.count=this.count+1 except: this.count=1 a=1 b=2 c=a+b ff() fa=ff ff() fa() print ff.count But that use, inside the function, the litteral name of the function; and I want no use litteral name (inside) @+ Michel Claveau From gosinn at gmail.com Thu Feb 8 12:55:31 2007 From: gosinn at gmail.com (Gosi) Date: 8 Feb 2007 09:55:31 -0800 Subject: Calling J from Python In-Reply-To: <1170936026.627390.212070@p10g2000cwp.googlegroups.com> References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <1170731096.976076.173270@h3g2000cwc.googlegroups.com> <1170749117.582426.151770@p10g2000cwp.googlegroups.com> <1170936026.627390.212070@p10g2000cwp.googlegroups.com> Message-ID: <1170957331.569557.323030@q2g2000cwa.googlegroups.com> On Feb 8, 12:00 pm, "Eric_Dex... at msn.com" wrote: > I may have mistook the source code licence for the use licence.. I > will look into a little further to see what it can do.. Looks like > you are not allowed to redistribute k for profit. Some day I will > look up letters a random in the search engine to see what I come up > with. > > On Feb 6, 2:05 am, "Gosi" wrote: > > > On Feb 6, 3:04 am, "Eric_Dex... at msn.com" wrote: > > > > On Feb 5, 8:48 am, "Gosi" wrote: > > > > > It is quite easy to call J from Python > > > > >http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... > > > > There are a couple of issue that should be adressed. Am I going to > > > jail if I write a program and then redistribute all the files required > > > to run the program I write?? > > > J is free for anyone to download and use. > > > If someone is interested in putting you in jail it will not because > > you distribute J or redistribute the J utilities. > > > > The second is how do I use the j stuff > > > without learning all that much about j. > > > Just like Python then how much time you spend is uo to you. > > > If you want to be good at it you may have to spend some time. > > > You may also be just a casual user and dip into it now and again. > > > There are lots of Demos, Labs and Help files besides all the > > utilities. > > > You can freely use the utilities and examples to create your own > > application. > > > You can write code in conventional style and not spend any time on the > > advanced functionality. > > > > I am just intrested in > > > stealing graphics libraries and using what I have already written in > > > python.. > > > There are a number of graphics examples, utilities and demos you can > > use in J and combine it with Python. > > > The new grid classes in J are amazingly useful too. > > > I am just starting to learn Python and I find it interesting to > > combine it with J. > > I know a few people who are doing so successfully. > > > There are always some nicetise in any language that can be beneficial. > > Combining them enhances both. > > >http://groups.google.com/group/j-programminghttp://jsoftware.com/ You can get older versions of the source code too for free. The utility sources are also free. From pydecker at gmail.com Mon Feb 19 13:14:51 2007 From: pydecker at gmail.com (Peter Decker) Date: Mon, 19 Feb 2007 13:14:51 -0500 Subject: Help Required for Choosing Programming Language In-Reply-To: <1171907766.635204.161240@h3g2000cwc.googlegroups.com> References: <1171660934.267466.75250@l53g2000cwa.googlegroups.com> <1171907766.635204.161240@h3g2000cwc.googlegroups.com> Message-ID: On 19 Feb 2007 09:56:06 -0800, Mark Morss wrote: > Good grief. I suppose it is Microsoft to whom we owe the idea that > there could be such a thing as a "GUI based" programming language. Who do we blame for the idea that everyone in the world should be able to express themselves in perfect English without confusion? It was obvious what the OP meant. He's looking for something akin to VB, but in Python. -- # p.d. From larry.bates at websafe.com Wed Feb 14 12:43:58 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 14 Feb 2007 11:43:58 -0600 Subject: list of range of floats In-Reply-To: References: Message-ID: Steve wrote: > I'm trying to create a list range of floats and running into problems. > I've been trying something like: > > a = 0.0 > b = 10.0 > > flts = range(a, b) > > fltlst.append(flts) > > When I run it I get the following DeprecationWarning: integer argument > expected, got float. How can I store a list of floats? > > TIA > Steve > What does range of floats mean? How many floats are there between 0.0 and 10.0? If you want the step to be 1.0 and beginning and ending values will be whole numbers then this will work: flts=[float(i) for i in range(1, 11)] If you want arbitrary starting and ending floats and an arbitrary step, you will need to write your own function. -Larry From exarkun at divmod.com Thu Feb 8 10:06:32 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 8 Feb 2007 10:06:32 -0500 Subject: help on packet format for tcp/ip programming In-Reply-To: <530s0uF1q8kfsU1@mid.uni-berlin.de> Message-ID: <20070208150632.25807.507531114.divmod.quotient.14567@ohm> On Thu, 08 Feb 2007 15:56:30 +0100, "Diez B. Roggisch" wrote: >rattan at cps.cmich.edu wrote: > >> On Feb 8, 3:40 am, Grant Edwards wrote: >>> On 2007-02-08, rat... at cps.cmich.edu wrote: >>> >>> > struct module pack and unpack will only work for fixed size buffer : >>> > pack('>1024sIL', buffer, count. offset) but the buffer size can vary >>> > from one packet to the next :-( >>> >>> Oh for Pete's sake... >>> >>> struct.pack('>%dsIL' % len(buffer), buffer, count, offset) >>> >>> -- >>> Grant Edwards grante Yow! I want the >>> presidency >>> at so bad I can already >>> taste >>> visi.com the hors d'oeuvres. >> >> that is great but how does one unpack on the other side? > >By peeking into the header, determining the number of bytes necessary? > >But why do you need this anyway - if you know that you will have python on >both ends, use Pyro or xmlrpc. > Grant had the right idea, I think, but he failed to actually include a byte length in his format. :) So there's nothing to peek at. If the packing is done like this, instead.. struct.pack('!IIL', len(buffer), count, offset) + buffer Then it is a simple matter to unpack it once the receiving side, by waiting for struct.calcsize('!IIL') bytes, using struct to get len(buffer), count, and offset: length, count, offset = struct.unpack('!IIL', bytes) And then waiting for `length' more bytes, which will be the buffer. I'm not sure what the original use-case was here. XML-RPC isn't a good transport for arbitrary binary data. If `buffer' contains text, though, that might be a good suggestion. Jean-Paul From etatoby at gmail.com Sun Feb 25 07:19:12 2007 From: etatoby at gmail.com (Toby) Date: 25 Feb 2007 12:19:12 GMT Subject: How to build Hierarchies of dict's? (Prototypes in Python?) References: <45e06bab$0$20809$5fc30a8@news.tiscali.it> Message-ID: <45e17ec0$0$20813$5fc30a8@news.tiscali.it> Charles D Hixson wrote: > a class whose sub-classes automatically have unique class variables of > a determined form such that I can do a hierarchical search through them Something like this? (scroll down to see the results) # --- begin --- class AttrSearch(object): @classmethod def getclassattrset(cls, name): s = set() if name in cls.__dict__: s.add((cls.__name__, cls.__dict__[name])) for base in cls.__bases__: try: s.update(base.getclassattrset(name)) except AttributeError: pass return s def getattrset(self, name): s = set() try: s.add((None, self.__dict__[name])) except KeyError: pass s.update(self.__class__.getclassattrset(name)) return s def __getattribute__(self, name): if name.startswith('__'): #XXX not pretty return object.__getattribute__(self, name) found = AttrSearch.getattrset(self, name) print 'Looking for "%s" in a %s instance, found %d candidates:' \ % (name, self.__class__.__name__, len(found)) print '\n'.join([ ' %-4s %s' % x for x in found ]) print '(now choose wisely what to return)' class A(AttrSearch): a = 1 class B(A): a = 2 class C(A): a = 3 class D(B, C): a = 4 D().a # --- end --- Results: Looking for "a" in a D instance, found 4 candidates: A 1 B 2 C 3 D 4 (now choose wisely what to return) Toby From horpner at yahoo.com Tue Feb 27 11:29:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 27 Feb 2007 17:29:26 +0100 Subject: Lists: Converting Double to Single References: <%6QEh.6362$_73.1862@newsread2.news.pas.earthlink.net> Message-ID: On 2007-02-27, Steven D'Aprano wrote: > On Tue, 27 Feb 2007 10:06:29 +0000, Duncan Booth wrote: >> Adding up a long list of values and then dividing by the >> number of values is the classic computer science example of >> how to get an inaccurate answer from a floating point >> calculation. > > I'm not entirely ignorant when it comes to computational > mathematics, but I must admit this is a new one to me. > > If the values vary greatly in magnitude, you probably want to add them > from smallest to biggest; other than that, how else can you calculate the > mean? > > The only alternative I thought of was to divide each value by the count > before summing, but that would be horribly inaccurate. > > Or would it? > >>>> def mean1(*args): > ... return sum(args)/len(args) > ... >>>> def mean2(*args): > ... n = len(args) > ... return sum([x/n for x in args]) > ... >>>> L = range(25, 597) # 572 values >>>> L = [x/3.3 for x in L] >>>> >>>> mean1(*L) > 94.090909090909108 >>>> mean2(*L) > 94.090909090909108 > > The first calculation has 571 additions and one division; the > second calculation has 571 additions and 572 divisions, but > they both give the same result to 15 decimal places. How about this? >>> L = range(5, 10) >>> L = [pow(2, -x) for x in L] >>> "%40.40f" % mean1(*L) '0.0121093750000000000000000000000000000000' >>> "%40.40f" % mean2(*L) '0.0121093750000000020000000000000000000000' Offhand, I think the first is "righter". Weird! -- Neil Cerutti From troy.melhase at gmail.com Wed Feb 28 04:33:21 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Wed, 28 Feb 2007 00:33:21 -0900 Subject: Installing java2python (Newbie) In-Reply-To: <1172654566.960775.66080@j27g2000cwj.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> <1172654566.960775.66080@j27g2000cwj.googlegroups.com> Message-ID: > Hi Troy, Windows users don't really "want" to do that. They'd prefer > to download a Windows installer, and "double-click on it". Hi John, Understood and agreed. I was thinking about Andy's problem, and I realized that many users would benefit from a gui to do side-by-side translation. If I ever have the time, I could write one I think. > This might save some wear'n'tear on their nervous systems, and > yours :-) Like so many projects, it works for me the way it is -- I'm driving j2py via makefiles, and a gui just isn't something I need. But of course patches are welcome -- even gui ones! From kevinliu23 at gmail.com Wed Feb 28 16:24:11 2007 From: kevinliu23 at gmail.com (kevinliu23) Date: 28 Feb 2007 13:24:11 -0800 Subject: How to check for remaining hard drive space in Windows? In-Reply-To: References: <1172694391.256770.234450@j27g2000cwj.googlegroups.com> <2adc542f0702281259q3ab2ac1dr8e76e6157f96537b@mail.gmail.com> Message-ID: <1172697850.946627.196420@a75g2000cwd.googlegroups.com> Thanks so much for the help guys. I got the code Sick Monkey provided to work on my computer. Now I"m more confused than ever though. :) I thought the only standard modules provided by Python are listed here: http://docs.python.org/modindex.html But it appears that there are other modules available to me without having to download third party code. Could someone point me to the documentation of these other modules such as win32com.client? Thanks everyone for your help. :) Also, how could I get the computer name? I would be running this code on another machine and don't want to change the computer name in the code every time I port it to another computer. Thanks! Kevin On Feb 28, 4:16 pm, Tim Golden wrote: > [... re getting free disk space ...] > > Sick Monkey wrote: > > Here you are: > > > >>> from win32com.client import GetObject > >>>> wmiObj = GetObject("winmgmts:\\\\MGW01641\\root\\cimv2") > >>>> diskinfo = wmiObj.ExecQuery("Select * from Win32_LogicalDisk") > >>>> for disk in diskinfo: > > ... print disk.Name, disk.FreeSpace > > ... > > A: None > > C: 16978259968 > > D: None > > Well it's not often someone beats me to a WMI > solution :) Just to be different, you can also > look at the GetDiskFreeSpace function in the > win32api module of the pywin32 extensions. > > The doc says: """ > tuple = GetDiskFreeSpace(rootPath) > > Retrieves information about the specified disk, including the amount of > free space available. > > Parameters > > rootPath : string > > Specifies the root directory of the disk to return information about. If > rootPath is None, the method uses the root of the current directory. > > Win32 API References > > Search for GetDiskFreeSpace at msdn, google or google groups. > > Return Value > The return value is a tuple of 4 integers, containing the number of > sectors per cluster, the number of bytes per sector, the total number of > free clusters on the disk and the total number of clusters on the disk. > If the function fails, an error is returned. > """ > > TJG From sturlamolden at yahoo.no Wed Feb 7 15:08:14 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 7 Feb 2007 12:08:14 -0800 Subject: multithreading concept In-Reply-To: References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> <1170872694.018720.301410@m58g2000cwm.googlegroups.com> Message-ID: <1170878893.963014.315070@q2g2000cwa.googlegroups.com> On Feb 7, 8:03 pm, Sergei Organov wrote: > I fail to see how threads in general could perform worse than > processes. I do understand that processes are inherently more > safe/secure, but when it comes to speed I really can't imagine why it > could happen that threads perform worse (poor threads implementation and > programming practices aside). Care to give some references? I believe Nick Maclaren explained that to you (and me) on January 10 and 11 this group. As far as I have understood the issue, it has to do with poor threads implementations. Look that up on Google groups and re-read the discussion (or ask Nick Maclaren as he is far more competent than me). http://groups.google.com/group/comp.lang.python/browse_frm/thread/332083cdc8bc44b From http Sat Feb 3 10:52:55 2007 From: http (Paul Rubin) Date: 03 Feb 2007 07:52:55 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xhcu3hk7i.fsf@ruckus.brouhaha.com> Message-ID: <7xodob2q7c.fsf@ruckus.brouhaha.com> Ben Finney writes: > > Since Python is being touted as good for web apps as a competitor to > > PHP > > Python is being touted as a good language for *many* purposes, not > just web applications. Python is also a "competitor" to Java, to Ruby, > to Perl, to many other languages. They all have strengths and > weaknesses. Yes but in the cases where Python's weakness compared with one of those other languages is lack of library functionality, if Python can remedy the weakness by incorporating similar functionality into its library it should do so. > That doesn't follow at all. Many consider the humungous function > library of PHP to be a significant downside of the system, which > criterion leaves Python ahead. More is not necessarily better. I've never heard that as a PHP criticism, at least in any large scale deployment, which is what a hosting service is. > > I'm paying the hosting company for access to a computer that's > > connected to electricity and to the internet and which has a > > straightforward OS, language package, web server, and db installed. > > In which case, there should be no problem with *you* installing > whatever software you need to use the system for what you want. No. That would be colo or something similar , where I'm basically paying for bare metal plus electricity and network, and I'm completely in charge of the software. Web hosting means the ISP is in charge of all the software except for my application (i.e. they handle the OS, language package, web server, and db, as described above). So they run (typically) Linux, MySQL, Apache, and PHP; and I get to upload my own PHP apps and use the PHP library. That's a lot less work for me since I don't have to stay on top of kernel patches or firewall configuration, and it's cheaper because they host a bazillion sites (virtual hosts) in a a single server instance. > > They shouldn't have to deal with dozens of interdependent modules > > downloaded from different places just to support one language. > > Either they are providing far more than the minimal set you describe > above, or this is entirely outside their domain. Make up your mind. No it's you who's got it wrong, I just described above what they're doing. Do you actually use any services like this? > You can't claim both that the hosting company should have to maintain > a comprehensive set of functionality, *and* that they should not have to. They should get a distro that includes a lot of stuff, type "make", and all the stuff becomes available to their users. From jstroud at mbi.ucla.edu Wed Feb 14 19:35:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 14 Feb 2007 16:35:48 -0800 Subject: anyway to create a table-like object? In-Reply-To: References: Message-ID: James Stroud wrote: > Wensui Liu wrote: > >> Dear all, >> >> is there a way to create a 2-dimension-table-like object such that I >> can reference a whole column directly using something like : >> mytable.column1 ? >> >> by the way, can python be used for database programming to pull large >> volume data (hundred M or even several Gs) out of large database and >> do data manipulation and reporting ? if yes, how is the speed and >> efficiency ? >> >> thanks. >> >> wensui > > > I have a table class that works like this: > > atable['some_col'] ==> list of values > atable[some_row_index] ==> list of values > atable[slice_start:slice_end] ==> new table > atable[('some_col', 'other_col', 'another_col')] ==> 3 col. table > atable['some_col', some_row_index] ==> one value > atable['some_col', slice_start:slice_end] ==> list of values > atable[('some_col', 'other_col'), some_row_index] ==> list of 2 vals > atable[('some_col', 'other_col'), slice_start:end]) ==> 2 col. table > > As you can see, it has a lot of flexibility, but may not be the ultimate > in terms of speed (and purists may not like the way __getitem__ returns > data based on context). It is for people who care about convenience over > speed and do not adhere to some puritanical ideal about how __getitem__ > should work. There is little typechecking (in accord with my own brand > of puritanical philosophy), so be careful if you have ints as column > headers. The datastructure is implemented as a list of lists (by row) > and the "keys" (column headings) are a list. So size limitations are > limited by memory. Theoretically, the __getitem__ (where all the work > and decisions are done) could be factored out and wrapped around dbi for > hard-core database usage. This might entail some serious creativity. > > It also has some other features, such as returning matches, etc. It is > not intended, at all, to rival an actual database such as mysql--the > model is more based on how Joe Users use excel files. > > If you are interested, I can send you the module. Beyond actual use in > my own and my wife's work, there has been little testing. > > James Also, if you want columns as attributes (which may be pretty cool): def __getattr__(self, att): if att in self.headers: return self[att] else: return self.__getattribute__(att) James From mike.klaas at gmail.com Mon Feb 12 17:07:47 2007 From: mike.klaas at gmail.com (Klaas) Date: 12 Feb 2007 14:07:47 -0800 Subject: huge amounts of pure Python code broken by Python 2.5? In-Reply-To: References: <1170988167.356729.187920@v33g2000cwv.googlegroups.com> <1170988670.576168.205640@v33g2000cwv.googlegroups.com> <1171060243.501374.249430@a75g2000cwd.googlegroups.com> Message-ID: <1171318067.395371.63050@p10g2000cwp.googlegroups.com> On Feb 10, 5:59 am, Brian Blais wrote: > Klaas wrote: > > I have converted our 100 kloc from 2.4 to 2.5. It was relatively > > painless, and 2.5 has features we couldn't live without. > > Just out of curiosity, what features in 2.5 can you not live without? I just > migrated to 2.5, but haven't had much time to check out the cool new features. Most important being the finalization of generators, which allowed me to implement remote-rpc-yield elegantly. It would have been possible to do this using iterator classes, I admit. with statements have also been a wonderful addition -- like decorators for code blocks! -Mike From tdelaney at avaya.com Tue Feb 20 17:16:46 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 21 Feb 2007 09:16:46 +1100 Subject: f---ing typechecking Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ECA8@au3010avexu1.global.avaya.com> Nick Craig-Wood wrote: > x += a > > does not equal > > x = x + a > > which it really should for all types of x and a Actually, this will *never* be the case for classes that do in-place augmented assignment. a = [1] b = [2] c = a + b print a, b, c a += b print a, b, c You'll note that I didn't rebind 'a' in the non-augmented assignment. If you do, augmented and non-augmented assignment may look the same, but they can be very different. Tim Delaney From worlman385 at yahoo.com Sat Feb 3 14:18:31 2007 From: worlman385 at yahoo.com (worlman385 at yahoo.com) Date: Sat, 03 Feb 2007 11:18:31 -0800 Subject: nokia pys60 contacts + calendar References: <1170499082.377190.25650@l53g2000cwa.googlegroups.com> Message-ID: On 3 Feb 2007 02:38:02 -0800, "cyberco" wrote: >You can most likely find an answer on Nokia's Python forum: >http://discussion.forum.nokia.com/forum/forumdisplay.php?f=102 > >And if there's no answer there you should post the question there :) cyberco, do you knwo the answer? thanks again From sjmachin at lexicon.net Wed Feb 28 04:22:47 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2007 01:22:47 -0800 Subject: Installing java2python (Newbie) In-Reply-To: <1172640476.259853.245530@8g2000cwh.googlegroups.com> References: <1172635476.227019.149350@m58g2000cwm.googlegroups.com> <1172637274.994742.173850@p10g2000cwp.googlegroups.com> <1172637721.119848.188380@a75g2000cwd.googlegroups.com> <1172640476.259853.245530@8g2000cwh.googlegroups.com> Message-ID: <1172654566.960775.66080@j27g2000cwj.googlegroups.com> On Feb 28, 4:27 pm, "troy.melh... at gmail.com" wrote: > > Hi Jeremy, that's the problem I'm having. Where should I type that " > > python setup.py install" ? Once again I'm using Windows system and not > > Unix. Should I move the file to a specific folder under Python 2.5 and > > then type " python setup.py install" in IDLE or Command Line window? > > I get the error "SyntaxError: invalid syntax" with the word "setup" > > hi andy, > > you want to run the windows command prompt, which is called "cmd.exe" > in windows xp. press the "start menu", then select "run", then type > "cmd.exe" without the quotes. > Hi Troy, Windows users don't really "want" to do that. They'd prefer to download a Windows installer, and "double-click on it". http://docs.python.org/dist/postinstallation-script.html This might save some wear'n'tear on their nervous systems, and yours :-) HTH, John From bjourne at gmail.com Tue Feb 20 19:41:01 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 21 Feb 2007 01:41:01 +0100 Subject: Python 3.0 unfit for serious work? In-Reply-To: <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> References: <5tGdnWXg-a5hpkjYnZ2dnUVZ_ragnZ2d@comcast.com> <1171990150.797668.19770@p10g2000cwp.googlegroups.com> <740c3aec0702201247u5b7203f8u2e171d8272289e0@mail.gmail.com> <820fa4350702201304m61c15318l113c2dd8eb97de91@mail.gmail.com> Message-ID: <740c3aec0702201641k88d6e1asc822276f4131b99b@mail.gmail.com> On 2/20/07, Jeff Templon wrote: > Bjorn, I am not sure I see why my post is bull crap. I think all you > are doing is agreeing with me. My post was entitled "Python 3.0 unfit > for serious work", you just indicated that the Linux distros will > agree with me, in order to be taken seriously, the distros will have > to include 2.x python for a very long time. If 3.0 and 2.x have any > serious degree of incompatibility, python will be a favorite subject > for religious rants and heated arguments for many people. And if we > don't manage to restrain our developers from using features that force > us prematurely to move to 3.0 ... and don't underestimate what this > means, because this means other things will have to move as well, > which may have dependencies on yet other things like C++ library > versions ... then I would have to, for reasons of maintainability, > argue against continuing to allow python code development in the > project. I love python, but not enough to make 20+ people's lives > difficult. > > There are already people making this sort of argument in our project. This is why I said that your post was a load of bull crap: "Then Python is pretty much determined to remove itself from consideration from various kinds of international projects like the one I work on [unless py3k is backwards compatible with python 2.x]." You did not explain why this is so. "if 2.4 code doesn't run on 3.0, it's rather likely that strong pressure will be applied to port *away* from Python into something less capricious." Who are these people that are applying the strong pressure? How can you run a international and seemingly very important project without knowing basic things about how to handle versioning problems? I mean, they would rather port this big system, deployed on thousands of computers all over the world, to an entirely different programming language than to continue using Python 2.x because Python 3.x, when it is released, MIGHT cause them some problems several YEARS from now? -- mvh Bj?rn From usable.thought at gmail.com Fri Feb 16 10:20:49 2007 From: usable.thought at gmail.com (Endless Story) Date: 16 Feb 2007 07:20:49 -0800 Subject: Command line prompt broken on XP with Python 2.5 - help! In-Reply-To: <1171637804.543331.314020@m58g2000cwm.googlegroups.com> References: <1171626740.495269.169020@m58g2000cwm.googlegroups.com> <1171637804.543331.314020@m58g2000cwm.googlegroups.com> Message-ID: <1171639249.324828.304940@t69g2000cwt.googlegroups.com> On Feb 16, 9:56 am, "Jim" wrote: > On Feb 16, 5:52 am, "Endless Story" wrote: > Are you talking about the Environment Variables-->System Variable-->path? > You may want to right click on My Computer-->System Properties-->Advanced--> > Environment Variables-->System variables-->Path-->Edit. > And check to see if it's there, if not then add it. I've already added the new python to my path in this fashion, but to no avail. Besides, if it were a path problem in the usual sense, the symptom would be a message at the command line saying that "python" is not recognized. Since I don't get this message, it's not a typical path problem. What it is, I don't know - that's my quandry. From bjourne at gmail.com Thu Feb 1 04:22:09 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 1 Feb 2007 10:22:09 +0100 Subject: division by 7 efficiently ??? In-Reply-To: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <740c3aec0702010122t7e14f01v9c0151b6ffbef74b@mail.gmail.com> This is maybe not so efficient :) but it implements integer division by 7 for positive integers without - and /. def div2(num): return num >> 1 def div4(num): return num >> 2 def div8(num): return num >> 3 def mul2(num): return num << 1 def mul4(num): return num << 2 def mul7(num): return mul4(num) + mul2(num) + num def div7_help(num, lo, hi): avg = div2(lo + hi) if avg == lo or avg == hi: if mul7(hi) == num: return hi return lo avg7 = mul7(avg) if avg7 > num: return div7_help(num, lo, avg) elif avg7 < num: return div7_help(num, avg, hi) return avg def div7(num): lo = div8(num) hi = div4(num) return div7_help(num, lo, hi) for nr in range(0, 20000): #print "%d // 7 = %d" % (nr, nr // 7) #print "div7(%d) = %d" % (nr, div7(nr)) assert nr // 7 == div7(nr) A somewhat better approach is to convert the recursion to an interative method. But that is.. um.. left as an exercise. -- mvh Bj?rn From orsenthil at gmail.com Wed Feb 28 04:23:02 2007 From: orsenthil at gmail.com (Phoe6) Date: 28 Feb 2007 01:23:02 -0800 Subject: using telnetlib Message-ID: <1172654582.919944.13530@k78g2000cwa.googlegroups.com> Hi All, I am trying to use the telnetlib module. Manually when I do telnet 172.31.128.244 I get: Login: (I type root) Password: ( I type Password) And it enters to the Telnet Session: [root]# Now, I am trying to use telnetlib module >>> import telnetlib >>> tn = telnetlib.Telnet("172.31.128.244") >>> tn.read_until("Login: ") '\r\nLogin: ' >>> tn.write("root\n:") >>>tn.read_until("Password: ") Cursor stays over here forever!. Delays are not working. I tried all the codes mentioned n c.l.p, but i have not yet been able to get telnetlib working. Any suggestions as how to troubleshoot and resolve this issue? Thanks, Senthil From steve at holdenweb.com Thu Feb 8 11:56:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Feb 2007 16:56:19 +0000 Subject: python linux distro In-Reply-To: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> Message-ID: azrael wrote: > Hy guys > > last night i was lying in my bed and thinking about something. is > there any linux distro that is primary oriented to python. you know > what i mean. no need for php, java, or something like this. pure > python and containig all the funky modules like scipy, numpy, > boaconstructor (wx of course). something like the python enthought > edition, but all this on a distro included. maybe psql but persistant > predered, zope of course. everything a developer is ever going to > need. > So i stood up, sat down on my ugly acer notebook with a python stiker > on it and made a huge list of cool modles i would prefer. I would like > to make such a distro but i am not a linux pro. so this is going to > stay just a idea. i thouht it should be realy user fredly like sabayon > or ubuntu (without xgel). if this were a live distro it would be > amazing. > I know, dont expet someone else to do your work, but is there anyone > who likes the idea and has the knowledge i dont have. > I also know for quantian (cool distro), but for me, there is too much > other crap and not enough python. > > i even got the nam of it. maybee not the best but it fits the context. > PyTux > Well, Ubuntu is normally held to be a pretty Python-friendly distro. But nowadays you might get more mileage out of distributing a Xen or VMWare virtual machine that has Python and all necessary packages installed with it. There is a fine example, the Python Web Developer Appliance, at http://www.mcguru.net/pyweb.html regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From jstroud at mbi.ucla.edu Fri Feb 9 18:50:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 09 Feb 2007 15:50:33 -0800 Subject: interacting with shell - another newbie question In-Reply-To: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> References: <1171054628.719353.149510@h3g2000cwc.googlegroups.com> Message-ID: James wrote: > Hello, > > I work in this annoying company where I have to autheticate myself to > the company firewall every 30-50 minutes in order to access the > internet. (I think it's a checkpoint fw). > > I have to run "telnet what.ever.ip.address 259" then it prompts me > with userid, then password, then I have to select "1". Then the > program closes itself and the internet is enabled. > > I would like to automate this process with Python and run it every 30 > miniutes so I don't have to keep typing in these userid/password > everytime. How can this be done? Is there a module I can use to > interact with the shell? (I'm running linux) > > Thank you. > > James > You should really randomize the timing somehow--and skip some intervals. You do not want some turd figuring out that you have scripted the process and ratting on you to the dorks who came up with this scheme. Maybe keep track of your manual activites for a while in terms of timing and then attempt to approximate what you find using the random module. James From silovana.vjeverica at com.gmail Sat Feb 3 11:30:47 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Sat, 3 Feb 2007 17:30:47 +0100 Subject: Jython References: <1170519648.346636.165190@m58g2000cwm.googlegroups.com> Message-ID: Boris Ozegovic wrote: > gregturn at mindspring.com wrote: > >> Files aren't lists and thus don't have the functions for iteration. > > They do have iterator: > > C:\Documents and Settings\Silovana Vjeverica\Desktop>python FileReader.py > 'import site' failed; use -v for traceback > boris ozegovic > vedran ozegovic But apparently not in Jython... Only Python. Tnx, anyway -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" From charleshixsn at earthlink.net Sat Feb 24 19:29:13 2007 From: charleshixsn at earthlink.net (Charles D Hixson) Date: Sat, 24 Feb 2007 16:29:13 -0800 Subject: How to build Hierarchies of dict's? (Prototypes in Python?) In-Reply-To: <45e06bab$0$20809$5fc30a8@news.tiscali.it> References: <45e06bab$0$20809$5fc30a8@news.tiscali.it> Message-ID: <45E0D859.1040109@earthlink.net> Toby wrote: > Charles D Hixson wrote: > >> What I basically want is a kind of class that has both class and >> instance level dict variables, such that descendant classes >> automatically create their own class and instance level dict variables. >> The idea is that if a member of this hierarchy looks up something in >> it's local dict, and doesn't find it, it then looks in the class dict, >> and if not there it looks in its ancestral dict's. This is rather like >> what Python does at compile time, but I want to do it at run time. >> > > I don't understand, Python already does it at runtime: > > class A: > A_class_var = 1 > > class B(A): > B_class_var = 2 > def __init__(self): > self.B_inst_var = 3 > > >>>> b.A_class_var >>>> > 1 > >>>> b.B_class_var >>>> > 2 > >>>> b.B_inst_var >>>> > 3 > >>>> A.another = 4 >>>> b.another >>>> > 4 > > Can you post a ">>>"-script of what you would like your classes to do? > > > Toby > Sorry, the "script" hasn't been written. But Python apparently *won't* (automatically) do what I want, which is create a class whose sub-classes automatically have unique class variables of a determined form such that I can do a hierarchical search through them. (I could plausibly handle this for the instance case but "class variables are static", so it looks like I can't do it for class variables in a straightforward manner. This looks like it's going to demand a factory method, or some alternate approach. (Not sure yet which I'll choose.) What I'm looking for is a reasonable way to implement what Marvin Minsky calls Panologies. These are "objects" (my term) with sufficient local intelligence to try alternative models of a situation until they find one that's appropriate. E.g., is this being operated on as a physical transaction or a social transaction. (Yes, it is physically happening, and it's taking place in physical space, but different models yield different analyses of what's happening. Which is appropriate for the situation currently being evaluated?) Well, I'm not trying to handle all that, merely to create a simple model of what a panology *IS*. So each Panology object will need a list of delegatees to handle the operations, and a list of indexes to assist it in evaluating which delegatee to use. If it doesn't find it locally, it will need to search through the situational context and these should be maintained at both the class and instance levels by it's ancestors. The base class should have a method that manages the searching, and the finding of delegatees (models) based around the indexing keys. This will take a bit of work, but if I can manage it, it should be rather interesting. It could also be used to test some of Minsky's ideas...or not, because what I'm thinking of it different from exactly what he's proposing. E.g., after I figure out how to build the basic structure, I'm going to need to figure out how to determine the appropriate model. This may be a harder problem. P.S.: What I really expect is that by the time I get this solved, somebody else will already have a solution. (It's happened before. I had the "idea" of an "intelligent spam filter" before spambayes was built...but I was much too slow at the implementation. MUCH! (I spend too much time dreaming and not enough time programming.) P.P.S.: This isn't all loss. I'm expecting that eventually I'll start running into performance problems, and at that point it would be necessary to start translating into a native-compiler language. From rupole at hotmail.com Fri Feb 9 07:18:16 2007 From: rupole at hotmail.com (Roger Upole) Date: Fri, 9 Feb 2007 07:18:16 -0500 Subject: Problem - Win32 Programming References: <1171016671.740414.30730@p10g2000cwp.googlegroups.com> Message-ID: <1171023678_11503@sp6iad.superfeed.net> wrote in message news:1171016671.740414.30730 at p10g2000cwp.googlegroups.com... > Hi .. > > I'm a newbie to python win32 programming. I was just reading Python > Programming on Win32 and I was trying to run this program: > > # SimpleCOMServer.py - A sample COM server - almost as small as they > come! > # > # We expose a single method in a Python COM object. > class PythonUtilities: > _public_methods_ = [ 'SplitString' ] > _reg_progid_ = "PythonDemos.Utilities" > # NEVER copy the following ID > # Use "print pythoncom.CreateGuid()" to make a new one. > _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}" > > def SplitString(self, val, item=None): > import string > if item != None: item = str(item) > return string.split(str(val), item) > > # Add code so that when this script is run by > # Python.exe, it self-registers. > if __name__=='__main__': > print "Registering COM server..." > import win32com.server.register > win32com.server.register.UseCommandLine(PythonUtilities) > > > I am using Python 2.5 and it says: > > Traceback (most recent call last): > File "E:/PyEN/PythonUtilities.py", line 20, in > import win32com.server.register > ImportError: No module named win32com.server.register Have you installed the Pywin32 extensions from here: http://sourceforge.net/projects/pywin32/ ? Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-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 jstroud at mbi.ucla.edu Thu Feb 8 06:10:56 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 08 Feb 2007 03:10:56 -0800 Subject: 'IF' Syntax For Alternative Conditions In-Reply-To: References: Message-ID: rshepard at nospam.appl-ecosys.com wrote: > All my python books and references I find on the web have simplistic > examples of the IF conditional. A few also provide examples of multiple > conditions that are ANDed; e.g., > if cond1: > if cond2: > do_something. > > However, I cannot find, nor create by trial-and-error, the syntax for > alternative conditions that are ORed; e.g., > > if cond1 OR if cond2: > do_something. > > I've tried using the C syntax for OR (||) but python complained. I'm sure > there's a way to do this rather than using if cond1: elif cond2: both with > the same code to execute. > > Please pass me a pointer so I can learn how to correctly write this. > > Rich For lots of conditions: import operator reduce(operator.or_, list_of_conditions) e.g.: py> import operator py> list_of_conditions = [ ... 'big' < 'small', ... 'all' > 'half', ... 'five' > 'one', ... 'six' < 'seven' ... ] py> list_of_conditions [True, False, False, False] py> reduce(operator.or_, list_of_conditions) True James From jorge.vargas at gmail.com Wed Feb 21 17:36:28 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 21 Feb 2007 18:36:28 -0400 Subject: BDFL in wikipedia In-Reply-To: <20070221082830.31BD26F4CF3@longblack.object-craft.com.au> References: <32822fe60702201827k36f8bd53k69908869a19f00e6@mail.gmail.com> <20070221082830.31BD26F4CF3@longblack.object-craft.com.au> Message-ID: <32822fe60702211436l506c501cp6472c05b9fdc0fbc@mail.gmail.com> On 2/21/07, Andrew McNamara wrote: > >Hi I just hit this page in wikipedia BDFL[1] > > > >and it redirected me to Guido's wikipedia[2] entry > >now without causing any troubles (read flamewar) shouldn't > > > >a) that page have an explanation of what BDFL is > >b) shouldn't it mention Linus, Larry Wall, others?[3] > >c) for the ones that have been around longer then me who was the first > >being call like that? > > > >[1] http://en.wikipedia.org/wiki/BDFL > >[2] http://en.wikipedia.org/wiki/Guido_van_Rossum > >[3] http://www.answers.com/topic/list-of-benevolent-dictators-for-life > > I'm sure you'll get 101 people telling you this, but this really isn't a > question for the python list, rather, it's a question for the Wikipedia > editors (and that's anyone). > well then here is a good place to find editors :) > I suspect, in this case, the redirect is implicit. It's happening > because the Wikipedia search engine finds no page called BDFL, and the > Guido_van_Rossum is the next closest match. > with my little knowledge of mediawiki that has to be set by someone. it's not automatic. > If you care and you have enough to say on the subject, maybe you could > start a BDFL page. > well that's the point I have here with c) I really don't know enough about it to write something there that is why I ask here. > -- > Andrew McNamara, Senior Developer, Object Craft > http://www.object-craft.com.au/ > From fumanchu at amor.org Fri Feb 9 16:51:09 2007 From: fumanchu at amor.org (fumanchu) Date: 9 Feb 2007 13:51:09 -0800 Subject: Database Programming with Python In-Reply-To: <1171047833.095277.62350@a75g2000cwd.googlegroups.com> References: <1171034880.089616.113380@p10g2000cwp.googlegroups.com> <1171040420.760665.326290@m58g2000cwm.googlegroups.com> <1171047833.095277.62350@a75g2000cwd.googlegroups.com> Message-ID: <1171057869.729513.287460@l53g2000cwa.googlegroups.com> On Feb 9, 11:03 am, Finger.Octo... at gmail.com wrote: > There are no examples of Dejavu that I found yet. I have installed it > but don't know how to use or call its functions. Read http://projects.amor.org/docs/dejavu/1.5.0RC1/ to learn how to use Dejavu. It's short and should at least give you an idea whether or not Dejavu is right for you. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From silverburgh.meryl at gmail.com Mon Feb 19 15:27:22 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 19 Feb 2007 12:27:22 -0800 Subject: How to call a function defined in another py file In-Reply-To: <45da0720$0$3822$5402220f@news.sunrise.ch> References: <1171916439.300543.209210@h3g2000cwc.googlegroups.com> <45da0720$0$3822$5402220f@news.sunrise.ch> Message-ID: <1171916841.964600.262530@q2g2000cwa.googlegroups.com> On Feb 19, 2:22 pm, "Martin Blume" wrote: > schrieb > > > I have a function called 'test' defined in A.py. > > How can I call that function test in my another file B.py? > > In B.py: > > import A > > A.test() > > HTH > Martin But Do I need to put A.py and B.py in the same directory? if not, where does python look for A.py ? And do I need to compile A.py before I can import it to B.py? From gagsl-py at yahoo.com.ar Mon Feb 12 01:01:56 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Feb 2007 03:01:56 -0300 Subject: string.replace non-ascii characters References: Message-ID: En Mon, 12 Feb 2007 02:38:29 -0300, Samuel Karl Peterson escribi?: Sorry to steal the thread! This is only related to your signature: > "if programmers were paid to remove code instead of adding it, > software would be much better" -- unknown I just did that last week. Around 250 useless lines removed from a 1000 lines module. I think the original coder didn't read the tutorial past the dictionary examples: *all* functions returned a dictionary or list of dictionaries! Of course using different names for the same thing here and there, ugh... I just throw in a few classes and containers, removed all the nonsensical packing/unpacking of data going back and forth, for a net decrease of 25% in size (and a great increase in robustness, maintainability, etc). If I were paid for the number of lines *written* that would not be a great deal :) -- Gabriel Genellina From igorr at ifi.uio.no Mon Feb 5 21:09:34 2007 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 06 Feb 2007 03:09:34 +0100 Subject: Checking default arguments References: <1170525388.330296.71480@j27g2000cwj.googlegroups.com> Message-ID: [ George Sakkis ] First of all, thanks to everyone who replied. [ ... ] > I don't know why you might want to distinguish between the two in > practice (the unique object idea mentioned in other posts should > handle most uses cases), but if you insist, here's one way to do it: There is no actual code situation where it happens. I was simply intrigued by the problem and could not find an answer. Since {}.pop behaves this way, I checked the C code. Apparently, it *is* quite easy from C, since PyArg_UnpackTuple and clever initial values (NULL vs. Py_None) make all the difference. The inspect-suggestion is, unfortunately, a bit more difficult to comprehend than I initially hoped for :) Thanks for all the suggestions [ ... ] ivr -- "...but it's HDTV -- it's got a better resolution than the real world." -- Fry, "When aliens attack" From B.Ogryczak at gmail.com Wed Feb 28 12:19:09 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 28 Feb 2007 09:19:09 -0800 Subject: finding out the precision of floats In-Reply-To: <1172674419.411077.4210@t69g2000cwt.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172674419.411077.4210@t69g2000cwt.googlegroups.com> Message-ID: <1172683149.885750.323640@j27g2000cwj.googlegroups.com> On Feb 28, 3:53 pm, "John Machin" wrote: > On Feb 28, 10:38 pm, "BartOgryczak" wrote: > > > [1] eg. consider calculating interests rate, which often is defined as > > math.pow(anualRate,days/365.0). > > In what jurisdiction for what types of transactions? I would have > thought/hoped that the likelihood that any law, standard or procedure > manual would define an interest calculation in terms of the C stdlib > would be somewhere in the region of math.pow(epsilon, HUGE), not > "often". YPB? Have you ever heard of real-time systems? > More importantly, the formula you give is dead wrong. The correct > formula for converting an annual rate of interest to the rate of > interest to be used for n days (on the basis of 365 days per year) is: > > (1 + annual_rate) ** (n / 365.0) - 1.0 > or > math.pow(1 + annual_rate, n / 365.0) - 1.0 > if you prefer. YPB? Anyone with half a brain knows, that you can either express rate as 0.07 and do all those ridiculous conversions above, or express it as 1.07 and apply it directly. > > BTW, math.* functions do not return Decimals. > > For which Bell Labs be praised, but what's your point? That Decimal is useless, for anything but invoices. From gagsl-py at yahoo.com.ar Tue Feb 20 22:28:08 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Feb 2007 00:28:08 -0300 Subject: Regex Speed References: <1172006981.581224.119090@l53g2000cwa.googlegroups.com> <1172013317.943062.303110@t69g2000cwt.googlegroups.com> <1172018440.659870.195010@h3g2000cwc.googlegroups.com> Message-ID: En Tue, 20 Feb 2007 21:40:40 -0300, escribi?: > My apologies. I don't have specifics right now, but it's something > along the line of this: > > error_list = re.compile(r"error|miss|issing|inval|nvalid|math") > > Yes, I know, these are not re expressions, but the requirements for > the script specified that the error list be capable of accepting > regular expressions, since these lists are configurable. Can you relax that restriction? Not always a regex is a good way, specially if you want speed also: py> import timeit py> line = "a sample line that will not match any condition, but long enough to be meaninful in the context of this problem, or at least I thik so. This has 174 characters, is it enough?" py> timeit.Timer('if error_list.search(line): pass', ... 'import re;error_list=re.compile(r"error|miss|issing|inval|nvalid|math");f rom __main__ import line').repeat(number=10000) [1.7704239587925394, 1.7289717746328725, 1.7057590543605246] py> timeit.Timer('for token in tokens:\n\tif token in line: break\nelse: pass', ... 'from __main__ import line;tokens = "error|miss|issing|inval|nvalid|math". split("|")').repeat(number=10000) [1.0268617863829661, 1.050040144755787, 1.0677314944409151] py> timeit.Timer('if "error" in line or "miss" in line or "issing" in line or "i nval" in line or "nvalid" in line or "math" in line: pass', ... 'from __main__ import line').repeat(number=10000) [0.97102286155842066, 0.98341158348013913, 0.9651561957857222] The fastest was is hard coding the tokens: if "error" in line or "miss" in line or... If that is not acceptable, iterating over a list of tokens: for token in token: if token in line... The regex is the slowest, a more carefully crafted regex is a bit faster, but not enough: py> timeit.Timer('if error_list.search(line): pass', ... 'import re;error_list=re.compile(r"error|m(?:iss(?:ing)|ath)|inval(?:id)") ;from __main__ import line').repeat(number=10000) [1.3974029108719606, 1.4247005067123837, 1.4071600141470526] -- Gabriel Genellina From jstroud at mbi.ucla.edu Fri Feb 2 07:19:11 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 02 Feb 2007 12:19:11 GMT Subject: Writing "pythonish" code In-Reply-To: References: Message-ID: <3%Fwh.1226$gj4.1040@newssvr14.news.prodigy.net> Mizipzor wrote: > Hi, this is my first mail to the list (and any list for that matter) > so any pointers on errors from my part would be appreciated. Im more > used to forums. > > To start off, Ive read some python documents and done some small apps > so I think I can say I know it semi-well, and I know c++ very well. > But I want learn python even better, since I know that a company I aim > to be employed by make heavy use of python, knowing python myself > would give me an extra edge. > > The problem isnt in pythons syntax, its in the architecture/design, > the concept of writing "pythonish code" if you like. One thing is that > in c++ im used to have private members in classes and no member is > altered except through the public functions of the class. In python > everything is, as far as I know, public. Im confused by this, should I > still have members in the python class that I simply dont edit > directly and let the class do its internal stuff? Or should I see the > python classes like c++ structs with functions? > > I guess the ultimate is somewhere in between but I would like a nudge > or two to get there. > > Now, the thing that bothers me the most. When I write python modules I > write one class per file, and the file and the class has a common > name. Maybe this is due to c++ habits. The problem is when I import > the module, make an instance of its class and store it in a variable: > > foo.py > ========= > > class foo: > def bar(self): > print "bar" > > ========= > > main.py > ========= > > import foo > > localFoo = foo.foo() > localFoo.bar() > > ========= > > To me, the main.py code above looks very ugly. So, assuming Im never > gonna have more than one instance of the foo class, can I write > something like this: > > foo.py > ========= > > def bar(self): > print "bar" > > ========= > > main.py > ========= > > import foo > > foo.bar() > > ========= > > Thats much more cleaner if you ask me, and kinda a good way to make > sure that you dont have more than one "instance" of the foo class > (which no longer is a class at all). But is it "pythonish"? > > Gonna stop now, this mail got a little longer than i first thought. > Any input will be greatly appreciated. :) The "import foo ... foo.bar()" way is preferred. Your instincts are correct. If you want to write pythonic style, here are some references in roughly the order I would read them after the tutorial--this is not a ranking but more ordered for study: 1. google and read the "python style guide" 2. "How to Think like a Computer Scientist" (google it) 3. Read this email list and take notes--these people know 4. David Mertz's "Text Processing in Python" -- a classic (google it) 5. John Grayson's "Python and Tkinter Programming" (Manning) 6. "Programming Python" by Mark Lutz (O'Reilly) I'm sure the cookbook (Ed. Alex Martelli) should be in there, but I haven't read it extensively so I don't know where it fits. Probably #7. James From gatti at dsdata.it Fri Feb 23 03:34:07 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: 23 Feb 2007 00:34:07 -0800 Subject: parse HTML by class rather than tag In-Reply-To: <1172217260.318877.290250@m58g2000cwm.googlegroups.com> References: <1172217260.318877.290250@m58g2000cwm.googlegroups.com> Message-ID: <1172219647.199461.247770@a75g2000cwd.googlegroups.com> On Feb 23, 8:54 am, lorean2... at yahoo.fr wrote: > Hello, > > i'm would be interested in parsing a HTML files by its corresponding > opening and closing tags but by taking into account the class > attributes and its values, [...] > so i wondering if i should go with regular expression, but i do not > think so as i must jumpt after inner closing div, or with a simple > parser, i've searched and foundhttp://www.diveintopython.org/html_processing/basehtmlprocessor.html > but i would like the parser not to change anything at all (no > lowercase). Horribly brittle idea. Use a robust HTML parser (e.g. http://www.crummy.com/software/BeautifulSoup/) to build a document tree, then visit it top down and look at the value of the 'class' attributes. Regards, Lorenzo Gatti From jfabiani at yolo.com Wed Feb 28 00:04:21 2007 From: jfabiani at yolo.com (johnf) Date: Tue, 27 Feb 2007 21:04:21 -0800 Subject: PyCon blogs? References: Message-ID: <578Fh.88$Pf1.42@newsfe02.lga> skip at pobox.com wrote: > Was anybody blogging about PyCon (talks and/or sprints)? Got any > pointers? > > Thanks, > > Skip At least one session was posted on YouTube http://dabodev.com/pycon2007 Johnf From arkanes at gmail.com Mon Feb 12 09:01:31 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Feb 2007 08:01:31 -0600 Subject: standardized us address In-Reply-To: References: Message-ID: <4866bea60702120601j7bc07060g4626060241004aec@mail.gmail.com> On 2/11/07, mark wrote: > Hi > Is there any python module that will convert address to standard US address > format: > for ex: > > 314 south chauncey avenue > > should be: > 314 s chauncey ave > > > thanks > mark > This isn't standardization, it's normalization. The USPS maintains databases that you can use to help you do this, and they'll point you to third parties who sell software that does it. It's a non-trivial task. From paddy3118 at netscape.net Fri Feb 2 23:46:08 2007 From: paddy3118 at netscape.net (Paddy) Date: 2 Feb 2007 20:46:08 -0800 Subject: from... import... In-Reply-To: <9s28s29864vgkdbtevi8fna5h1r04ekgr9@4ax.com> References: <9s28s29864vgkdbtevi8fna5h1r04ekgr9@4ax.com> Message-ID: <1170477968.298619.60370@l53g2000cwa.googlegroups.com> On Feb 3, 4:12 am, fatwallet... at yahoo.com wrote: > what's the from ... import keyword use for? > for example - from contenttype import getContentType > > import os > import sys > import getopt > import types > import re > import pprint > import logging > from contenttype import getContentType > > In Java what kind of statement is similar this? > > thanks Try: http://diveintopython.org/object_oriented_framework/ importing_modules.html http://www.python.org/doc/current/tut/ node8.html#SECTION008100000000000000000 And more generally maybe: http://www.ferg.org/projects/python_java_side-by-side.html http://dirtsimple.org/2004/12/python-is-not-java.html Happy coding - Paddy. From tdelaney at avaya.com Wed Feb 28 16:40:13 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 1 Mar 2007 08:40:13 +1100 Subject: Python Source Code Beautifier Message-ID: <2773CAC687FD5F4689F526998C7E4E5F07446E@au3010avexu1.global.avaya.com> Alan Franzoni wrote: > Yeah, that's right, it could have semantic differences, but that > shouldn't be the case anyway. I mean, if I don't define an __iadd__ > method, writing > > a += n > > or > > a = a + n > > is just the same, right? > > So, if I bother to define an __iadd__ method, I should make sure it > works just the same, or I would introduce a very strange and > hard-to-understand behaviour. As you've seen, that's not the case. The *whole point* of having __iadd__ is to perform an *in-place* add i.e. mutate the object you're assigning to. So it's the behaviour of *immutable* objects that is the exception. The other semantics of immutable objects cover that though - you should never rely on whether two equal immutable objects (like integers) are the same or different objects. Tim Delaney From jeremit0 at gmail.com Tue Feb 6 11:42:55 2007 From: jeremit0 at gmail.com (jeremito) Date: 6 Feb 2007 08:42:55 -0800 Subject: How can I use __setitem__ method of dict object? In-Reply-To: <1170777579.390667.313670@q2g2000cwa.googlegroups.com> References: <1170775388.533078.115330@k78g2000cwa.googlegroups.com> <1170777579.390667.313670@q2g2000cwa.googlegroups.com> Message-ID: <1170780175.118806.11700@k78g2000cwa.googlegroups.com> On Feb 6, 10:59 am, "bruno.desthuilli... at gmail.com" wrote: > On 6 f?v, 16:23, "jeremito" wrote: > > > > > Please excuse me if this is obvious to others, but I can't figure it > > out. I am subclassing dict, but want to prevent direct changing of > > some key/value pairs. For this I thought I should override the > > __setitem__ method as such: > > > class xs(dict): > > """ > > XS is a container object to hold information about cross sections. > > """ > > > def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): > > """ > > """ > > x = {} > > x['xS'] = xS > > x['xF'] = xF > > x['nu'] = nu > > x['xG'] = xG > > x['xA'] = x['xG'] + x['xF'] > > x['xT'] = x['xA'] + x['xS'] > > > return x > > replace this with: > def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): > dict.__init__( > self, > xS=xS, > xF=xF, > xG=xG, > nu=nu, > xA=xG + xF, > xT=xG + xF + xS > ) > > > def __setitem__(self, key, value): > > """ > > I have overridden this method to prevent setting xT or xA > > outside the > > class. > > """ > > print "I am in __setitem__" > > if key == 'xT': > > raise AttributeError( > > "Can't change xT. Please change, xF, xS, or xG" > ) > dict.__setitem__(self, key, value) > > > But I can't even get __setitem__ to run. > > of course, since your __new__ method returns a dict instance, not a xs > instance... > There are very few cases where you really need to override the __new__ > method. The reason I create my object with __new__ instead of __init__ is because when I use __init__ when a value is set it calls __setitem__. This is what I want to happen, but not inside of __init__. Does this make sense? I'm sure there is a better/more pythonic way to do this, but I'm unsure of what it is. Can someone show me an example of how this should work? > > > Example: > > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > > Type "help", "copyright", "credits" or "license" for more information.>>> import xs > > >>> cs = xs.xs() > > >>> cs > > > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}>>> cs['xT'] = 3.1415 > > >>> cs > > > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': > > 3.1415000000000002} > > > Is this what the __setitem__ method is for? > > Yes. But note that you you need to manually call the superclass's > overriden method - unless you > really want to replace it with your own, which is obviously not the > case here... > > Note that if someone manually changes the values of xG, xF, or xS, the > computed values of xA and/or xT > won't reflect this change. Is that what you want ? > Eventually (when I figure out how to use __setitem__) I will change what happens when xG, xF, or xS are changed so that it also changes xA and xT. > Finally, and if I may ask, what is your use-case for subclassing > dict ? You don't need this to implement a dict-like object, > and it might be simpler in your case to write an ordinary class, then > add support for the required subset of the dict interface. Eventually I am going to add other features to my class (as I have mentioned) so I can't simply use a dict object. > > My 2 cents... Thanks again, Jeremy From moustikitos at gmail.com Thu Feb 22 16:55:42 2007 From: moustikitos at gmail.com (moustikitos at gmail.com) Date: 22 Feb 2007 13:55:42 -0800 Subject: Scrolled frame for Tkinter & Python Wrapper for Tile Message-ID: <1172181342.821655.202930@a75g2000cwd.googlegroups.com> I wrote a scrolled frame for Tkinter : http://bruno.thoorens.free.fr/downloads/scrolled.py I also wrote a Tile wrapper for Python : http://bruno.thoorens.free.fr/downloads/ttk.html http://bruno.thoorens.free.fr/downloads/Ttk-src.zip Bruno From v.davis2 at cox.net Wed Feb 28 19:20:02 2007 From: v.davis2 at cox.net (v.davis2) Date: Wed, 28 Feb 2007 17:20:02 -0700 Subject: A Windows Printing Problem -- Tk Canvas Under Python Message-ID: Hi all, I have searched a bit for this -- both in the newsgroup and Google -- No luck. How do I print a Tk Canvas object under Windows? No, I do NOT want to generate the Postscript and do it that way (unless I have to). The same question applies to other aspects of the GUI. I just have to believe that this common problem has been solved so many times that everyone thinks it trivial -- except me. Help please? Vic From arkanes at gmail.com Fri Feb 2 14:51:26 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 2 Feb 2007 13:51:26 -0600 Subject: Python does not play well with others In-Reply-To: <7xr6t89wkw.fsf@ruckus.brouhaha.com> References: <7xzm864y36.fsf@ruckus.brouhaha.com> <7x64alp986.fsf@ruckus.brouhaha.com> <1170418101.540654.307320@l53g2000cwa.googlegroups.com> <7xtzy48jg3.fsf@ruckus.brouhaha.com> <7xr6t89wkw.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60702021151t29e9af7bwbd637c7a07d06e7c@mail.gmail.com> On 02 Feb 2007 11:41:03 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Chris Mellon" writes: > > How about because thats what you pay them for? Seriously. Do you even > > think about what you're saying? Python needs to move MySQL (and only > > MySQL, of course) into the core because installing packages is too > > much of a burden for hosting companies? > > What does "batteries included" mean to you? To me, it means you don't > have to install add-ons. > Well, thats just stupid. I'm not sure where else to go with that. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Feb 26 20:30:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Feb 2007 02:30:48 +0100 Subject: Lists: Converting Double to Single References: Message-ID: <54hfu8F209918U1@mid.individual.net> rshepard at nospam.appl-ecosys.com wrote: > I end up with a single list, but with two brackets on each end, > for example, [[3.5, 4.5, 5.5, 6.5, 7.5]]. > > Unfortunately, when I try to use that last list in a NumPy > function, I'm > told that it cannot be broadcast to the correct shape. So, what I > want to do is strip the extra brackes from each end to leave just > [3.5, 4.5, 5.5, 6.5, 7.5]. > > How do I do this, please? Easy :) I'll show you by example: >>> ham = [[1,2,3],[4,5,6]] >>> ham [[1, 2, 3], [4, 5, 6]] >>> ham[0] [1, 2, 3] >>> ham.remove([4,5,6]) >>> ham[0] [1, 2, 3] >>> ham [[1, 2, 3]] >>> HTH&Regards, Bj?rn -- BOFH excuse #453: Spider infestation in warm case parts From a.schmolck at gmail.com Mon Feb 5 16:55:39 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Feb 2007 21:55:39 +0000 Subject: Calling J from Python References: <1170686928.985128.16720@h3g2000cwc.googlegroups.com> <52ov20F1of7ecU1@mid.uni-berlin.de> <1170692852.549730.81030@v33g2000cwv.googlegroups.com> <52p5mbF1p0r0cU2@mid.individual.net> <52pc34F1oqe5fU1@mid.individual.net> <45c7a075$0$1029$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > No, thanks. But hopefully we have Python : > > Python 2.4.1 (#1, Jul 23 2005, 00:37:37) > [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>> 3 + 4 > 7 > >>> My calculuator even gives a pretty good answer if I divide them (without importing anything from the __future__). 'as From mail at microcorp.co.za Fri Feb 9 01:18:10 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 9 Feb 2007 08:18:10 +0200 Subject: Simple Interpolation in Numpy? References: <134863FF4EA9A54E8EC307A2F4214566096E0E51@ACCLUST01EVS1.ugd.att.com> Message-ID: <021a01c74c18$4428d040$03000080@hendrik> LAPI, VINCENT J, ATTLABS wrote: >Hi, >Please bear with me as I am new to Python and have not done any programming in about 20 years. I am >attempting to do a simple interpolation of a line's intermediate points given the x,y coordinates of the line's two >endpoints within an Active State Python script that I am working with. Is there a simple way to do this simple >interpolation in the Active state Python 2.4 that I have or do I need to get Numeric Python? And where do I get >it? You don't need anything fancy, the bulk standard python should do this: untested: ep0 = (x0,y0) # known endpoints ep1 = (x1,y1) dx = x1-x0 # calculate span dy = y1-y0 y = y0 + dy*(x-x0)/dx # to give y from known x x = x0 + dx*(y-y0)/dy # to give x from known y The interactive interpreter is your friend. (you activate it by typing "Python" at the command prompt) (don't type the quotes..) Use it for playing with this kind of stuff. And other stuff too - it answers most questions of the: "can I do this? " and "what happens when I ..." variety. Also read the tutorial - if you have done programming twenty years ago, you will take to it like a duck to water. It really works much easier than a teletype... hth - Hendrik From deets at nospam.web.de Mon Feb 26 15:13:31 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Feb 2007 21:13:31 +0100 Subject: Add images together In-Reply-To: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> References: <1172520384.664573.192880@q2g2000cwa.googlegroups.com> Message-ID: <54gtc3F214sakU1@mid.uni-berlin.de> iceman schrieb: > Hi, > > I am trying to add together a number of images: > > im = image1 + image2 + ... > > How can i do this? I have tried to add two image instances > together but i get the following error: > TypeError: unsupported operand type(s) for +: 'instance' and > 'instance' Create a new image of double size, and blit the images to the correct destination. Diez From kavithapython at yahoo.co.in Wed Feb 28 03:26:55 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Wed, 28 Feb 2007 08:26:55 +0000 (GMT) Subject: newbie question(file-delete trailing comma) In-Reply-To: <45E42C8E.7020804@isy.liu.se> Message-ID: <495461.77638.qm@web7801.mail.in.yahoo.com> ok,,, my script writes a dictionary to a file.but i need only the values from the dictionary which should be sepearted by a comma,,,so i did as following: some=getAllData()------>dictionary f=open("test.txt", "w") for value in some.values(): f.writelines('\%s\,' % value )---->strings seperated by comma when i execute the above code,my test.txt file has the following: a,b,c,d, now i need to delete the comma at the end,,,this is my problem,,, kavitha Mikael Olofsson wrote: kavitha thankaian wrote: > i get an error when i try to delete in file and rename it as out > file,,the error says > "permission denied". Perhaps you should give us both the exact code you are running and the complete traceback of the error. That could make things easier. There can be numerous reasons for "permission denied". > actually i need something like following: > > in_file = open('in.txt','w') > for line in in_file: > line.strip().strip(',') > > but when i run the above code,i get an error"bad file descriptor" Of course you do! You are opening the file for writing, but your code attempts to read the file. Probably, you think that the code would change the lines in the file itself, which it does not, even if it would be possible to read from a file opened for writing. What's wrong with the code that Mohammad posted? Note that you might need to close out_file in his code. /MiO -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From gigs at hi.t-com.hr Fri Feb 16 04:45:50 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 16 Feb 2007 10:45:50 +0100 Subject: Tkinter __call__ In-Reply-To: References: Message-ID: John McMonagle wrote: > Gigs_ wrote: >> from Tkinter import * >> from tkFileDialog import askopenfilename >> from tkColorChooser import askcolor >> from tkMessageBox import askquestion, showerror >> from tkSimpleDialog import askfloat >> >> demos = { >> 'Open': askopenfilename, >> 'Color': askcolor, >> 'Query': lambda: askquestion('Warning', 'You typed >> "..."\nConfirm?'), >> 'Error': lambda: showerror('Error!', "He's dead, Jim"), >> 'Input': lambda: askfloat('Entry', 'Enter credit card number') >> } >> >> >> class Demo(Frame): >> def __init__(self, parent=None): >> Frame.__init__(self, parent) >> self.pack() >> Label(self, text="Basic demos").pack() >> for (key, value) in demos.items(): >> func = (lambda: self.printit(key)) >> Button(self, text=key, command=func).pack(side=TOP, >> fill=BOTH) >> def printit(self, name): >> print name, 'returns =>', demos[name]() >> >> >> I have tried but cant get it to work properly. >> I want to instead printit method to put __call__ and call it like that >> Can someone help me, please? > > Add the following lines to the end of your script and all should work as > expected: > > root = Tk() > app = Demo(root) > root.mainloop() > I have write root window, but forgot to write here I want to use __call__ method instead printit From dingbat at codesmiths.com Wed Feb 14 10:09:52 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 14 Feb 2007 07:09:52 -0800 Subject: rot13 in a more Pythonic style? Message-ID: <1171465792.491203.309030@k78g2000cwa.googlegroups.com> I'm trying to write rot13, but to do it in a better and more Pythonic style than I'm currrently using. What would you reckon to the following pretty ugly thing? How would you improve it? In particular, I don't like the way a three-way selection is done by nesting two binary selections. Also I dislike stating the same algorithm twice, but can't see how to parameterise them neatly. Yes, I know of .encode() and .translate(). No, I don't actually need rot13 itself, it's just a convenient substitute example for the real job-specific task. No, I don't have to do it with lambdas, but it would be nice if the final function was a lambda. #!/bin/python import string lc_rot13 = lambda c : (chr((ord(c) - ord('a') + 13) % 26 + ord('a'))) uc_rot13 = lambda c : (chr((ord(c) - ord('A') + 13) % 26 + ord('A'))) c_rot13 = lambda c : (((c, uc_rot13(c)) [c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']), lc_rot13(c) )[c in 'abcdefghijklmnopqrstuvwxyz'] rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'') print rot13( 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' ) From steve at holdenweb.com Wed Feb 7 15:46:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Feb 2007 20:46:19 +0000 Subject: Simple SVN/CVS-like library in Python? In-Reply-To: References: Message-ID: <45CA3A9B.4090908@holdenweb.com> Andrea Gavana wrote: > Hi All, > > in our office we work with quite complex input files for a > reservoir simulator. Those files have thousands of keywords, switches, > sub-keywords and whatever. Every time a modification is requested, we > modify the input file and re-run the simulator. Obviously, the > possible modifications are innumerable: so, after few months, we lose > the records of all the changes we made during time and we don't have > anymore a clear history of our work. This can be a problem, as > sometimes it happens that an old input file is requested by > collegues/sub-companies, and it is a pain to retrieve the correct file > and results. > So, I have written a GUI in wxPython that could help us in tracking > the history, but I was wondering if there exists a small and simple > SVN/CVS-like library in Python that may help us in a better way, > storing modifications/changes and showing which input file are the > "children" of (are derived from) another input file (older). > But I am open to all possible suggestions to improve/modify the > software, as this is an area in which my experience is about nothing > above zero. > > Thank you very much for every hint. > I should have thought that the best way to achieve this functionality would be to use the SVN or CVS commands using os.system or the subprocess module. There is at least one Python interface to Subversion, however. See http://pysvn.tigris.org/ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From svatoboj at gmail.com Tue Feb 27 10:18:46 2007 From: svatoboj at gmail.com (svata) Date: 27 Feb 2007 07:18:46 -0800 Subject: os.system and quoted strings In-Reply-To: <1172587001.704618.230120@j27g2000cwj.googlegroups.com> References: <1172586281.606903.79990@s48g2000cws.googlegroups.com> <1172587001.704618.230120@j27g2000cwj.googlegroups.com> Message-ID: <1172589526.538625.29100@a75g2000cwd.googlegroups.com> On Feb 27, 2:36 pm, "Sriram" wrote: > Hello svata, > It is always better to compose your string before you send it as a > command. > > try printing your command string out like this : > print 'gvim dir+fileName+".txt". You'll see what the problem is. > > One possible solution is to compose your command string in the > following manner: > cmd = "gvim %s%s.txt" %(dir, fileName) > and simply call os.system with cmd. > os.system(cmd) > > Here is a little more detail on string format specifiershttp://docs.python.org/lib/typesseq-strings.html > > HTH > Sriram > > On Feb 27, 7:24 am, "svata" wrote: > > > Hello, > > > as I'm new to python I've stumbled accros os.system and its not very > > well documented usage. > > > I use Win XP Pro and Python 2.5. > > > Here is the code snippet: > > > -------------------------------------------------------------------------------------------------- > > > import time > > import os > > > dir = "C:\\Documents and Settings\\somepath\\" > > fileName = time.strftime("%d%m%Y") > > os.system('gvim dir+fileName+".txt"') > > > --------------------------------------------------------------------------------------------------- > > > The problem is that concatenated variable dir+fileName doesn't get > > expanded as expected. > > > Is there anything I omitted? > > > svata Thank you for prompt reply. I should be more concise with strings, I think :) svata From mdfranz at gmail.com Thu Feb 8 16:10:23 2007 From: mdfranz at gmail.com (Matthew Franz) Date: Thu, 8 Feb 2007 15:10:23 -0600 Subject: python linux distro In-Reply-To: <1170955617.478249.82460@m58g2000cwm.googlegroups.com> References: <1170945862.761651.4710@v33g2000cwv.googlegroups.com> <1170955617.478249.82460@m58g2000cwm.googlegroups.com> Message-ID: <33acb3db0702081310l22ac5094v1e4206380ede60c@mail.gmail.com> > thanks guys > > when i wrote this, i thought that out there is some crazy guy like me. > i was hoping for more support but after these arguments, there is > nothing more then to say:you are right. the world doesnt need another > distro. but if one day I mange to do it, hope you will be glade that i > post the lik here. > Now what would be interesting (and *really* crazy) would be Linux (or BSD or whatever) distro written almost entirely *in* Python, with the goal of eliminating as much bash/sh as possible. That would be fun. - mdf From ziga.seilnacht at gmail.com Tue Feb 27 15:50:37 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 27 Feb 2007 12:50:37 -0800 Subject: Automatic reloading, metaclasses, and pickle In-Reply-To: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> References: <1172605270.840362.248090@q2g2000cwa.googlegroups.com> Message-ID: <1172609437.801573.150900@m58g2000cwm.googlegroups.com> Andrew Felch wrote: > Hello all, > > I'm using the metaclass trick for automatic reloading of class member > functions, found at:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > > My problem is that if I > 1) pickle an object that inherits from "AutoReloader" > 2) unpickle the object > 3) modify one of the pickled' object's derived class methods > 4) reload the module holding the class > > ... then the changes don't affect the unpickled object. If I unpickle > the object again, of course the changes take effect. > > My friend that loves Smalltalk is laughing at me. I thought I had the > upperhand when I discovered the metaclasses but now I am not sure what > to do. I really don't want to have to unpickle again, I'm processing > video and it can take a long time. > > By the way, I used to avoid all of these problems by never making > classes, and always building complex structures of lists, > dictionaries, and tuples with global functions. It's going to take me > a while to kick those horrible habits (during my transition, I'm > deriving from list, dict, etc. hehe), perhaps a link to the metaclass > trick is in order in the tutorial's comments on reload? > > Any help that avoids having to unpickle again is appreciated! > > Thanks, > Andrew Felch This happens because unpickling doesn't recreate your object by calling its type. MetaInstanceTracker registers an instance only when it is created by calling a class. You can solve this by moving the instance registration to AutoReloader.__new__ and using pickle protocol version 2, but the best solution is to avoid both pickle (old pickles break if you change your code) and autoreloading (it's meant to be used in interactive console and entertaining ircbots, not in normal code). Ziga From danielkleinad at gmail.com Wed Feb 28 22:46:47 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Thu, 01 Mar 2007 03:46:47 GMT Subject: Question about raise and exceptions. References: <45e5e640$0$18215$426a74cc@news.free.fr> Message-ID: On Wed, 28 Feb 2007 22:03:13 +0100, Bruno Desthuilliers wrote: >Daniel Klein a ?crit : >> The arguments for TransitionError must be a tuple, > >Err... > >> eg: >> >> msg = "Going to error state %d from state %d" % (self.curr_state, >> newstate) >> raise TransitionError(self, curr_state, newstate, msg) > >Where did you see a tuple here ? You're code is *calling* >TransitionError, passing it the needed arguments. > >Note that it's the correct syntax - but not the correct explanation !-) My bad :-( Thanks for setting me straight. I had (wrongly) thought that the stuff inside of () was a tuple. To the OP: Please accept my apology for providing incorrect information. Dan From steve at holdenweb.com Sat Feb 10 13:30:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Feb 2007 18:30:08 +0000 Subject: What does "del" actually do? In-Reply-To: <76fd5acf0702100936l2e6db946k8891d7ee0ab83c65@mail.gmail.com> References: <8bnzh.74754$qO4.52439@newssvr13.news.prodigy.net> <76fd5acf0702100936l2e6db946k8891d7ee0ab83c65@mail.gmail.com> Message-ID: Calvin Spealman wrote [top-posting, which I have corrected]: > On 2/10/07, John Nagle wrote: >> The Python "reference manual" says, for "del", "Rather that spelling it out >> in full details, here are some hints." That's not too helpful. >> >> In particular, when "del" is applied to a class object, what happens? >> Are all the instance attributes deleted from the object? Is behavior >> the same for both old and new classes? >> >> I'm trying to break cycles to fix some memory usage problems. >> > del simply removes the name in the current scope. if that happens to > be the last non-cyclic reference to the object it was bound to, then > it will remove the object to, but thats a separate matter. if you > remove the class and there are instances out there, they can only > exist if there are some other references to them, so no, they arent > deleted. > > del wont just delete a bunch of objects and leave broken names. i has > nothing to do with deleting objects, only names. > Except, of course, when you aren't deleting names but elements of some container object. The del statement removes references to objects as well as removing names from namespaces and elements from container objects. Calvin is correct, though. Since each instance of a class contains a reference to the class, the class will live on even after it is deleted by name, being garbage-collected only after all instances have ceased to exist. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From jjl at pobox.com Sun Feb 4 14:15:44 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 04 Feb 2007 19:15:44 GMT Subject: Create a cookie with cookielib References: <45c46296$0$40782$4fafbaef@reader4.news.tin.it> Message-ID: <874pq1spir.fsf@pobox.com> "Matthew Franz" writes: > I'm not sure what you mean be forge, but if you mean set an arbitrary > cookie manually (vs. one that was provided by the server). just use > add_header() in http://docs.python.org/lib/request-objects.html > > It may be possible to use CookieJar for this purpose but I've only > used it for manipulating cookies set by the server... > > And I would agree that Python cookie APIs are less intuitive than > what are available in others such as Jakarta HttpClient.... There's not really intended to *be* an API, for most purposes -- you just let it do its stuff. What do you like from HttpClient? John From jstroud at mbi.ucla.edu Mon Feb 5 18:29:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 05 Feb 2007 15:29:33 -0800 Subject: Coordinate Grid Points In-Reply-To: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> References: <1170716120.975642.41450@k78g2000cwa.googlegroups.com> Message-ID: Eric.Gabrielson at gmail.com wrote: > Hello, > I am very knew to python and am attempting to write a program > in python that a friend of mine is having to write in java. I am doing > this for fun and would like some help as to how i can generate random > coordinate points (x,y) and compare them with user inputted coordinate > points. For example how will I be able to access the separate values, > the x from the x,y position. I think I understand everything except > 1)the random coordinate points 2) the getting the users inputted x and > y values in one line ("Please guess a coordinate point from (1,1) to > (20,20): ") as opposed to ("Please enter an x value:" and "Please > enter a y value") and finally 3) acessing the x value from the x,y > coordinate function. the assignment description is located here http:// > www.cs.washington.edu/education/courses/142/07wi/homework/ > homework.html if you would like to see a more in depth discription of > the game. > > Many Thanks, > Eric > For 1: see the random module (e.g. random.randint) For 2: see the "eval" function and "raw input" For 2 (without cheating): see the re module. For example: map(int, re.compile("\(?(\d+),(\d+)\)?").search(inpt).groups()) (Giving you the latter because eval will do this for you anyway.) Also see "raw_input". James From gert.cuykens at gmail.com Wed Feb 28 06:39:37 2007 From: gert.cuykens at gmail.com (gert) Date: 28 Feb 2007 03:39:37 -0800 Subject: random textimage In-Reply-To: References: <1172660299.114009.42950@a75g2000cwd.googlegroups.com> Message-ID: <1172662776.965147.49920@v33g2000cwv.googlegroups.com> On Feb 28, 12:13 pm, James Stroud wrote: > gert wrote: > > gert at gert:~/Desktop/svn/xhtml$ python2.5 textimg.py > > Traceback (most recent call last): > > File "textimg.py", line 27, in > > print gen() > > File "textimg.py", line 22, in gen > > f.write(im) > > TypeError: argument 1 must be string or read-only character buffer, > > not instance > > gert at gert:~/Desktop/svn/xhtml$ > > > i am stuck anybody can help me ? > > Are you sure you don't want f.write(img) ? > > James no this seems to work lol :) import ImageFont, ImageDraw, Image def gen(text): image_file = "test.jpg" image = Image.open(image_file) font = "font.ttf" draw = ImageDraw.Draw(image) font = ImageFont.truetype(font, 12) draw.text((1, 1), text,font=font) image.save("temp.jpg") if __name__ == "__main__": import random print gen(str(random.randint(0,1000))) The next problem would be that i need this to work in cherrypy because if two persons login at the same time the first user get to see the second user textimage DOH! From fred at adventistcare.org Tue Feb 13 16:40:50 2007 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 13 Feb 2007 16:40:50 -0500 Subject: Testers please Message-ID: <1A4BF05172023E468CB6E867923BC90404B0CFB6@accmail2.sunbelt.org> cool product, I'll test depending on schedule at the time. one (more) suggestion (from those of us who arn't doing the work ;) is to put this in eclipse, rather than apache, since many developers work with it. Please no IDE wars, I like emacs too, but when I'm trying to teach to newbies I use elcipse. -----Original Message----- From: python-list-bounces+frsells=adventistcare.org at python.org [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On Behalf Of martien friedeman Sent: Monday, February 12, 2007 8:38 PM To: python-list at python.org Subject: Testers please I have written this tool that allows you to look at runtime data and code at the same time. And now I need people to test it. The easiest way to see what I mean is to look at some videos: http://codeinvestigator.googlepages.com/codeinvestigator_videos It requires Apache and Sqlite. It works for me with a Firefox browser on Linux. -- http://mail.python.org/mailman/listinfo/python-list From lbates at websafe.com Mon Feb 26 12:37:54 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 26 Feb 2007 11:37:54 -0600 Subject: NetUseAdd mystery In-Reply-To: <1172508987.854983.162370@j27g2000cwj.googlegroups.com> References: <1172508987.854983.162370@j27g2000cwj.googlegroups.com> Message-ID: king kikapu wrote: > Is anyone see any error in the following code: > > mapDrive = "\\\\MyServer\\C$" > data = {'remote' : mapDrive, 'local' : 'M:', 'password' : > 'mypassword', 'user' : 'Administrator', 'asg_type' : 0} > win32net.NetUseAdd(None, 1, data) > > It gives me "pywintypes.error: (1326, 'NetUseAdd', 'Logon failure: > unknown user name or bad password.')" and i cannot figured out why...I > searched the forum about the syntax of NetUseAdd command and i think > that the syntax is correct and also are the data that i pass to it. > (the same data can give me a connection if i use "net use ..." from a > command line" > > So, what am i doing the wrong way (and keeps me on this the last 2 > hours??...) > > > Thanks for a any enlightenment... > I think your problem is that C$ is a "special" share. Try creating a share and connect to it instead. It is either that your your userid/ password are in fact incorrect. -Larry From bkamrani at gmail.com Fri Feb 23 04:01:35 2007 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: 23 Feb 2007 01:01:35 -0800 Subject: list/get methods/attributes of a class? In-Reply-To: <1172162242.724603.224050@v45g2000cwv.googlegroups.com> References: <1172158035.977029.188980@q2g2000cwa.googlegroups.com> <1172162242.724603.224050@v45g2000cwv.googlegroups.com> Message-ID: <1172221295.741748.145850@s48g2000cws.googlegroups.com> On Feb 22, 5:37 pm, "Jason" wrote: > On Feb 22, 8:27 am, bkamr... at gmail.com wrote: > > > Hello, > > Sorry guys for this newbie questions. But I wonder if there is a > > standard or build-in method to know the methods of a class? > > > I'm not originally a progrommer and I have worked with python/qt in a > > basic level. Now I work a package which has many predefined classes > > which I'm going to resue by importing them. I would like to know more > > about each imported class, what methods exists and so on. Printing the > > object or type(object) doesn't say so much. > > > Any hint or helps is really appreciated! > > /Ben > > Also, try out the built-in help function on the original class. It'll > list the class layout, methods, and any associated document strings. > (It won't list member variables, though.) To see all elements in an > instance or class, use the dir() function. > > >>> class Dummy(object): > > ... "A sample class that can have any given data." > ... def __init__(self, *args): > ... self._args = args > ... def GetArgCount(self): > ... """Show how many arguments were passed at > instantiation.""" > ... return len(self._args) > ...>>> d = Dummy(1, 2, 'three') > >>> help(d) # help(Dummy) also works > > Help on Dummy in module __main__ object: > > class Dummy(__builtin__.object) > | A sample class that can have any given data. > | > | Methods defined here: > | > | GetArgCount(self) > | Show how many arguments were passed at instantiation. > | > | __init__(self, *args) > | > | > ---------------------------------------------------------------------- > | Data and other attributes defined here: > | > | __dict__ = > | dictionary for instance variables (if defined) > | > | __weakref__ = > | list of weak references to the object (if defined) > > > > --Jason Thanks and regards!