[ANN] Leipzig Python User Group - Meeting, October 9, 2007, 08:00pm
=== Leipzig Python User Group === We will meet on Tuesday, Oktober 9 at 08:00pm at the training center of Python Academy in Leipzig, Germany ( http://www.python-academy.com/center/find.html ). Markus Zapke-Gründemann will present an example application with Nevow. Food and soft drinks are provided. Please send a short confirmation mail to [EMAIL PROTECTED], so we can prepare appropriately. Everybody who uses Python, plans to do so or is interested in learning more about the language is encouraged to participate. While the meeting language will be mainly German, we will provide English translation if needed. Current information about the meetings are at http://www.python-academy.com/user-group . Mike == Leipzig Python User Group === Wir treffen uns am Dienstag, 09.10.2007 um 20:00 Uhr im Schulungszentrum der Python Academy in Leipzig ( http://www.python-academy.de/Schulungszentrum/anfahrt.html ). Markus Zapke-Gründemann wird eine Beispielanwendung mit Nevow vorstellen. Für das leibliche Wohl wird gesorgt. Eine Anmeldung unter [EMAIL PROTECTED] wäre nett, damit wir genug Essen besorgen können. Willkommen ist jeder, der Interesse an Python hat, die Sprache bereits nutzt oder nutzen möchte. Aktuelle Informationen zu den Treffen sind unter http://www.python-academy.de/User-Group zu finden. Viele Grüße Mike -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Top Programming Languages of 2013
http://www.redcanary.ca/view/top-programming Dick Moores -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
On Oct 6, 12:57 pm, Bruno Desthuilliers Michele Simionato a écrit : I looked at the source code and it seems fine to me, but I have not used it directly, not stressed it. I need a production-level WSGI session middleware and I wonder what the players are (for instance how Beaker does compare with flup?) Can't tell, but I'd trust the Pylons team on this kind of choices. They're doing good job so far AFAICT. Probably Beaker works well, but it is certainly NOT doing things as Eby recommends: http://dirtsimple.org/2007/02/wsgi-middleware-considered-harmful.html BTW, I know that Eby is asking opinions about WSGI 2.0 on the WSGI SIG and interested people may have a look there. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter text widget
On Oct 6, 11:18 pm, goldtech [EMAIL PROTECTED] wrote: I thought the DISABLED made it so I could not edit it. But it also makes it so I can not scroll down. If you make the window smaller than the content then try to put a cursor in there to use up/down arrow you can't. What I want is not to be able to change text content, but no other action is disabled. Is this complicated to do? Thanks. from Tkinter import * root = Tk() text = Text(root, font=(Courier)) text.pack() i='123456789abcdefghijklmnopqrstuvwxyz\n' for x in range(30): text.insert(END, i) text.config(state=DISABLED) mainloop() You can scroll, but you can't see the cursor. Use for x in range(30): text.insert(END, %3d % x + i) to check. ED -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help to understand garbage collection
Thanks Gabriel! I get it now. With your help I was able to focus on the real problem. Here is the correctly working example for the record: import gc class Test(object): def __init__(self): pass gc.collect() original_objects_id = [id(x) for x in gc.get_objects()] #create object a a = Test() gc.collect() new_objects = [x for x in gc.get_objects() if id(x) not in original_objects_id] print - * 40 print Added object:, len(new_objects) for obj in new_objects: print * * 10 print str(id(obj)) + : + str(obj) print gc.get_referents(obj) print * * 3 print - * 20 del new_objects del obj gc.collect() original_objects_id = [id(x) for x in gc.get_objects()] #remove object a del a gc.collect() after_rm_objects_id = [id(x) for x in gc.get_objects()] removed_objects_id = [idx for idx in original_objects_id if idx not in after_rm_objects_id] print - * 40 print Removed objects:, len(removed_objects_id) print removed_objects_id print - * 20 -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyparsing 1.4.8 released
I'm happy to announce that I have just uploaded the latest release (v1.4.8) of pyparsing. This release has a few new features and corresponding demonstration examples. There are also a few minor bug-fixes, and a performance speedup in the operatorPrecedence method. Here are the notes: - Added new helper method nestedExpr to easily create expressions that parse lists of data in nested parentheses, braces, brackets, etc. - Added withAttribute parse action helper, to simplify creating filtering parse actions to attach to expressions returned by makeHTMLTags and makeXMLTags. Use withAttribute to qualify a starting tag with one or more required attribute values, to avoid false matches on common tags such as TD or DIV. - Added new examples nested.py and withAttribute.py to demonstrate the new features. - Added performance speedup to grammars using operatorPrecedence, instigated by Stefan Reichör - thanks for the feedback, Stefan! - Fixed bug/typo when deleting an element from a ParseResults by using the element's results name. - Fixed whitespace-skipping bug in wrapper classes (such as Group, Suppress, Combine, etc.) and when using setDebug(), reported by new pyparsing user dazzawazza on SourceForge, nice job! - Added restriction to prevent defining Word or CharsNotIn expressions with minimum length of 0 (should use Optional if this is desired), and enhanced docstrings to reflect this limitation. Issue was raised by Joey Tallieu, who submitted a patch with a slightly different solution. Thanks for taking the initiative, Joey, and please keep submitting your ideas! - Fixed bug in makeHTMLTags that did not detect HTML tag attributes with no '= value' portion (such as td nowrap), reported by hamidh on the pyparsing wiki - thanks! - Fixed minor bug in makeHTMLTags and makeXMLTags, which did not accept whitespace in closing tags. Download pyparsing 1.4.8 at http://sourceforge.net/projects/pyparsing/. The pyparsing Wiki is at http://pyparsing.wikispaces.com -- Paul Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - Hello, World! (English, Korean, Greek, and Spanish(new)) - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler - Python value string parser (lists, dicts, tuples, with nesting) (safe alternative to eval) - HTML tag stripper - S-expression parser - macro substitution preprocessor -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
Dick Moores [EMAIL PROTECTED] wrote http://www.redcanary.ca/view/top-programming Interesting, but I'm not sure what the criteria for top is. Is it a measure of power, popularity, usage? Scary that HTML/CSS should be so high though given its not a programming language at all! Alan G. -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
What are these stats based on? On 10/7/07, Alan Gauld [EMAIL PROTECTED] wrote: Dick Moores [EMAIL PROTECTED] wrote http://www.redcanary.ca/view/top-programming Interesting, but I'm not sure what the criteria for top is. Is it a measure of power, popularity, usage? Scary that HTML/CSS should be so high though given its not a programming language at all! Alan G. -- http://mail.python.org/mailman/listinfo/python-list -- http://www.goldwatches.com/mens/cufflinks.html http://www.jewelerslounge.com -- http://mail.python.org/mailman/listinfo/python-list
Re: supplying password to subprocess.call('rsync ...'), os.system('rsync ...')
On 10/5/07, timw.google [EMAIL PROTECTED] wrote: Hi I want to write a python script that runs rsync on a given directory and host. I build the command line string, but when I try to run subprocess.call(cmd), or p=subprocess.Popen(cmd, shell=True),or os.system(cmd), I get prompted for my login password. I expected this, but when I try to give my password, it's echoed back to the terminal and the special characters in the password is (I think) getting interpreted by the shell (zsh) I can't ssh w/o supplying a password. That's the way the security is set up here. How do I use python to do this, or do I just have to write a zsh script? SSH takes measures to ensure that passwords are typed from a keyboard (pty) rather than being piped in automatically (stdin). If SSH public key authentication (see ssh-keygen) doesn't work for you, then try ssh agent (see, ssh-add), sshpass, or something like empty-expect. If you use ssh public keys, you can also setup the public key so that only a specified command can be run, and that the public key can only be used from a specific host. This is more secure. See this page for more info: http://troy.jdmz.net/rsync/index.html Otherwise you may need to do some pty-hackery in python to fool ssh into thinking it's password is being entered from a keyboard and not a script. However, you should try public key authentication (with rsync as the only allowed command) first. Another method is to setup an ssh service on the server (perhaps in inetd). One disadvantage of this is that the rsync session (including rsync login passwords) is not encrypted. -- http://mail.python.org/mailman/listinfo/python-list
Re: supplying password to subprocess.call('rsync ...'), os.system('rsync ...')
Typo. Another method is to setup an ssh service on the server (perhaps in Should be: Another method is to setup an rsync service on the server (perhaps in -- http://mail.python.org/mailman/listinfo/python-list
Re: Mysql class works like php
Bruno Desthuilliers wrote: Andrey a écrit : Hi just a quick question about using MySQL module... are there any api / class available to give a higher level in working with Mysql in python? such as db.fetch_array(), db.fetch_rows(), db.query(), for eachrow in db.fetch_array(): You really find this higher level than Python's db-api ??? just as easy as PHP? D'oh :( // PHP: // suppose we have a valid $connection $q = mysql_query(select * from yaddayadda, $connection) if (is_resource($q)) { while($row = mysql_fetc_row($q)) { do_something_with($row); } mysql_free($q); } else { // handle the error here } # python: # suppose we have a valid connection cursor = connection.cursor() # can specify the kind of cursor here try: cursor.execute(select * from yaddayadda) except MysqlError, e: # handle error here else: for row in cursor: do_something_with(row) # not strictly necessary, you can reuse the same # cursor for another query cursor.close() As far as I'm concerned, I fail to see how PHP is higher level or easier here. Maybe You should look into sqlalchemy. I am also a newbie at that, but it allows you to do things like this (untested): sqltxt=select * from mytable result=mysession.execute(sqltxt) for r in result.fetchmany(): which pretty good mimics the 'for eachrow in db.fetch_array():' yours politely jorgen -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
On Oct 6, 2007, at 11:31 PM, goldtech wrote: Can anyone link me or explain the following: I open a file in a python script. I want the new file's location to be on the user's desktop in a Windows XP environment. fileHandle = open (., 'w' ) what I guess I'm looking for is an environmental variable that will usually be correct on most XP desktops and will work in the open statement. Or is there another way? Thanks -- http://mail.python.org/mailman/listinfo/python-list import os.path home = os.path.expanduser('~') desktop = os.path.join(home, 'Desktop') -- http://mail.python.org/mailman/listinfo/python-list
configure urllib.urlretrieve timeout
Hi.. I want to set 30 second urllib.urlretrieve timeout.. Because if urllib.urlretrieve can't connect to page wait 1-2 hour... I download the images to my server with urlretrieve if you know the better way please help me. I'm sorry my bad english.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
On Oct 7, 8:35 am, Michele Simionato [EMAIL PROTECTED] wrote: On Oct 6, 12:57 pm, Bruno Desthuilliers Michele Simionato a écrit : I looked at the source code and it seems fine to me, but I have not used it directly, not stressed it. I need a production-level WSGI session middleware and I wonder what the players are (for instance how Beaker does compare with flup?) Can't tell, but I'd trust the Pylons team on this kind of choices. They're doing good job so far AFAICT. Probably Beaker works well, but it is certainly NOT doing things as Eby recommends: http://dirtsimple.org/2007/02/wsgi-middleware-considered-harmful.html BTW, I know that Eby is asking opinions about WSGI 2.0 on the WSGI SIG and interested people may have a look there. Michele Simionato I think that Beaker is a Mako dependency. So if you use Mako, Beaker is not an option :) G -- http://mail.python.org/mailman/listinfo/python-list
Problem using subprocess.Popen on windows
Hi, I get an error that I don't understand when using the subprocess module on Windows. I guess I'm missing out something very basic. For instance, to execute and capture the output of the ms-dos dir command, I tried the following: from subprocess import * p1 = Popen([dir], stdout=PIPE) output = p1.communicate()[0] But I get a WindowsError : [Error 2] File Not Found The exact traceback is : Traceback (most recent call last): File pipe2.py, line 5, in module p1 = Popen([dir], stdout=PIPE) File C:\Python25\lib\subprocess.py, line 593, in __init__ errread, errwrite) File C:\Python25\lib\subprocess.py, line 815, in _execute_child startupinfo) WindowsError: [Error 2] Le fichier spÚcifiÚ est introuvable Do you know what is missing in my code? Thanks a lot jorma -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
But the question is when will the cheap hosting company's start to host normal python files! On 10/7/07, genro [EMAIL PROTECTED] wrote: On Oct 7, 8:35 am, Michele Simionato [EMAIL PROTECTED] wrote: On Oct 6, 12:57 pm, Bruno Desthuilliers Michele Simionato a écrit : I looked at the source code and it seems fine to me, but I have not used it directly, not stressed it. I need a production-level WSGI session middleware and I wonder what the players are (for instance how Beaker does compare with flup?) Can't tell, but I'd trust the Pylons team on this kind of choices. They're doing good job so far AFAICT. Probably Beaker works well, but it is certainly NOT doing things as Eby recommends: http://dirtsimple.org/2007/02/wsgi-middleware-considered-harmful.html BTW, I know that Eby is asking opinions about WSGI 2.0 on the WSGI SIG and interested people may have a look there. Michele Simionato I think that Beaker is a Mako dependency. So if you use Mako, Beaker is not an option :) G -- http://mail.python.org/mailman/listinfo/python-list -- http://www.goldwatches.com/mens/cufflinks.html http://www.jewelerslounge.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + Shoutpy + Twisted Locks
On Oct 6, 4:21 am, Gabriel Genellina [EMAIL PROTECTED] wrote: En Fri, 05 Oct 2007 04:55:55 -0300, exhuma.twn [EMAIL PROTECTED] escribi?: [...] What I found is that libshout is blocking, which should be fine as the whole thing runs in it's separate thread. But the application hangs nevertheless while streaming. This effectively blocks out the other thread that checks the player status, which then fails to append new songs to the queue. So only one song is played when streaming. The other threads in my application run fine and don't block the rest of the app. So I guess, that the main problem is that blocking occurs outside the python world and inside the libshout world. Only one thread at a time may be executing Python code; the Global Interpreter Lock (GIL) ensures the mutual exclusion. Extension modules (written in C) may use the macros Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS to release/acquire the GIL before/after an external blocking call. I don't know libshout, or how you are doing the binding python-libshout, but if your analysis is correct it means that the code is not releasing the GIL at the appropiate points. -- Gabriel Genellina Hmmm... ok. I suppose rewriting the whole thing using twisted's deferreds could then solve the problem. Which are basically nothing more than callbacks with a weird name ;) Unfortunately this means that I have to re-think a lot. But in the end I suppose it will pay off. Thanks for taking the time and reading my little essay Gabriel ;) -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pyrex 0.9.6
Pyrex 0.9.6 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ There is a *lot* of new stuff in this version, too much to fit into this announcement. Read all about it here: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/changes-0.9.6.html 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. -- http://mail.python.org/mailman/listinfo/python-list
Newbie packages Q
Hi All, I do not understand the packages system in python. I have read this http://docs.python.org/tut/node8.html a 100 times and I can not get it to work. I make a test app like this: *** Test/ __init__.py (a empty file) apack/ __init__.py (a empty file) atest.py bpack/ __init__.py (a empty file) btest.py *** atest.py: from Test.bpack import btest def printA(): print This is Atest from Apack def printbtest(): print btest.printB() print printA() print printbtest() *** btest.py: from Test.apack import atest def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printatest() *** All I get is an import error: ImportError: cannot import name x I can remove the import statements an use the Test package quit normal but when I try to make intra-pacage references I get the import error. I must be missing something, could any one point me at what. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
a good website for softwares,movies and music etc.
www.space666.com support!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter text widget
You can scroll, but you can't see the cursor. Use for x in range(30): text.insert(END, %3d % x + i) to check. ED I tried it w/the line numbers. On my system I see 0-23. But there is no way to scroll. Still the same result. -- http://mail.python.org/mailman/listinfo/python-list
Re: Off Topic: Gmail hates newsgroups!!!
I just delete what people say.. so.. no at all :D. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem using subprocess.Popen on windows
jorma kala wrote: I get an error that I don't understand when using the subprocess module on Windows. I guess I'm missing out something very basic. For instance, to execute and capture the output of the ms-dos dir command, I tried the following: from subprocess import * p1 = Popen([dir], stdout=PIPE) output = p1.communicate()[0] But I get a WindowsError : [Error 2] File Not Found That's because dir isn't an executable file in its own right, merely a subcommand of the command shell. Do this: code from subprocess import * p1 = Popen (dir, shell=True, stdout=PIPE) print p1.communicate ()[0] /code TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Top Programming Languages of 2013
Alan Gauld wrote: Dick Moores [EMAIL PROTECTED] wrote http://www.redcanary.ca/view/top-programming Interesting, but I'm not sure what the criteria for top is. Is it a measure of power, popularity, usage? Scary that HTML/CSS should be so high though given its not a programming language at all! Alan G. Besides all that, we are programmers not fashion models. Who cares which is the top language, leave that for the top models and such. Our trade is code, not fashion. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
This is really a Windows question, not a Python question. You should have been able to figure it out yourself by examining existing environment variables. I agree, you're right. I learn more by figuring out the code myself. After Google briefly: In a DOS box type: SET This was too easy - sorry. Something like the code below should work for you if the standard environment variables haven't been hosed. -- import os Filename = os.getenv(HOMEDRIVE) + os.getenv(HOMEPATH) + \\Desktop \MyNewFile f = file(Filename, w) f.write(Here's a file on the desktop\n) f.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
Lawrence Oluyede wrote: Jorge Godoy [EMAIL PROTECTED] wrote: What is good, since a lot of good things from Pylons will work with TG and a lot of good TG things will remain (and possibly be compatible with Pylons). If you take a better look at the next version, you'll also see that the major concern was with WSGI support and reinventing / rewriting the wheel (what TG developers don't want to do all the time). Not reinventing the wheel just don't feel as a universal dogma to me. I developed quite a bit with Django and I was glad they started from scratch. On the paper reusing different and existing projects is great but not always is good or done the right way. Anyway I don't know TG at all so I'm speaking in a figurative way. We (Michele, myself and our colleagues) have a series of stuff we need to stick to so the choosing of a web framework ain't that easy. Most of the frameworks are a vision of the author of how to do things from scratch but a framework (by definition an evolution of a library) is not always meant to be used when the scratch is far from your starting point. I'd like to read some commenting of Michele's thoughts, they would be really useful. :-) Porting existing web applications to new architectures requires more than just transliteration, since you lose some metaphors available only in the donor system and may therefore need to take advantage of new idioms in the new environment to compensate. I spent some time trying to re-architect the code from Python Web Programming in TurboGears. That was difficult not because TG is a bad system but because there was an impedance mismatch between the original code's framework and the way TG does things. I guess I would have similar problems with Django. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
Matimus wrote: On Oct 6, 8:31 pm, goldtech [EMAIL PROTECTED] wrote: Can anyone link me or explain the following: I open a file in a python script. I want the new file's location to be on the user's desktop in a Windows XP environment. fileHandle = open (., 'w' ) what I guess I'm looking for is an environmental variable that will usually be correct on most XP desktops and will work in the open statement. Or is there another way? Thanks I've always used 'USERPROFILE'. I'm not sure how standard it is, but I have never run into any issues. Code for your perusal: [code] import os, os.path prof_path = os.environ['USERPROFILE'] filename = os.path.join(prof_path,'Desktop','filename.txt') f = open(filename,'w') try: # do stuff with f finally: f.close() [/code] Matt You are assuming the system is not localized, that won't work if you distribute your applications internationally. In my system it is not Desktop, it is Escritorio, and I guess it will vary with every locale. Does someone know a way to find out what name does the desktop have? -- http://mail.python.org/mailman/listinfo/python-list
Putting a line from a text file into a variable, then moving to next line
I'm not really sure how readline() works. Is there a way to iterate through a file with multiple lines and then putting each line in a variable in a loop? -- http://mail.python.org/mailman/listinfo/python-list
Re: configure urllib.urlretrieve timeout
Abandoned wrote: Hi.. I want to set 30 second urllib.urlretrieve timeout.. Because if urllib.urlretrieve can't connect to page wait 1-2 hour... I download the images to my server with urlretrieve if you know the better way please help me. I'm sorry my bad english.. import socket socket.setdefaulttimeout(30) at the top of your program might help. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
James Matthews wrote: What are these stats based on? This survey here: http://app.sgizmo.com/reports/4762/6895/QJK8UD9C9371P37EOQ7V8OIC1RP39O/ Now how was this survey advertised? Who was asked to participate? Dunno. Clearly not MacFans, given the high number of 1 scores given to Objective C + cocoa. Interestingly, python got the most votes (619--the next highest were 518 (Java) and 505 (Ruby)), the highest average score (8.5 out of 10, followed by HTML/CSS with 7.6 and Javascript with 7.3), *and* the highest percentage of 10 scores, (49.3%, with HTML/CSS second with 28.6%). Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Re: Putting a line from a text file into a variable, then moving to next line
Vernon Wenberg III wrote: I'm not really sure how readline() works. Is there a way to iterate through a file with multiple lines and then putting each line in a variable in a loop? To know how something works you can always check the docs about this specific functionality: a = open('a') help(a.readline) Help on built-in function readline: readline(...) readline([size]) - next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. help(a.readlines) Help on built-in function readlines: readlines(...) readlines([size]) - list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. If you are creating new variables on every loop iteration you might be interested in two things: - you can loop directly through the file, on a line by line basis - you can assign the read line to a an array -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
MarkyMarc wrote: Hi All, I do not understand the packages system in python. I have read this http://docs.python.org/tut/node8.html a 100 times and I can not get it to work. I make a test app like this: *** Test/ __init__.py (a empty file) apack/ __init__.py (a empty file) atest.py bpack/ __init__.py (a empty file) btest.py *** atest.py: from Test.bpack import btest def printA(): print This is Atest from Apack def printbtest(): print btest.printB() print printA() print printbtest() *** btest.py: from Test.apack import atest def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printatest() *** All I get is an import error: ImportError: cannot import name x I can remove the import statements an use the Test package quit normal but when I try to make intra-pacage references I get the import error. I must be missing something, could any one point me at what. Thank you. Would it hep to observe that the atest and btest submodules attemot to import each other? There is no reason I can see for apack and bpack to be subpackages. Why not just rename atest.py as apack.py at the same level as the Test package's __init__.py, and in the same way make btest.py bpack.py. Then the __init__.py can do: from apack import printA from bpack import printB and your main program can do import Test Test.printA(...) regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it -- http://mail.python.org/mailman/listinfo/python-list
Re: Putting a line from a text file into a variable, then moving to next line
I'm not really sure how readline() works. Is there a way to iterate through a file with multiple lines and then putting each line in a variable in a loop? You can use readlines() to get the whole line (including the newline): lines = file('x.txt').readlines() or you can iterate over the file building a list without the newline: lines = [line.rstrip('\n') for line in file('x.txt')] Thus, line[0] will be the first line in your file, line[1] will be the second, etc. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
Steve Holden a écrit : Lawrence Oluyede wrote: (snip) We (Michele, myself and our colleagues) have a series of stuff we need to stick to so the choosing of a web framework ain't that easy. Most of the frameworks are a vision of the author of how to do things from scratch but a framework (by definition an evolution of a library) is not always meant to be used when the scratch is far from your starting point. Porting existing web applications to new architectures requires more than just transliteration, since you lose some metaphors available only in the donor system and may therefore need to take advantage of new idioms in the new environment to compensate. I spent some time trying to re-architect the code from Python Web Programming in TurboGears. That was difficult not because TG is a bad system but because there was an impedance mismatch between the original code's framework and the way TG does things. I guess I would have similar problems with Django. Indeed. But AFAICT, Lawrence and Michele problems is not to port an existing web application, but to choose a web framework that will play well with their existing *system* (RDBMS, existing apps and libs etc). Which is quite another problem, and may eliminate some otherwise pretty good frameworks for compatibility reasons (DBMS support and other issues). (please Michele or Lawrence correct me if I'm wrong...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Mysql class works like php
gardsted a écrit : Bruno Desthuilliers wrote: Andrey a écrit : Hi just a quick question about using MySQL module... are there any api / class available to give a higher level in working with Mysql in python? such as db.fetch_array(), db.fetch_rows(), db.query(), for eachrow in db.fetch_array(): (snip) Maybe You should look into sqlalchemy. I am also a newbie at that, but it allows you to do things like this (untested): sqltxt=select * from mytable result=mysession.execute(sqltxt) for r in result.fetchmany(): which pretty good mimics the 'for eachrow in db.fetch_array():' SQLAlchemy is quite a good package (and *way* higher level than anything in PHP), but you don't need it to do the above. Any db-api compliant package will do: sql = SELECT * FROM yaddayadda cursor.execute(sql) for row in cursor.fetchall(): # code here -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
On Oct 7, 8:36 am, Bruno Desthuilliers Indeed. But AFAICT, Lawrence and Michele problems is not to port an existing web application, but to choose a web framework that will play well with their existing *system* (RDBMS, existing apps and libs etc). Which is quite another problem, and may eliminate some otherwise pretty good frameworks for compatibility reasons (DBMS support and other issues). (please Michele or Lawrence correct me if I'm wrong...) Yes, our main concern is compatibility with the existing system: for instance, one constraint is the MS SQL database. Having said that, we would like to port parts of a Zope application to the new framework, but I do not expect this to be particularly difficult for the parts we want to migrate since they are not really using Zope features. Other parts instead would require a very substantial rewrite so for the moment I think they will stay in Zope. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Putting a line from a text file into a variable, then moving to next line
On Sun, 07 Oct 2007 12:00:44 +, Vernon Wenberg III wrote: I'm not really sure how readline() works. Is there a way to iterate through a file with multiple lines and then putting each line in a variable in a loop? There are always more ways how to do it.. one of them is: f = open(filename) for line in f: # you may then strip the newline: line = line.strip('\n') # do anything you want with the line f.close() -- http://mail.python.org/mailman/listinfo/python-list
Pil image module, mode bug..
Hi.. I find the picture color with: im=Image.open(/%s %name) color=im.mode #p=black beyaz rgb=color L=grey This usually work true but in these pictures: http://malatya.meb.gov.tr/images/alt/ilsis_logo.gif http://malatya.meb.gov.tr/images/meb.gif Say me P (blackwhite) but these pictures are color.. What is the reason of this ? I'm sorry my bad english -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
Wildemar Wildenburger [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: While I agree that the word free implies free of monetary cost to many people societies, that is by no means set in stone (talk to native americans, blacks, jews, palestinians, etc. about the word free, see what they have to say). Words are defined by popular usage. In popular usage, the meaning of free as an adjective depends on the context. If the adjective is applied to people, it means the opposite of slavery or imprisonment. If it's applied to something other than people, it means free as in beer. For example, a dog with no owner, wandering freely (adverb), would not be called a free dog (adjective), to mean possessing freedom. Free dog means free as in beer. Likewise, in popular usage, free software means free as in beer. People who use it with a different meaning are vainly trying to change its meaning. But the meanings of words can't be arbitrarily changed, just by dictating different meanings. The meaning has to be adopted by popular usage, which free-as-in-GPL software has not been. Therefore, I propose, using dog freedom as our logic, we call it stray software. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
On Oct 7, 2:16 pm, Steve Holden [EMAIL PROTECTED] wrote: Would it hep to observe that the atest and btest submodules attemot to import each other? There is no reason I can see for apack and bpack to be subpackages. Why not just rename atest.py as apack.py at the same level as the Test package's __init__.py, and in the same way make btest.py bpack.py. Then the __init__.py can do: from apack import printA from bpack import printB and your main program can do import Test Test.printA(...) This is away of doing it, but not a very Package way. The situation is I want to make a package split up in sub dir's. And each sub dir need to call the other. And I cant see why it will not work, the way i do it. And the atest and btest, shouldn't they be able to import each other?? -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Pyrex 0.9.6
Greg Ewing wrote: Pyrex 0.9.6 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ There is a *lot* of new stuff in this version, too much to fit into this announcement. Read all about it here: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/changes-0.9.6.html 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. Some of the doc\Manual files seem to be missing eg source_files. I was browsing hoping to find an answer to the question Do I need a C compiler to use Pyrex, if so, which one? Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Override 'and' and 'or'
Is it possible to override 'and' and/or 'or'? I cannot find a special method for it... __and__ and __rand__ and __or__ and __ror__ are for binary manipulation... any proposals? Have marvelous sunday, Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: Pil image module, mode bug..
On Sun, 07 Oct 2007 06:03:06 -0700, Abandoned wrote: Hi.. I find the picture color with: im=Image.open(/%s %name) color=im.mode #p=black beyaz rgb=color L=grey This usually work true but in these pictures: http://malatya.meb.gov.tr/images/alt/ilsis_logo.gif http://malatya.meb.gov.tr/images/meb.gif Say me P (blackwhite) but these pictures are color.. What is the reason of this ? I'm sorry my bad english P does mean palette, blackwhite is a special case of palette, with two colors. -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Dekker [EMAIL PROTECTED] wrote: Is it possible to override 'and' and/or 'or'? I cannot find a special method for it... __and__ and __rand__ and __or__ and __ror__ are for binary manipulation... any proposals? If you want to customize the truth value testing you have to implement __nonzero__ __nonzero__( self) Called to implement truth value testing, and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined (see below). If a class defines neither __len__() nor __nonzero__(), all its instances are considered true. Keep in mind the relation between __len__ and __nonzero__ ps. why you need to customize such a thing? -- Lawrence, oluyede.org - neropercaso.it It is difficult to get a man to understand something when his salary depends on not understanding it - Upton Sinclair -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Dekker a écrit : Is it possible to override 'and' and/or 'or'? I cannot find a special method for it... __and__ and __rand__ and __or__ and __ror__ are for binary manipulation... any proposals? http://docs.python.org/ref/customization.html __nonzero__(self) Called to implement truth value testing, and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined (see below). If a class defines neither __len__() nor __nonzero__(), all its instances are considered true. Not that in Python, 'and' don't yield bools: aa and bb 'bb' aa and None # yields None aa and 0 0 aa or bb 'aa' 0 or bb 'bb' None or bb 'bb' aa or 0 'aa' aa or None 'aa' HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
On Sun, 07 Oct 2007 13:52:15 +, Dekker wrote: Is it possible to override 'and' and/or 'or'? Not without hacking the Python source code, in which case what you've got is no longer Python. Why do you want to do so? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Dekker wrote: Is it possible to override 'and' and/or 'or'? I cannot find a special method for it... __and__ and __rand__ and __or__ and __ror__ are for binary manipulation... any proposals? Have marvelous sunday, Marco I guess you're looking for __nonzero__() URL:http://docs.python.org/ref/customization.html. You don't actually override the boolean operators, you just tell the object how to tell others if it evaluates to True or False (Truth-testing isn't a binary operation; cf. bool(my_object)). /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
MarkyMarc a écrit : (snip) And the atest and btest, shouldn't they be able to import each other?? import is a statement. It's executed, like any other top-level code, when the module is imported (or the script loaded into the interpreter if it's called directly). So if A.py imports B.py and B.py imports A.py, you do have a circular reference that can't be solved. Anyway, circular dependencies are Bad(tm), so you *don't* want such a situation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Wildemar Wildenburger wrote: [whate everyone else wrote :(] /W Dangit! 4th of 4. Gotta type quicker. /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
On Oct 7, 4:24 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: MarkyMarc a écrit : (snip) And the atest and btest, shouldn't they be able to import each other?? import is a statement. It's executed, like any other top-level code, when the module is imported (or the script loaded into the interpreter if it's called directly). So if A.py imports B.py and B.py imports A.py, you do have a circular reference that can't be solved. Anyway, circular dependencies are Bad(tm), so you *don't* want such a situation. Yes it is bad and I would not do it in production. But shouldn't I be able to call one module from another module inside a package? -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
On Sun, 07 Oct 2007 16:24:35 +0200, Wildemar Wildenburger wrote: Wildemar Wildenburger wrote: [whate everyone else wrote :(] /W Dangit! 4th of 4. Gotta type quicker. That's okay, in two weeks time there will be 139 messages in this thread, it will have devolved into an argument about whether Python's truth- testing semantics are better or worse than whatever Java/Lisp/Haskell/ Ruby does, and *then* somebody will respond to the Original Poster with customize the __and__ and __or__ methods of your class. Happens every time. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
On 7 Okt., 16:19, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sun, 07 Oct 2007 13:52:15 +, Dekker wrote: Is it possible to override 'and' and/or 'or'? Not without hacking the Python source code, in which case what you've got is no longer Python. Why do you want to do so? -- Steven. Well I think it is not possible what I wanted to achieve. By overriding the and and or keyword I wanted to return a new object: SqlValueInt(4) and SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) This is only possible for: +, -, /, *, , =, ... Well... I have to live with the (binary) __and__, __or__ option and the user has to write: SqlValueInt(4) SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) Thanks for your input, but __nonzero__ is not of any help in this case... I want to abuse the magic functions for some transformations and not some evaluation. Marco -- http://mail.python.org/mailman/listinfo/python-list
weakrefs and bound methods
Hi. I have a problem with weak refs and bound methods. The best explanation for the problem is a short bit of code. I have the three classes Wrapper, Foo and Bar: import weakref class Wrapper(object): def __init__(self,x): self.x = weakref.ref(x) def __call__(self,*args,**kwargs): x = self.x() if x is None: print lost reference else: return x(*args,**kwargs) class Foo(object): def __init__(self): self._methods = set() self._methods.add(Wrapper(self._foo)) def _foo(self): print _foo def callMethods(self): for method in self._methods: method() def __del__(self): print del Foo class Bar(object): def __init__(self): self._methods = set() self._methods.add(self._foo) def _foo(self): print _foo def callMethods(self): for method in self._methods: method() def __del__(self): print del Bar Now look what happens when I do this: f=Foo() f.callMethods() lost reference del f del Foo b=Bar() b.callMethods() _foo del b Foo looses the reference to its method but Bar on the other hand has a refloop and never gets deleted. Does anyone know what happens here? How can I write such classes without refloop and without lost reference? I'm using: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 -panzi -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
When I change the class Wrapper to following, the class Foo works: class Wrapper(object): def __init__(self,x): self.func_name = x.func_name self.x = weakref.ref(x.im_self) def __call__(self,*args,**kwargs): x = self.x() if x is None: print lost reference else: return getattr(x,self.func_name)(*args,**kwargs) But that's ugly. Any better idea? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter text widget
On Oct 6, 11:18 pm, goldtech [EMAIL PROTECTED] wrote: I thought the DISABLED made it so I could not edit it. But it also makes it so I can not scroll down. If you make the window smaller than the content then try to put a cursor in there to use up/down arrow you can't. What I want is not to be able to change text content, but no other action is disabled. Is this complicated to do? Thanks. from Tkinter import * root = Tk() text = Text(root, font=(Courier)) text.pack() i='123456789abcdefghijklmnopqrstuvwxyz\n' for x in range(30): text.insert(END, i) text.config(state=DISABLED) mainloop() I just tried this script. You can select text and if you drap the selection outside the window then scrolling occurs, also Tk's default behavior of scrolling with the middle button still works (i.e. click- and-drag with the middle button to scroll.) The arrow keys don't scroll the window, but that's because either A. the Text widget won't take 'focus' while disabled -or- B. the arrow keys et. al. work through the cursor which isn't there in disabled mode. I'm guessing and I'm not sure which is right, or if it's something else entirely. Try adding a scrollbar widget and tying it to the Text (there are webpages out there that describe how to do this), I think this widget would still get focus (since it's NOT disabled) and therefore be able to scroll the Text. Or try explicitly binding the arrow keys to scroll commands. ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
MarkyMarc wrote: On Oct 7, 4:24 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: MarkyMarc a écrit : import is a statement. It's executed, like any other top-level code, when the module is imported (or the script loaded into the interpreter if it's called directly). So if A.py imports B.py and B.py imports A.py, you do have a circular reference that can't be solved. Anyway, circular dependencies are Bad(tm), so you *don't* want such a situation. Yes it is bad and I would not do it in production. But shouldn't I be able to call one module from another module inside a package? Thats not the point. Intra-package references are (of course) perfectly possible, the problem here are *circular* references (as Bruno explained). Secondly, if you have such circular dependencies, I would argue that your package design might need a little reconsideration. Why do 2 seperate modules need *each other*? To me that sounds like 2 modules begging to be combined. /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Dekker wrote: Well... I have to live with the (binary) __and__, __or__ option and the user has to write: SqlValueInt(4) SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) Thanks for your input, but __nonzero__ is not of any help in this case... I want to abuse the magic functions for some transformations and not some evaluation. Then again, you could always write a function that does this. I know, I know ... /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
IMO this is not as much a framework comparison rather than an evaluation of the individual components that make up Pylons. The framework is the sum of all its parts. Programmers should not need to know that that a package named Beaker is used for sessions, Routes for url mapping, PasteDeploy for whatever. This is the weakness of all glue-type frameworks i.e. TG and Pylons. It makes them look like they are duct-taped together. The more important question are whether the sessions actually work properly: i.e does session data persist through a server restart? Where is the session data stored: in memory, files, database and so on. The choice of templating language should be a non issue. Any half decent framework should allow you to use any other templating engine with ease. ... even python as you seem to prefer i. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
On Oct 7, 5:22 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: MarkyMarc wrote: On Oct 7, 4:24 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: MarkyMarc a écrit : import is a statement. It's executed, like any other top-level code, when the module is imported (or the script loaded into the interpreter if it's called directly). So if A.py imports B.py and B.py imports A.py, you do have a circular reference that can't be solved. Anyway, circular dependencies are Bad(tm), so you *don't* want such a situation. Yes it is bad and I would not do it in production. But shouldn't I be able to call one module from another module inside a package? Thats not the point. Intra-package references are (of course) perfectly possible, the problem here are *circular* references (as Bruno explained). Secondly, if you have such circular dependencies, I would argue that your package design might need a little reconsideration. Why do 2 seperate modules need *each other*? To me that sounds like 2 modules begging to be combined. /W It was simply to make a point. But then lets say the to files looks like this: *** atest.py: def printA(): print This is Atest from Apack *** btest.py: from Test.apack import atest def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printB() print printatest() *** Now only one of them imports the other, and this most be the simplest way of illustrating the intra-package references. But how do I get this to work? -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
On Oct 7, 4:48 pm, Dekker [EMAIL PROTECTED] wrote: On 7 Okt., 16:19, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sun, 07 Oct 2007 13:52:15 +, Dekker wrote: Is it possible to override 'and' and/or 'or'? Not without hacking the Python source code, in which case what you've got is no longer Python. Why do you want to do so? -- Steven. Well I think it is not possible what I wanted to achieve. By overriding the and and or keyword I wanted to return a new object: SqlValueInt(4) and SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) This is only possible for: +, -, /, *, , =, ... Well... I have to live with the (binary) __and__, __or__ option and the user has to write: SqlValueInt(4) SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) Thanks for your input, but __nonzero__ is not of any help in this case... I want to abuse the magic functions for some transformations and not some evaluation. Marco You can see what and and or are actually doing: import dis dis.dis(lambda: x or y and z) 1 0 LOAD_GLOBAL 0 (x) 3 JUMP_IF_TRUE11 (to 17) 6 POP_TOP 7 LOAD_GLOBAL 1 (y) 10 JUMP_IF_FALSE4 (to 17) 13 POP_TOP 14 LOAD_GLOBAL 2 (z) 17 RETURN_VALUE Here you can see nicely that they are not implemented as specialized opcodes but being compiled to jumps. This causes their lazy nature. If and would be implemented as a normal ( eager ) operator a statement like: if l and l[0] == 2: BLOCK would raise an IndexError if l is empty. -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Steven D'Aprano a écrit : On Sun, 07 Oct 2007 16:24:35 +0200, Wildemar Wildenburger wrote: Wildemar Wildenburger wrote: [whate everyone else wrote :(] /W Dangit! 4th of 4. Gotta type quicker. That's okay, in two weeks time there will be 139 messages in this thread, it will have devolved into an argument about whether Python's truth- testing semantics are better or worse than whatever Java/Lisp/Haskell/ Ruby does, and *then* somebody will respond to the Original Poster with customize the __and__ and __or__ methods of your class. keyboard !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
On Oct 7, 8:05 am, Dick Moores [EMAIL PROTECTED] wrote: http://www.redcanary.ca/view/top-programming Dick Moores Despite my doubts that Ajax and .NET will be programming languages in 2013 a more interesting question is: what could push Python forward s.t. it eats such a large piece of the PL cake? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
MarkyMarc wrote: *** atest.py: def printA(): print This is Atest from Apack *** btest.py: from Test.apack import atest def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printB() print printatest() *** Now only one of them imports the other, and this most be the simplest way of illustrating the intra-package references. But how do I get this to work? This doesn't work? What error do you get? I've never done too complicated packaging stuff, and can't raelly testdrive your example right now. Maybe you have to look into sys.path if Test can be found at all. Or maybe you have to play with the import statement (from apack import atest?). I'm just guessing here; importing continues to remain going on being a mystery to me. /W -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Pyrex 0.9.6
Colin J. Williams schrieb: Greg Ewing wrote: Pyrex 0.9.6 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ There is a *lot* of new stuff in this version, too much to fit into this announcement. Read all about it here: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/changes-0.9.6.html 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. Some of the doc\Manual files seem to be missing eg source_files. I was browsing hoping to find an answer to the question Do I need a C compiler to use Pyrex, if so, which one? Can't say that anything about the reason for the missing files - but one thing is for sure: you need one. And I _presume_ it's the one distutils would chose, so it depends on your python-build. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
Kay Schluehr wrote: On Oct 7, 8:05 am, Dick Moores [EMAIL PROTECTED] wrote: http://www.redcanary.ca/view/top-programming Dick Moores Despite my doubts that Ajax and .NET will be programming languages in 2013 a more interesting question is: what could push Python forward s.t. it eats such a large piece of the PL cake? import friends import sex try: sex.have() except ErrectionError, PrematureError: pass finally: sex.brag(friends) -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
[EMAIL PROTECTED] wrote: Wildemar Wildenburger [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: While I agree that the word free implies free of monetary cost to many people societies, that is by no means set in stone (talk to native americans, blacks, jews, palestinians, etc. about the word free, see what they have to say). Words are defined by popular usage. In popular usage, the meaning of free as an adjective depends on the context. If the adjective is applied to people, it means the opposite of slavery or imprisonment. If it's applied to something other than people, it means free as in beer. For example, a dog with no owner, wandering freely (adverb), would not be called a free dog (adjective), to mean possessing freedom. Free dog means free as in beer. Likewise, in popular usage, free software means free as in beer. People who use it with a different meaning are vainly trying to change its meaning. But the meanings of words can't be arbitrarily changed, just by dictating different meanings. The meaning has to be adopted by popular usage, which free-as-in-GPL software has not been. Therefore, I propose, using dog freedom as our logic, we call it stray software. But that sounds like software that may once have had a good home, but then one day a pack of stray software came into town and called to its wild side, so it left the PC of its birth ... you get the idea. Interestingly, this issue does ultimately hinge on ideas of property and ownership. Amazon (or their lawyers and marketing department together) would like you to believe that the idea of being able to order a product with a single click is protectable intellectual property, but ultimately it will be agreed, I predict, that such claims will fail on the grounds of obviousness of invention. though in a country where they regularly show fifth graders to be smarter than adults on network TV one can never be sure. A tide is turning in the world of IP, but only just, and so the ebb is hardly yet underway. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline so I couldn't cat it -- http://mail.python.org/mailman/listinfo/python-list
Re: Override 'and' and 'or'
Kay Schluehr schrieb: On Oct 7, 4:48 pm, Dekker [EMAIL PROTECTED] wrote: On 7 Okt., 16:19, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sun, 07 Oct 2007 13:52:15 +, Dekker wrote: Is it possible to override 'and' and/or 'or'? Not without hacking the Python source code, in which case what you've got is no longer Python. Why do you want to do so? -- Steven. Well I think it is not possible what I wanted to achieve. By overriding the and and or keyword I wanted to return a new object: SqlValueInt(4) and SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) This is only possible for: +, -, /, *, , =, ... Well... I have to live with the (binary) __and__, __or__ option and the user has to write: SqlValueInt(4) SqlValueInt(5) -- SqlOpAnd(SqlValueInt(4), SqlValueInt(5)) Thanks for your input, but __nonzero__ is not of any help in this case... I want to abuse the magic functions for some transformations and not some evaluation. Marco You can see what and and or are actually doing: import dis dis.dis(lambda: x or y and z) 1 0 LOAD_GLOBAL 0 (x) 3 JUMP_IF_TRUE11 (to 17) 6 POP_TOP 7 LOAD_GLOBAL 1 (y) 10 JUMP_IF_FALSE4 (to 17) 13 POP_TOP 14 LOAD_GLOBAL 2 (z) 17 RETURN_VALUE Here you can see nicely that they are not implemented as specialized opcodes but being compiled to jumps. This causes their lazy nature. If Very cool, didn't know that. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
On Oct 7, 5:49 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: MarkyMarc wrote: *** atest.py: def printA(): print This is Atest from Apack *** btest.py: from Test.apack import atest def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printB() print printatest() *** Now only one of them imports the other, and this most be the simplest way of illustrating the intra-package references. But how do I get this to work? This doesn't work? What error do you get? I've never done too complicated packaging stuff, and can't raelly testdrive your example right now. Maybe you have to look into sys.path if Test can be found at all. Or maybe you have to play with the import statement (from apack import atest?). I'm just guessing here; importing continues to remain going on being a mystery to me. /W I get no module name Test.apack. But if I print the sys.path just before importing the Test.apack, I have this: /python/Test/bpack So Test is in my path. But it seems like it will not look up the path but only down. And there by do not read the __init__.py files. But I might be wrong. Anyone that can explain me how this import and packaging in python works?? -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
On Oct 7, 11:54 am, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Kay Schluehr wrote: On Oct 7, 8:05 am, Dick Moores [EMAIL PROTECTED] wrote: http://www.redcanary.ca/view/top-programming Dick Moores Despite my doubts that Ajax and .NET will be programming languages in 2013 a more interesting question is: what could push Python forward s.t. it eats such a large piece of the PL cake? import friends import sex try: sex.have() except ErrectionError, PrematureError: pass finally: sex.brag(friends) Traceback (most recent call last): File stdin, line 1, in module KeyError: 'woman' -- http://mail.python.org/mailman/listinfo/python-list
Re: Pil image module, mode bug..
On Oct 7, 4:47 pm, Michal Bozon [EMAIL PROTECTED] wrote: On Sun, 07 Oct 2007 06:03:06 -0700, Abandoned wrote: Hi.. I find the picture color with: im=Image.open(/%s %name) color=im.mode #p=black beyaz rgb=color L=grey This usually work true but in these pictures: http://malatya.meb.gov.tr/images/alt/ilsis_logo.gif http://malatya.meb.gov.tr/images/meb.gif Say me P (blackwhite) but these pictures are color.. What is the reason of this ? I'm sorry my bad english P does mean palette, blackwhite is a special case of palette, with two colors. How can i understand the picture color ? (black white or color or grey) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
MarkyMarc a écrit : (snip) It was simply to make a point. But then lets say the to files looks like this: *** atest.py: def printA(): print This is Atest from Apack *** btest.py: from Test.apack import atest FWIW, better to stick to all_lower names for packages and modules. def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printB() print printatest() *** Now only one of them imports the other, and this most be the simplest way of illustrating the intra-package references. But how do I get this to work? You failed to specify how your files are organized, and what is not working. But anyway, if - atest.py is in wherever/Test/apack, - both Test and apack have a __init__.py - wherever is in the sys.path, then this should just work AFAICT. -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
On Oct 7, 11:00?am, [EMAIL PROTECTED] wrote: On Oct 7, 11:54 am, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Kay Schluehr wrote: On Oct 7, 8:05 am, Dick Moores [EMAIL PROTECTED] wrote: http://www.redcanary.ca/view/top-programming Dick Moores Despite my doubts that Ajax and .NET will be programming languages in 2013 a more interesting question is: what could push Python forward s.t. it eats such a large piece of the PL cake? import friends import sex try: sex.have() except ErrectionError, PrematureError: pass finally: sex.brag(friends) Traceback (most recent call last): File stdin, line 1, in module KeyError: 'woman' Looks like 'men' then. -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter question
Hendrik van Rooyen wrote: Kevin Walzer [EMAIL PROTECTED] wrote: I find pack to be more flexible than grid, so I prefer it for complex layouts. grid is better for simple layouts. *does a double take* are you serious? - my experience is that pack is only good for simple single row or single column stuff. - Hendrik Well, I guess it depends on your viewpoint. I find pack flexible because it allows me to think in terms of top, bottom, right, and left in terms of arranging UI elements--it's an elegant way to do it in my view. I tend to use grid if I have, say, a window with several preference items: a label, an entry field, and a button, all arranged in rows. grid is better for stuff like that, I agree. See http://www.codebykevin.com/blosxom/business/phynchronicity-new.png: this is an application I develop. The layout is all handled by pack and paned windows. Where you you use grid in a layout like this? -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter question
Kevin Walzer wrote: Well, I guess it depends on your viewpoint. I find pack flexible because it allows me to think in terms of top, bottom, right, and left in terms of arranging UI elements--it's an elegant way to do it in my view. I tend to use grid if I have, say, a window with several preference items: a label, an entry field, and a button, all arranged in rows. grid is better for stuff like that, I agree. See http://www.codebykevin.com/blosxom/business/phynchronicity-new.png: this is an application I develop. The layout is all handled by pack and paned windows. Where you you use grid in a layout like this? That should be: http://www.codebykevin.com/blosxom/business/phynchronicity-new.png Sorry. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
On Oct 7, 6:04 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: MarkyMarc a écrit : (snip) It was simply to make a point. But then lets say the to files looks like this: *** atest.py: def printA(): print This is Atest from Apack *** btest.py: from Test.apack import atest FWIW, better to stick to all_lower names for packages and modules. def printB(): print This is Btest from Bpack def printatest(): print atest.printA() print printB() print printatest() *** Now only one of them imports the other, and this most be the simplest way of illustrating the intra-package references. But how do I get this to work? You failed to specify how your files are organized, and what is not working. But anyway, if - atest.py is in wherever/Test/apack, - both Test and apack have a __init__.py - wherever is in the sys.path, then this should just work AFAICT. If you se me first post you will see have me files are organized. But like this: Test/ __init__.py (a empty file) apack/ __init__.py (a empty file) atest.py bpack/ __init__.py (a empty file) btest.py And also in me first post(and others), all I get is an import error: ImportError: cannot import name apack. And sys.path is /python/Test/bpack -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
On Oct 7, 1:24 am, Scott David Daniels [EMAIL PROTECTED] wrote: goldtech wrote: ... I want the new file's location to be on the user's desktop in a Windows XP environment How about: import os.path handle = open(os.path.expanduser(r'~\DeskTop\somefile.txt'), 'w') ... That doesn't work on my system. ~ uses the HOME environment variable if set, otherwise uses HOMEDRIVE and HOMEPATH which is what I posted before. See Lib/ ntpath.py in a recent source distribution. In my case I set HOME to a path without spaces in it, to simplify my use of Emacs and Cygwin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another comparison of Python Web Frameworks
On Oct 7, 11:31 am, Istvan Albert [EMAIL PROTECTED] wrote: IMO this is not as much a framework comparison rather than an evaluation of the individual components that make up Pylons. More in general let's say that I am interested in the evaluation of WSGI-compatible components. The framework is the sum of all its parts. Programmers should not need to know that that a package named Beaker is used for sessions, Routes for url mapping, PasteDeploy for whatever. This is the weakness of all glue-type frameworks i.e. TG and Pylons. It makes them look like they are duct-taped together. Here we disagree: I think that a programmer should know what he is using. Moreover I think that composability is good since you can understand the components one at the time and replace one component with another according to your needs. OTOH, it is true that duct-taped framework have some weak points, I am the first to recognize that. But I also think the issues will be less and less relevant as time goes by and the culture of composable frameworks will become more widespread in the community. The more important question are whether the sessions actually work properly: i.e does session data persist through a server restart? Where is the session data stored: in memory, files, database and so on. Of course Beaker has all these features and I have no reasons to believe they will not work. The choice of templating language should be a non issue. Any half decent framework should allow you to use any other templating engine with ease. ... even python as you seem to prefer Yes, the choice of templating language is a non-issue. Maybe I should have removed my considerations on the subject in my essay, just to avoid the bikeshed effect. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
On Sun, 07 Oct 2007 16:51:33 +0200, Mathias Panzenboeck wrote: import weakref class Wrapper(object): def __init__(self,x): self.x = weakref.ref(x) def __call__(self,*args,**kwargs): x = self.x() if x is None: print lost reference else: return x(*args,**kwargs) class Foo(object): def __init__(self): self._methods = set() self._methods.add(Wrapper(self._foo)) def _foo(self): print _foo def callMethods(self): for method in self._methods: method() def __del__(self): print del Foo class Bar(object): def __init__(self): self._methods = set() self._methods.add(self._foo) def _foo(self): print _foo def callMethods(self): for method in self._methods: method() def __del__(self): print del Bar Now look what happens when I do this: f=Foo() f.callMethods() lost reference del f del Foo b=Bar() b.callMethods() _foo del b Foo looses the reference to its method but Bar on the other hand has a refloop and never gets deleted. ``del b`` just deletes the name `b`. It does not delete the object. There's still the name `_` bound to it in the interactive interpreter. `_` stays bound to the last non-`None` result in the interpreter. Drop all those `__del__()` methods as they prevent the garbage collector from collecting cycles. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
Alan Gauld wrote: Dick Moores [EMAIL PROTECTED] wrote http://www.redcanary.ca/view/top-programming Interesting, but I'm not sure what the criteria for top is. Is it a measure of power, popularity, usage? Scary that HTML/CSS should be so high though given its not a programming language at all! Half of those aren't programming languages. They have .NET, HTML/CSS, and AJAX. If you combine .NET and C#, that's the platform with the most points. The survey asks a question worth thinking about, but doesn't ask it very well. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
On Sun, 2007-10-07 at 17:54 +0200, Wildemar Wildenburger wrote: Kay Schluehr wrote: On Oct 7, 8:05 am, Dick Moores [EMAIL PROTECTED] wrote: http://www.redcanary.ca/view/top-programming Dick Moores Despite my doubts that Ajax and .NET will be programming languages in 2013 a more interesting question is: what could push Python forward s.t. it eats such a large piece of the PL cake? import friends import sex try: sex.have() except ErrectionError, PrematureError: pass finally: sex.brag(friends) Good! But. I think a kiss is elegant more than a sex. What do you think of? -- Byung-Hee HWANG [EMAIL PROTECTED] Schshschshchsch. -- The Gorn, Arena, stardate 3046.2 -- http://mail.python.org/mailman/listinfo/python-list
newbie swig c++ to python
Hi all, I must wrap some c++ code in python with swig. I try the swig examples for VC++ , but when I build the project it gives me that error: example fatal error LNK1181: cannot open input file 'C:\Programmi \Python25\libs.obj' Any idea? thank you w -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
On Oct 7, 12:26 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: Drop all those `__del__()` methods as they prevent the garbage collector from collecting cycles. I fully agree and I will add that __del__ methods are always a bad idea. Also notice that recently Raymond Hetting said in this list that he wanted to submit a PEP to remove __del__ from Python 3000 (I don't know if this will ever happen tough). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
You are assuming the system is not localized, that won't work if you distribute your applications internationally. In my system it is not Desktop, it is Escritorio, and I guess it will vary with every locale. Does someone know a way to find out what name does the desktop have? I believe you need to read the Desktop value from HKEY_CURRENT_USER\software\microsoft\windows\currentversion\explorer\shell folders which should (in my understanding) hold the full path of the particular folder(s) of interest at that location, including across localizations. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
Marc 'BlackJack' Rintsch wrote: On Sun, 07 Oct 2007 16:51:33 +0200, Mathias Panzenboeck wrote: import weakref class Wrapper(object): def __init__(self,x): self.x = weakref.ref(x) def __call__(self,*args,**kwargs): x = self.x() if x is None: print lost reference else: return x(*args,**kwargs) class Foo(object): def __init__(self): self._methods = set() self._methods.add(Wrapper(self._foo)) def _foo(self): print _foo def callMethods(self): for method in self._methods: method() def __del__(self): print del Foo class Bar(object): def __init__(self): self._methods = set() self._methods.add(self._foo) def _foo(self): print _foo def callMethods(self): for method in self._methods: method() def __del__(self): print del Bar Now look what happens when I do this: f=Foo() f.callMethods() lost reference del f del Foo b=Bar() b.callMethods() _foo del b Foo looses the reference to its method but Bar on the other hand has a refloop and never gets deleted. ``del b`` just deletes the name `b`. It does not delete the object. There's still the name `_` bound to it in the interactive interpreter. `_` stays bound to the last non-`None` result in the interpreter. Why is it then that f (instance of Foo) really gets deleted? (__del__ is called) Drop all those `__del__()` methods as they prevent the garbage collector from collecting cycles. Ciao, Marc 'BlackJack' Rintsch I only inserted them so I can see if the objects are really freed. How can I see that without a __del__ method? Thanks so far, panzi -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
Marc 'BlackJack' Rintsch wrote: ``del b`` just deletes the name `b`. It does not delete the object. There's still the name `_` bound to it in the interactive interpreter. `_` stays bound to the last non-`None` result in the interpreter. Actually I have the opposite problem. The reference (to the bound method) gets lost but it shouldn't! -panzi -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie swig c++ to python
Now it works, the problem was in the project configuration of the example, that put the directory in Addictional Dependencies while it must be in Addictional Library Directories bye w n 7 Ott, 18:35, whatazor [EMAIL PROTECTED] wrote: Hi all, I must wrap some c++ code in python with swig. I try the swig examples for VC++ , but when I build the project it gives me that error: example fatal error LNK1181: cannot open input file 'C:\Programmi \Python25\libs.obj' Any idea? thank you w -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
On Sun, 07 Oct 2007 16:38:23 +, Michele Simionato wrote: On Oct 7, 12:26 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: Drop all those `__del__()` methods as they prevent the garbage collector from collecting cycles. I fully agree and I will add that __del__ methods are always a bad idea. Always? I recently wrote a bit of code where I needed to check that releasing the first object in a tree-like structure would allow Python to garbage collect all the other objects in a tree. I thought it would, but I wanted to be sure (don't guess, test), so I wrote a simple class, gave it a __del__ method that just printed self, inserted them in the tree, and then deleted the first one. Worked like a charm. Without __del__, what should I have done to test that my code was deleting objects and not leaking memory? What should I do when my objects need to perform some special processing when they are freed, if I shouldn't use __del__? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
Mathias Panzenboeck wrote: Marc 'BlackJack' Rintsch wrote: ``del b`` just deletes the name `b`. It does not delete the object. There's still the name `_` bound to it in the interactive interpreter. `_` stays bound to the last non-`None` result in the interpreter. Actually I have the opposite problem. The reference (to the bound method) gets lost but it shouldn't! Ahh, so you expected that ``Wrapper(self._foo)`` would not immediately lose the reference? It will, because every time you write ``self._foo``, a new bound method is created:: class C(object): ... def foo(self): ... pass ... f = C.foo g = C.foo id(f), id(g) (14931448, 14891008) Thus, there is only the one reference to the bound method, and by wrapping it in a weakref, you are allowing it to disappear immediately:: x = weakref.ref(C.foo) print x() None What behavior do you want here? That is, when were you hoping that the bound method would disappear? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
Tim Chase wrote: You are assuming the system is not localized, that won't work if you distribute your applications internationally. In my system it is not Desktop, it is Escritorio, and I guess it will vary with every locale. Does someone know a way to find out what name does the desktop have? I believe you need to read the Desktop value from HKEY_CURRENT_USER\software\microsoft\windows\currentversion\explorer\shell folders which should (in my understanding) hold the full path of the particular folder(s) of interest at that location, including across localizations. -tkc Ideally, use the shell API exposed by pywin32: code from win32com.shell import shell, shellcon desktop = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) /code For slight convenience: http://timgolden.me.uk/python/winshell.html TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a file on users XP desktop
Tim Chase wrote: You are assuming the system is not localized, that won't work if you distribute your applications internationally. In my system it is not Desktop, it is Escritorio, and I guess it will vary with every locale. Does someone know a way to find out what name does the desktop have? I believe you need to read the Desktop value from HKEY_CURRENT_USER\software\microsoft\windows\currentversion\explorer\shell folders which should (in my understanding) hold the full path of the particular folder(s) of interest at that location, including across localizations. -tkc Ideally, use the shell API exposed by pywin32: code from win32com.shell import shell, shellcon desktop = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) /code For slight convenience: http://timgolden.me.uk/python/winshell.html TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Pil image module, mode bug..
On Sun, 07 Oct 2007 09:02:09 -0700, Abandoned wrote: On Oct 7, 4:47 pm, Michal Bozon [EMAIL PROTECTED] wrote: On Sun, 07 Oct 2007 06:03:06 -0700, Abandoned wrote: Hi.. I find the picture color with: im=Image.open(/%s %name) color=im.mode #p=black beyaz rgb=color L=grey This usually work true but in these pictures: http://malatya.meb.gov.tr/images/alt/ilsis_logo.gif http://malatya.meb.gov.tr/images/meb.gif Say me P (blackwhite) but these pictures are color.. What is the reason of this ? I'm sorry my bad english P does mean palette, blackwhite is a special case of palette, with two colors. How can i understand the picture color ? (black white or color or grey) If you know how to work with RGB images, you can convert the image from the palette mode easily: img2 = img.convert(mode='RGB') Anyway, always is helpful to read the tutorial or basic documentation.. ;) MB -- http://mail.python.org/mailman/listinfo/python-list
Re: weakrefs and bound methods
On Oct 7, 1:14 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sun, 07 Oct 2007 16:38:23 +, Michele Simionato wrote: On Oct 7, 12:26 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: Drop all those `__del__()` methods as they prevent the garbage collector from collecting cycles. I fully agree and I will add that __del__ methods are always a bad idea. Always? I recently wrote a bit of code where I needed to check that releasing the first object in a tree-like structure would allow Python to garbage collect all the other objects in a tree. I thought it would, but I wanted to be sure (don't guess, test), so I wrote a simple class, gave it a __del__ method that just printed self, inserted them in the tree, and then deleted the first one. Worked like a charm. Without __del__, what should I have done to test that my code was deleting objects and not leaking memory? What should I do when my objects need to perform some special processing when they are freed, if I shouldn't use __del__? The best thing is to use explicit resource management, for instance with a try .. finally or with the with statement in Python 2.5. The next best thing is to use weak references. I have some code for various experiments with wearefs I did some time ago, here it is: import itertools, weakref, sys, gc reference_list = [] # cannot be a set, you would lose references resource_counter = itertools.count(1) def resource(before_closing_callback=None, after_closing_callback=None): private = '_resource_%s' % resource_counter.next() def get(self): return getattr(self, private) def set(self, resource): setattr(self, private, resource) def close(ref): if before_closing_callback: before_closing_callback(resource) resource.close() if after_closing_callback: after_closing_callback(resource) reference_list.remove(ref) reference_list.append(weakref.ref(self, close)) return property(get, set) class FakeResource(object): def __init__(self, name): print 'opening resource %s' % name self.name = name def close(self): print 'closing resource %s' % self.name def __repr__(self): return 'FakeResource %r' % self.name class Example(object): def __init__(self): self.resource1 = FakeResource('r1') self.resource2 = FakeResource('r2') def __del__(self): print '**' self.resource1.close() self.resource2.close() def warn_before_closing(res): sys.stdout.write('going to close %s\n' % res) class Example2(object): resource1 = resource(warn_before_closing) resource2 = resource() def __init__(self): self.resource1 = FakeResource('r1') self.resource2 = FakeResource('r2') gc.set_debug(gc.DEBUG_LEAK) #e = Example() e = Example2() e.e = e del e print reference_list -- http://mail.python.org/mailman/listinfo/python-list
Re: Top Programming Languages of 2013
Byung-Hee HWANG wrote: On Sun, 2007-10-07 at 17:54 +0200, Wildemar Wildenburger wrote: import friends import sex try: sex.have() except ErrectionError, PrematureError: pass finally: sex.brag(friends) Good! But. I think a kiss is elegant more than a sex. What do you think of? Elegant maybe, but for Python to stand out (he...), it needs something above newbie-level. Mind you that this is just a basic (and rather cheap) operation from the standard libs of 2013. More pythonic alternatives (like sex.strangle.*) will be provided as well. /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Putting a line from a text file into a variable, then moving to next line
On 07/10/2007, Tim Chase [EMAIL PROTECTED] wrote: I'm not really sure how readline() works. Is there a way to iterate through a file with multiple lines and then putting each line in a variable in a loop? You can use readlines() to get the whole line (including the newline): lines = file('x.txt').readlines() or you can iterate over the file building a list without the newline: lines = [line.rstrip('\n') for line in file('x.txt')] Thus, line[0] will be the first line in your file, line[1] will be the second, etc. or splitlines() lines = open('x.txt').read().splitlines() :) -- http://mail.python.org/mailman/listinfo/python-list
Re: supplying password to subprocess.call('rsync ...'), os.system('rsync ...')
timw.google wrote: Hi I want to write a python script that runs rsync on a given directory and host. I build the command line string, but when I try to run subprocess.call(cmd), or p=subprocess.Popen(cmd, shell=True),or os.system(cmd), I get prompted for my login password. I expected this, but when I try to give my password, it's echoed back to the terminal and the special characters in the password is (I think) getting interpreted by the shell (zsh) I can't ssh w/o supplying a password. That's the way the security is set up here. How do I use python to do this, or do I just have to write a zsh script? You need to use the pexpect module. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie packages Q
MarkyMarc a écrit : On Oct 7, 6:04 pm, Bruno Desthuilliers bruno. (snip) But how do I get this to work? You failed to specify how your files are organized, and what is not working. But anyway, if - atest.py is in wherever/Test/apack, - both Test and apack have a __init__.py - wherever is in the sys.path, then this should just work AFAICT. If you se me first post you will see have me files are organized. Could have changed. But like this: Test/ __init__.py (a empty file) apack/ __init__.py (a empty file) atest.py bpack/ __init__.py (a empty file) btest.py And also in me first post(and others), all I get is an import error: ImportError: cannot import name apack. And sys.path is /python/Test/bpack And you do wonder why you can't import ? Please reread with attention the first and third points listed above (following the 'But anyway'). The 'Test' package is *not* in your sys.path. -- http://mail.python.org/mailman/listinfo/python-list
Problem of Readability of Python
Python is supposed to be readable, but after programming in Python for a while I find my Python programs can be more obfuscated than their C/C ++ counterparts sometimes. Part of the reason is that with heterogeneous lists/tuples at hand, I tend to stuff many things into the list and *assume* a structure of the list or tuple, instead of declaring them explicitly as one will do with C structs. So, what used to be struct nameval { char * name; int val; } a; a.name = ... a.val = ... becomes cryptic a[0] = ... a[1] = ... Python Tutorial says an empty class can be used to do this. But if namespaces are implemented as dicts, wouldn't it incur much overhead if one defines empty classes as such for some very frequently used data structures of the program? Any elegant solutions? -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem of Readability of Python
Licheng Fang wrote: Python is supposed to be readable, but after programming in Python for a while I find my Python programs can be more obfuscated than their C/C ++ counterparts sometimes. Part of the reason is that with heterogeneous lists/tuples at hand, I tend to stuff many things into the list and *assume* a structure of the list or tuple, instead of declaring them explicitly as one will do with C structs. So, what used to be struct nameval { char * name; int val; } a; a.name = ... a.val = ... becomes cryptic a[0] = ... a[1] = ... Python Tutorial says an empty class can be used to do this. But if namespaces are implemented as dicts, wouldn't it incur much overhead if one defines empty classes as such for some very frequently used data structures of the program? Any elegant solutions? You can use __slots__ to make objects consume less memory and have slightly better attribute-access performance. Classes for objects that need such performance tweaks should start like:: class A(object): __slots__ = 'name', 'val' The recipe below fills in the obvious __init__ method for such classes so that the above is pretty much all you need to write: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem of Readability of Python
Licheng Fang a écrit : Python is supposed to be readable, but after programming in Python for a while I find my Python programs can be more obfuscated than their C/C ++ counterparts sometimes. Part of the reason is that with heterogeneous lists/tuples at hand, I tend to stuff many things into the list and *assume* a structure of the list or tuple, instead of declaring them explicitly as one will do with C structs. So, what used to be struct nameval { char * name; int val; } a; a.name = ... a.val = ... becomes cryptic a[0] = ... a[1] = ... Use dicts, not lists or tuples: a = dict(name='yadda', val=42) print a['name'] print a['val'] Python Tutorial says an empty class can be used to do this. But if namespaces are implemented as dicts, wouldn't it incur much overhead if one defines empty classes as such for some very frequently used data structures of the program? If you do worry about overhead, then C is your friend !-) More seriously: what do you use this 'nameval' struct for ? If you really have an overhead problem, you may want to use a real class using __slots__ to minimize this problem, but chances are you don't need it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem of Readability of Python
Licheng Fang wrote: struct nameval { char * name; int val; } a; a.name = ... a.val = ... becomes cryptic a[0] = ... a[1] = ... ?! (1) a = {} a[name] = ... a[val] = ... (2) NAME = 0 VAL = 1 a=[] a[NAME] = ... a[VAL] = ... Python Tutorial says an empty class can be used to do this. But if namespaces are implemented as dicts, wouldn't it incur much overhead if one defines empty classes as such for some very frequently used data structures of the program? Measure first, optimize later. How many million of instances and/or accesses per second do you have? Regards, Björn -- BOFH excuse #20: divide-by-zero error -- http://mail.python.org/mailman/listinfo/python-list