From me at nospam.com Tue Oct 5 16:35:38 2004 From: me at nospam.com (Lorin Hochstein) Date: Tue, 05 Oct 2004 16:35:38 -0400 Subject: Retrieving the full path of Unix apps In-Reply-To: <4163013c$0$59513$a1866201@newsreader.visi.com> References: <4163013c$0$59513$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > On 2004-10-05, Lorin Hochstein wrote: > > > Do you care _which_ path you end up with in the case where > there are multiple ones that end in the filename of interest? > > Are you assuming that the program is in one of the directories > listed in the PATH environment variable? > Sorry, I should've been more clear. I am assuming the program is in one of the directories listed in the PATH environment variable. I want the same one that 'which' will return: the one that would get invoked if someone just typed in the name of the program at the command-line. > > You could grab the value of the environment variable PATH, and > search those directories for the file in question. That's > pretty much what the 'which' command does. > That does seem more elegant than relying on 'which'. Thanks, Lorin From vinay_sajip at yahoo.co.uk Sat Oct 2 11:54:00 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 2 Oct 2004 08:54:00 -0700 Subject: limitations of current logging package References: <2e37dc1.0409230442.7e74543d@posting.google.com> <4edc17eb.0409232031.66ad3d4e@posting.google.com> <2e37dc1.0409260220.6ad5cb6c@posting.google.com> Message-ID: <2e37dc1.0410020754.739f8744@posting.google.com> > The above shows clearly that one can use logging in a simple > way, but as Michael points out, it's not well documented how > simple it can be. Even having read this thread and knowing > in advance that I could do that, I wasn't able to find the > relevant information easily in the documentation with > several minutes of reading (and several minutes covers a > lot of territory normally). Even when I found the comments > about the shortcut functions, I wouldn't have been certain > how to use them (as above) because an example is missing. The following documentation, which is in CVS for Python and will be part of the next release, does give information for simple usage: http://www.python.org/dev/doc/devel/lib/minimal-example.html > 2) I wanted my log files written to the application's own > directory, rather than to the current directory. Using > the fileConfig capability, you can't, at least not without > using absolute paths (near as I can tell). > > My hack workaround was to prepopulate the logging module's > vars() with one call _app_path, and then to reference that > in the config file in the following way. This works only > because (a) eval is used on the args, and (b) the os module > has already been imported by logging.__init__: > > (in the main code:) > logging._app_path = MY_APP_PATH > logging.config.fileConfig(MY_CONFIG_FILE) > > (in the config file:) > [handler_hand01] > class=handlers.RotatingFileHandler > level=NOTSET > formatter=form01 > args=(os.path.join(_app_path, 'bod.log'), 'a', 10000000, 9) > > > Now I can sort of see why the second issue might be awkward > to resolve (since it is in effect a problem that appears in > various other ways in the Python world, with no standard > solution, mainly because there's no simple "sys.getappdir()" > or whatever it would be called). You can simply say something like logging.mymodule = mymodule and in the config file, the args for the file handler can, instead of specifying the file name, reference a function such as mymodule.getpathname('myapp.log'), where getpathname prepends the appropriate path. In the same way, you can reference handlers defined in your own module in the config file. > For the first problem, I think the exc_info "flag" should be > changed so that if it contains actual exception info, or > maybe just a tuple of three items, then *that* information > is logged instead of a call to sys.exc_info() being made. Not quite true, although the documentation could be a little clearer. Originally, the exc_info flag was checked for true/false, and this check still holds for deciding whether exception info is logged. However, in recent versions, if an exception tuple (in the same format as returned by sys.exc_info()) is passed, sys.exc_info() is not called and the passed tuple is used instead. I aim to update the documentation to reflect this. Regards, Vinay Sajip From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Mon Oct 25 03:49:26 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Mon, 25 Oct 2004 08:49:26 +0100 Subject: how do i change from string to list In-Reply-To: References: <99ca2e2f.0410241005.39a4f1db@posting.google.com> <417bf196$0$771$3a628fcd@reader20.nntp.hccnet.nl> <417c1cda$0$152$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: BJ?rn Lindqvist wrote: > How do you do the opposite? List to string? Shortest method I've found is: > >>>>''.join(["H", "e", "l", "l", "o"]) That is the obvious way to do it. -- Michael Hoffman From jdc at uwo.ca Wed Oct 6 15:36:19 2004 From: jdc at uwo.ca (Dan Christensen) Date: Wed, 06 Oct 2004 15:36:19 -0400 Subject: Question mark in variable and function names In-Reply-To: (Fernando Perez's message of "Wed, 06 Oct 2004 11:30:41 -0600") References: <1gl90yk.v91yz8w1z0b2N%aleaxit@yahoo.com> Message-ID: <87d5zvwsek.fsf@uwo.ca> Fernando Perez writes: >> Andr? N?ss wrote: >> >>> One thing I liked about Lisp was the ability to use the question mark >>> (and the exclamation mark) in function names. > > Well, there would go the two remaining special, useful chars in ipython: > > In [4]: x? ... > In [5]: !uname -a ... If python only allowed ! and ? at the end of identifiers, then !uname would be fine, and ?x could be used in place of x? But the problem mentioned in other post with code like x!=0 is more serious. Dan From nelson at monkey.org Sun Oct 17 21:07:25 2004 From: nelson at monkey.org (Nelson Minar) Date: Mon, 18 Oct 2004 01:07:25 GMT Subject: md5 and large files References: <4172a5f6$0$28202$9b622d9e@news.freenet.de> <4172AA52.9030606@vt.edu> Message-ID: Brad Tilley writes: > I would like to verify that the files are not corrupt so what's the > most efficient way to calculate md5 sums on 4GB files? The machine > doing the calculations is a small desktop with 256MB of RAM. If all you want to do is verify that a file is not corrupt, MD5 is the wrong algorithm to use. Use something fast like crc32. If you're worried about corruption anywhere in the file, then testing the first 4k isn't going to help you very much. If you really need it to be efficient, don't use Python. Use a native program like md5sum or sum or something. If this is you're homework, you'll learn a lot more by figuring it out yourself. From theller at python.net Thu Oct 7 15:34:28 2004 From: theller at python.net (Thomas Heller) Date: Thu, 07 Oct 2004 21:34:28 +0200 Subject: Inline returning of function objects References: Message-ID: dataangel writes: > I've been finding more and more crazy stuff that you can do in Python, > and I was curious if it could handle this (it couldn't): > > def foo(x): > return def bar(y): > pass > > I was wondering why there's support for this for lambda functions but > not normal functions. I tried variations in the syntax like > surrounding the function definition with parenthesis but none worked. but you can write: def foo(x): def bar(y): pass return bar Thomas From ville at spammers.com Fri Oct 1 07:56:24 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Oct 2004 14:56:24 +0300 Subject: Emacs is going to die! =( [was Re: Emacs + python (Was Re: python is going to die! =() References: <278de0e.0409201131.57baf7f9@posting.google.com> <414f61bf$0$29449$636a15ce@news.free.fr> <87hdprv3qd.fsf_-_@ion.xlipstream.com> Message-ID: >>>>> "Richie" == Richie Hindle writes: Richie> 1. There is no File/Open. You can't just open an Richie> arbitrary file and edit it; the file must be part of a Richie> project. This makes (some) sense File / Open external file. It's not drag-and-drop, but better than nothing. Richie> 2. In the Python debugger (I was using the PyDev plugin) a Richie> Step took between 3 and 4 seconds on my 3GHz PC. (I'd Richie> previously tried I tried the debugger only briefly - it was not that slow. It wasn't snappy, but at least it felt faster than w/ some older version of PyDev (that was pydev 0.6.1). -- Ville Vainio http://tinyurl.com/2prnb From aleaxit at yahoo.com Mon Oct 18 03:27:45 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 18 Oct 2004 09:27:45 +0200 Subject: UNIX-style sort in Python? References: <41734491$0$27969$a1866201@newsreader.visi.com> Message-ID: <1glui57.aaac91au1t84N%aleaxit@yahoo.com> Grant Edwards wrote: > On 2004-10-18, Kotlin Sam wrote: > > > For a while at least I have to work in Windows rather than UNIX, which > > is more familiar. I'm trying to do with Python some of the things that > > I've done for years in shell, in particular, sort. The shell sort is > > pretty easy to use: > > Sounds like you need to install Cygwin so you have a real bash > shell and all of the normal shell utilities. An excellent piece of advice. Cygwin has occasionally save my sanity in the past when the weakness of Windows' cmd.exe was getting to me...!-) Alex From sean.carey at gmail.com Thu Oct 7 18:47:09 2004 From: sean.carey at gmail.com (Sean Carey) Date: 7 Oct 2004 15:47:09 -0700 Subject: Python script that generates blob files Message-ID: <1097189229.883950.253450@z14g2000cwz.googlegroups.com> I am wondering if anyone knows of a python script or any other script that will generate random files with random sizes that I can specify. Thanks Sean From lbates at syscononline.com Thu Oct 7 09:37:30 2004 From: lbates at syscononline.com (Larry Bates) Date: Thu, 07 Oct 2004 08:37:30 -0500 Subject: generating emails from Python In-Reply-To: <4edc17eb.0410070159.1b9e670f@posting.google.com> References: <4edc17eb.0410070159.1b9e670f@posting.google.com> Message-ID: Michele Simionato wrote: > Is it possible, using email.MIMEMessage, to generate an email with > both HTML and plain text content, in such a way that: > 1) it is displayed as HTML if the email client recognizes HTML; > 2) it is displayed as plain text if the email client is HTML impaired? > > I realize that the answer is most probably no, but one can always hope > ... > > Michele Simionato Google is your friend: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083 Larry Bates From deetsNOSPAM at web.de Fri Oct 8 07:23:49 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 08 Oct 2004 13:23:49 +0200 Subject: How to determine if a file is busy? References: Message-ID: > I have written a stay-open-AppleScript for Mac OS X, gathering certain > informations from different apps, which can only be gathered via > AppleScript. This script writes its informations into a simple text > file, every 15 seconds. And a python script is supposed to read this > text file on a regular basis in order to feed the aquired datat into a > database working only on Windows. Now the problem: How can I prevent > that the python script reads the content of the text file, while my > AppleScripts writes new information to it? Is there any 'busy'-status > for files? You could use a file-lock using the module fcntl.lock operation on the file descriptor of your file. That ensures that only when the writing is completed, the reading can occur. Check man flock on your console/terminal. But that works only on _one_ machine. When you have a shared filesystem that two different OSes access, you might be better off with a protocol of some sort - by that I mean that you use e.g. http-style header information. So your producer-script gathers data - lets say 4000 bytes - and writes this to the file: Content-Length: 4000 Then your consumer-script reads the header. Only after that is fully received and understood, it knows how many bytes to expect after the second newline and won't start processing earlier. Apart from that, the usecase you describe cries for a decent inter-process-communication. You could e.g. use XMLRPC, PYRO, CORBA or the like. That would free you from the necessity of a shared filesystem between windows and macosx, and from implementing a protocol. -- Regards, Diez B. Roggisch From eddie at holyrood.ed.ac.uk Fri Oct 1 06:00:45 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 1 Oct 2004 10:00:45 +0000 (UTC) Subject: Dynamically Generating a Graph in Python References: <47f7cc78.0409300618.332a3278@posting.google.com> Message-ID: tim.tadh at gmail.com (Tim Henderson) writes: >Hi >I want to dynamically generate a graph in python that would be >displayable on a web page. What would be the best way to do this? >The reason I want to do this, is because I am making a program to >convert data from scientic probes into web pages. I have been able to >do every thing except the graph generation. http://newcenturycomputers.net/projects/gdmodule.html is what I use. From grante at visi.com Mon Oct 25 15:09:41 2004 From: grante at visi.com (Grant Edwards) Date: 25 Oct 2004 19:09:41 GMT Subject: GPL and Python modules. References: <417d18bc$0$1313$a1866201@newsreader.visi.com> <417d4471$0$524$a1866201@newsreader.visi.com> <417d48f6$0$1324$a1866201@newsreader.visi.com> <2b-dnQaA6rzh0eDcRVn-gQ@powergate.ca> Message-ID: <417d4f75$0$45524$a1866201@newsreader.visi.com> On 2004-10-25, Peter Hansen wrote: > Grant Edwards wrote: >> I guess I could just tell py2exe to also include the .py files >> in the install directory. There's still the problem of the >> time/cost required to support them. >> >>> But as long as you don't mind people seeing, redistributing, >>> and modifying your source, >> >> The problem is the time spent answering questions and helping >> the people who have the source code. > > Whatever gave you the idea you are obligated to provide support?! Experience. Customers seem to have no problem with not getting source code, but once you _do_ give them source code then you have to support it. Ignoring customers when they ask questions about the source code has always proven in past experience to be "not an option." -- Grant Edwards grante Yow! If elected, Zippy at pledges to each and every visi.com American a 55-year-old houseboy... From adalke at mindspring.com Thu Oct 7 18:24:51 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 07 Oct 2004 22:24:51 GMT Subject: Graceful detection of EOF In-Reply-To: <654bb44cb5ff9def08dab7c56459c4c0@localhost.talkaboutprogramming.com> References: <654bb44cb5ff9def08dab7c56459c4c0@localhost.talkaboutprogramming.com> Message-ID: MickeyBob wrote: > How does one detect the EOF gracefully? Assuming I have a pickle file > containing an unknown number of objects, how can I read (i.e., > pickle.load()) until the EOF is encountered without generating an EOF > exception? Why isn't catching the exception graceful? # UNTESTED CODE def load_pickle_iter(infile): while 1: try: yield pickle.load(infile) except EOFError: break for obj in load_pickle_iter(open("mydata.pickle", "rb")): print obj This is well in line with the normal Python idiom, as compared to "look before you leap". Andrew dalke at dalkescientific.com From aahz at pythoncraft.com Fri Oct 8 15:40:04 2004 From: aahz at pythoncraft.com (Aahz) Date: 8 Oct 2004 15:40:04 -0400 Subject: Parallelization on muli-CPU hardware? References: <6db3f637.0410042045.2171ad5f@posting.google.com> <1glb1jy.1at6as41fab2t9N%aleaxit@yahoo.com> <1glbyrn.4jt08j144wg1dN%aleaxit@yahoo.com> Message-ID: In article <1glbyrn.4jt08j144wg1dN%aleaxit at yahoo.com>, Alex Martelli wrote: >Bryan Olson wrote: >> >> Guido did not impose the GIL lightly. This is a hard problem. > >Sure. I wonder what (e.g.) IronPython or Ruby do about it -- never >studied the internals of either, yet. Ruby doesn't have OS-level threading IIRC. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From agriff at tin.it Wed Oct 27 15:50:29 2004 From: agriff at tin.it (Andrea Griffini) Date: Wed, 27 Oct 2004 19:50:29 GMT Subject: GPL and Python modules. References: <417d18bc$0$1313$a1866201@newsreader.visi.com> Message-ID: <3tuvn05ndqa434m36ieub2rqm8q3f456t9@4ax.com> On Wed, 27 Oct 2004 11:45:40 +0200, Bernhard Herzog wrote: >No. They have to be able to link a *modified* version of the library, >not necessarily a newer or incompatible one. The LGPL quite explicitly >says that this relinking only has to be possible for sufficiently >compatible modifications. You're right. I've no excuses for basing my misinformed post on just hearsay. Now that I took the time to actually read the license that part is clear. Thankyou for the correction. Andrea From nick at craig-wood.com Thu Oct 7 11:29:57 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 07 Oct 2004 15:29:57 GMT Subject: End of file References: <6a13a506.0410062329.5de9e695@posting.google.com> Message-ID: Duncan Booth wrote: > You need to read the next line before you can tell which is the last line. > The easiest way is probably to use a generator: > > def lineswithlast(filename): > prev, line = None, None > for line in file(filename): > if prev is not None: > yield prev, False > prev = line > if line: > yield line, True > > > for line, last in lineswithlast('somefile.txt'): > print last, line I like that. I generalised it into a general purpose iterator thing. You'll note I use the spurious sentinel local variable to mark unused values rather than None (which is likely to appear in a general list). I think this technique (which I invented a few minutes ago!) is guaranteed correct (ie sentinel can never occur in iterator). def iterlast(iterator): "Returns the original sequence with a flag to say whether the item is the last one or not" sentinel = [] prev, next = sentinel, sentinel for next in iterator: if prev is not sentinel: yield prev, False prev = next if next is not sentinel: yield next, True for line, last in iterlast(file('z')): print last, line -- Nick Craig-Wood -- http://www.craig-wood.com/nick From richie at entrian.com Thu Oct 7 09:24:41 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 07 Oct 2004 14:24:41 +0100 Subject: Simple Python web proxy stalls for some web sites In-Reply-To: <41649d0e@post.usenet.com> References: <41649d0e@post.usenet.com> Message-ID: [Carl] > I have written a simple web proxy using the Python standard library > BaseHTTPRequestHandler. [...] some?web sites simply seem to stall > indefinitely (e.g. www.google.com). By default, urllib2 specifies "User-Agent: Python-urllib/x.y" Some sites, Google included, reject this because they don't like to be web-scraped. You need to tell urllib2 to ditch its built-in User-Agent header and pass through the one from the browser. I don't know how to do that off the top of my head, but some Googling should soon find the answer. 8-) I do know that there were some bugs in this that were fixed in Python 2.3, so make sure you're using at least that version. -- Richie Hindle richie at entrian.com From kirk-news at jobsluder.net Tue Oct 19 17:23:13 2004 From: kirk-news at jobsluder.net (Kirk Job-Sluder) Date: Tue, 19 Oct 2004 21:23:13 GMT Subject: bz2 & cpu usage In-Reply-To: References: Message-ID: <5Bfdd.9261$5b1.3267@newssvr17.news.prodigy.com> Sorry for the late post, the original scrolled off the server. > I'd like to keep at least 50% of the cpu free while doing bz2 file > compression. Currently, bz2 compression takes between 80 & 100 percent > of the cpu and the Windows GUI becomes almost useless. How can I lower > the strain on the cpu and still do compression? I'm willing for the > compression process to take longer. > > Thanks, > > Brad > > def compress_file(filename): > path = r"C:\repository_backup" > print path > for root, dirs, files in os.walk(path): > for f in files: > if f == filename: > print "Compressing", f > x = file(os.path.join(root, f), 'rb') > os.chdir(path) > y = bz2.BZ2File(f + ".bz2", 'w') > while True: > data = x.read(1024000) > time.sleep(0.1) > if not data: > break > y.write(data) > time.sleep(0.1) > y.close() > x.close() > else: > return One of the issues you may be running into is memory. Under windows, using up 90% of the CPU shouldn't affect GUI performance (much) but swapping does. According to the bzip2 man page, the maximum block size is 900KB so you might be running into problems reading your file 1024KB at a time. Use the system monitor control panel to check for excessive swapping. Bzip2 uses 8x memory. So with the default setting of a 900KB block size, you are looking at 7.2M + some bookeeping memory. Another issue is that you might be better off downloading bzip2 for windows and letting the gnu bzip2 implementation handle file input and output. Using a shell command here might be more efficient in spite of spawning a new process. A third issue is that bzip2 achieves high compression efficiency at the expense of CPU time and memory. It might be worth considering whether gzip might occupy the sweet spot compromise between minimal archive size and minimal cpu usage. Fourth, how many of those files are uncompressible? I've noticed that bzip2 tries really hard to eek out some form of savings from uncompressible files. A filename filter for files that should not be compressed (png, jpg, gif, sx*) might be worth doing here. From werner_DOT_merkl_ at _fujitsu_DASH_siemens.com Mon Oct 25 06:56:16 2004 From: werner_DOT_merkl_ at _fujitsu_DASH_siemens.com (Werner Merkl) Date: Mon, 25 Oct 2004 12:56:16 +0200 Subject: py2exe and UPPER CASE file system Message-ID: Hi, my problem is, I try to use a py2exe compiled python script from a CD-ROM. This should work, BUT the tool I use (or have to use) generates only upper case file names on the CD-ROM. For py2exe 0.4.1 and python 2.2 this worked fine... but the current releases do not. Any ideas or help? Thanks in advance Werner Merkl From tim.golden at viacom-outdoor.co.uk Fri Oct 15 11:50:58 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 15 Oct 2004 16:50:58 +0100 Subject: Search-Filter for LDAP (MS Active Directory) Message-ID: | I asked here a few weeks ago the same question but the answer of Tim | Golden didn't really help yet. | | I'd like to know how to set up a query for all computer-accounts in a | special part of Active Directory by using LDAP. OK. I imagine that this is far too late to solve your particular problem, and several others have already provided LDAP-based solutions but... I've uploaded a module-wrapper round Microsoft's LDAP:// object set to: http://tgolden.sc.sabren.com/downloads/active_directory.py I'll try to put some info on that site to support it, but it's fairly simple, fairly well-commented within, and I'll add an example below to match your situation. | Example: | all computers with a name like "ABC*" at "..., ou=Production, | DC=business,DC=company,DC=com" import active_directory ad = active_directory.AD () production = ad.child ("ou=production") for computer in production.search (["objectClass=computer", "displayName=ABC*"]): print computer print "Properties used:", [p for p in computer.properties if getattr (computer, p)] print computer.operatingSystemVersion HTH TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From michele.simionato at gmail.com Mon Oct 4 06:23:32 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 Oct 2004 03:23:32 -0700 Subject: metaclass and customization with parameters References: <3b59a80.0410021910.17b31c29@posting.google.com> <1gl3wcp.15oxvkd1jdp8dbN%aleaxit@yahoo.com> Message-ID: <4edc17eb.0410040223.4aa4f24b@posting.google.com> Carlos Ribeiro wrote in message news:... > BTW, once I finish my deep imersion into new style classes, which > includes metaclasses and descriptors, I intend to write a tutorial and > post it somewhere. It's a fascinating topic, but the documentation > seems to assume that you already know what is this stuff useful for > :-) A tutorial would help to clarify stuff greatly. Notice that there already valuable resources on this stuff. Unfortunately, after several minutes of searching on www.python.org I didn't find them (which may denote that something is wrong with me or with python.org). Search for new style classes, Shalab and may be even Dave Kuhlman . Michele Simionato From limodou at gmail.com Sat Oct 16 02:14:09 2004 From: limodou at gmail.com (limodou) Date: Sat, 16 Oct 2004 14:14:09 +0800 Subject: How to deal __getattr__ In-Reply-To: <505f13c04101522596d9ea6e3@mail.gmail.com> References: <505f13c04101522596d9ea6e3@mail.gmail.com> Message-ID: <505f13c04101523143f78d2a7@mail.gmail.com> I resolved the problem via defining __eq__method, just like: >>> class A: def __getattr__(self, name): print name return None def __eq__(self, obj): return id(self) == id(obj) >>> a=A() >>> b=A() >>> a==b False I don't know whether it's the right solution, any ideas? On Sat, 16 Oct 2004 13:59:11 +0800, limodou wrote: > I found it puzzled me that: > > class A: > def __getattr__(self, name): > return None > a=A() > b=A() > a==b will raise Exception: > > __eq__ > > Traceback (most recent call last): > File "", line 1, in -toplevel- > a==b > TypeError: 'NoneType' object is not callable > > I want to compare the objects themself not the attributes of them. But > it seems python invoke __getattr__ method, it's strange. How can I > compare the object directly without calling __getattr__? > > Thankx > > -- > I like python! > -- I like python! From alikakakhel3 at hotmail.com Fri Oct 8 12:49:49 2004 From: alikakakhel3 at hotmail.com (Ali) Date: 8 Oct 2004 09:49:49 -0700 Subject: How do you do this in python with tk? References: <8f17f4bc.0410071431.15e0c4ef@posting.google.com> Message-ID: <8f17f4bc.0410080849.51fbdcfa@posting.google.com> Jeff Epler wrote in message news:... > You could create a Text widget and insert lines of text in it. > > import Tkinter > def add_rows(w, titles, rows): > for r in rows: > for t, v in zip(titles, r): > w.insert("end", "%s:\t%s\n" % (t, v)) > w.insert("end", "\n") > > app = Tkinter.Tk() > t = Tkinter.Text(app) > t.pack() > info = [['Ali',18], > ['Zainab',16], > ['Khalid',18]] > add_rows(t, ["Name", "Age"], info) > app.mainloop() > > If there are many lines, you can use a scrollbar widget to scroll the > text widget. You can use the tabs= argument of the Text widget to > adjust the alignment of the second column. If you want to make the > items "interactive", you can use tags and tag_bind to react to things > like button presses. You can set the text widget to be "disabled" to > keep the user from changing the contents. > > Jeff > > -- I will try out your code. Thank you for helping. From peter at engcorp.com Sat Oct 30 10:59:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Oct 2004 10:59:47 -0400 Subject: What is Python's answer to Perl 6? In-Reply-To: References: <2uh4j7F2a86uqU1@uni-berlin.de> <1099144064.931829.257240@z14g2000cwz.googlegroups.com> <2uhl84F2ahviqU1@uni-berlin.de> Message-ID: Michael Hoffman wrote: > Reinhold Birkenfeld wrote: > >> C. Functions that could be made attributes of lists/sequences >> >> max, min, len, enumerate, sum >> >> But that would require to implement them for all sequence types or >> implement a common basetype 'seq'. > > And iterators? And dicts. And .... From rff_rff at remove-yahoo.it Tue Oct 5 06:39:38 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Tue, 05 Oct 2004 10:39:38 GMT Subject: Python Macros In-Reply-To: <41618797$0$69737$ed2619ec@ptn-nntp-reader01.plus.net> References: <41618797$0$69737$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: Michael Sparks ha scritto: >>I'd like to add messages and message passing, for example. > > > Why do you feel you need to extend the language for this? Why not (for > example) overload <<, >> and similar operators? __lshift__, __rshift__ etc. ah, so the OP is asking about Higher Order Messages a-la F-Script? (or hyper ops a-la perl6) I don't think this can be done in pure python. You can do half of it, say: collection >> stuff # map the stuff over the collection or collection >> operator << othercollection but you cant do stuff operator << collection From deets.nospaaam at web.de Thu Oct 21 09:32:37 2004 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Thu, 21 Oct 2004 15:32:37 +0200 Subject: excluding search string in regular expressions References: <02dfn0dvebf10uleb8m9kia8nm8cjkhg8n@4ax.com> Message-ID: <2tps4sF225s2rU1@uni-berlin.de> > > A more common solution for detecting functions/Methods would be fine. Maybe you should go for a real parser here - together with a C-syntax-grammar. Trying to cram this stuff into regexps is bound for not catching special cases. And its gereally difficult to have a regexp _not_ macht a certain word. Another approach would be to look for closing comments and function definitions in several rexes, and use python-logic: if doxy_close_rex.match(line): line = lines.next() if fun_def_rex.match(line): .... -- Regards, Diez B. Roggisch From EP at zomething.com Wed Oct 20 03:06:16 2004 From: EP at zomething.com (EP) Date: Tue, 19 Oct 2004 23:06:16 -0800 Subject: Luther Blisset In-Reply-To: <41747784$1@clarion.carno.net.au> References: <9jb8n014advbvs5n0li6lo1a0d4cedbcsp@4ax.com> <7nXcd.719$si.122@lakeread04> <41747784$1@clarion.carno.net.au> Message-ID: <20041019230616.39575413.EP@zomething.com> > The "situationist" email address was a always a giveaway. Very > clever! Ah, me thinks someone's been playing football without a proper helmet. :-) Does the inclusion of something like "(c) Luther Blissett, all rights reserved" in one's code do away with the need for GNU and GNU-like licensing? Have we been listening to lawyers when we should have been hanging out with the neo-(something) crowd? the later are bound to be more fun (he says having little experience with either) Luther: http://www.thefa.com/Features/EnglishDomestic/Postings/2003/07/54903.htm EP (effects of sea water on under-ocean Ethernet may cause degradation of humor and social revolution, some checks required) From emayo at home.com Wed Oct 27 14:40:58 2004 From: emayo at home.com (Pater Maximus) Date: Wed, 27 Oct 2004 14:40:58 -0400 Subject: Can not get urllib.urlopen to work Message-ID: <3JKdnSvPhssyduLcRVn-sg@comcast.com> I am trying to implement the recipe listed at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/211886 However, I can not get to first base. When I try to run import urllib fo=urllib.urlopen("http://www.dictionary.com/") page = fo.read() I get: Traceback (most recent call last): File "C:/Program Files/Python/Lib/idlelib/testurl", line 2, in -toplevel- fo=urllib.urlopen("http://www.dictionary.com/") File "C:\PROGRA~1\PYTHON\lib\urllib.py", line 76, in urlopen return opener.open(url) File "C:\PROGRA~1\PYTHON\lib\urllib.py", line 181, in open return getattr(self, name)(url) File "C:\PROGRA~1\PYTHON\lib\urllib.py", line 297, in open_http h.endheaders() File "C:\PROGRA~1\PYTHON\lib\httplib.py", line 712, in endheaders self._send_output() File "C:\PROGRA~1\PYTHON\lib\httplib.py", line 597, in _send_output self.send(msg) File "C:\PROGRA~1\PYTHON\lib\httplib.py", line 564, in send self.connect() File "C:\PROGRA~1\PYTHON\lib\httplib.py", line 548, in connect raise socket.error, msg IOError: [Errno socket error] (10061, 'Connection refused') From aurora00 at gmail.com Fri Oct 15 15:59:40 2004 From: aurora00 at gmail.com (aurora) Date: Fri, 15 Oct 2004 12:59:40 -0700 Subject: reloading updated modules in long running server? References: Message-ID: > I would put a big fat (possibly figurative) button on the application > somewhere and press it when I wanted the source updated. > > Jp Yeah why not. Sound like a simple solution. Thanks. From kendall at monkeyfist.com Wed Oct 6 13:21:28 2004 From: kendall at monkeyfist.com (Kendall Clark) Date: Wed, 6 Oct 2004 13:21:28 -0400 Subject: Question mark in variable and function names In-Reply-To: <1gl90yk.v91yz8w1z0b2N%aleaxit@yahoo.com> References: <1gl90yk.v91yz8w1z0b2N%aleaxit@yahoo.com> Message-ID: <20041006172128.GB29668@monkeyfist.com> On Wed, Oct 06, 2004 at 07:11:02PM +0200, Alex Martelli wrote: > Ruby has this convention and it seems to work wonderfully well for them. > I wish Python could grow it, too, but I don't think I stand any chance > of convincing Guido -- perhaps somebody else can. For my money this is *the* biggest syntactic wart in Python. I think ? and ! at the ends of function/method names is an insanely good idea that Python should steal. I'm not holding my breath, but it would be really great to at least have a community conversation about this. Best, Kendall Clark Managing Editor, XML.com From ialbert at mailblocks.com Fri Oct 8 13:15:02 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 08 Oct 2004 13:15:02 -0400 Subject: Desactivating Python keywords and built-in functions In-Reply-To: References: Message-ID: Andr? Roberge wrote: > Is there a simple way to desactivate Python keywords and built-in > keywords [e.g. eval()] Try rexec: http://docs.python.org/lib/module-rexec.html not fully safe but I might be enough. Istvan. From bokr at oz.net Sat Oct 30 23:28:52 2004 From: bokr at oz.net (Bengt Richter) Date: Sun, 31 Oct 2004 03:28:52 GMT Subject: "number-in-base" ``oneliner'' References: <1gmfz0k.a3xefz1xzms61N%aleaxit@yahoo.com> <41832f8b.1140475326@news.oz.net> <41834032.1144738587@news.oz.net> <418357db.1150795766@news.oz.net> Message-ID: <41845aa2.1217042835@news.oz.net> On Sat, 30 Oct 2004 09:02:14 GMT, bokr at oz.net (Bengt Richter) wrote: [... previous versions ...] Silly last best shot put the quotient in an unneeded box. Sorry for all the self-followups. I think I'll call this my best version (so far ;-): >>> def number_in_base(x, N=10, digits='0123456789ABCDEF'): ... return '-'[:x<0]+''.join([digits[r] for q in [abs(x)] ... for q,r in iter(lambda:divmod(q, N), (0,0))][::-1]) or '0' ... >>> number_in_base( 126, 2) '1111110' >>> number_in_base(-126, 2) '-1111110' >>> number_in_base(-126, 8) '-176' >>> number_in_base(-126,16) '-7E' >>> number_in_base( 1,16) '1' >>> number_in_base( 1, 2) '1' >>> number_in_base( 0, 2) '0' Regards, Bengt Richter From steve at holdenweb.com Tue Oct 26 18:04:41 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 26 Oct 2004 18:04:41 -0400 Subject: CGIHTTPServer always return 200, no redirects (302) possible In-Reply-To: References: Message-ID: Thomas Guettler wrote: > Hi, > > The CGIHTTPServer returns > > self.send_response(200, "Script output follows") > > before it starts the cgi process. This means > you cannot set the status header to 302 for > a redirect. > > I don't see a easy and portable way to fix this. > > CGIHTTPServer.py: > http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/CGIHTTPServer.py?rev=1.36&view=auto > > Maybe a little note in the docs would save some > people 30-60 minutes of their sparetime. > > Thomas > If you'd spent the time it took to post your message posting a doc patch instead then you'd have saved us boith some time ;-) regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From bingham at cenix-bioscience.com Thu Oct 7 05:58:49 2004 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Thu, 07 Oct 2004 11:58:49 +0200 Subject: correct way to detect container type In-Reply-To: <864d37090410070250210881d2@mail.gmail.com> References: <41650CAE.704@chamonix.reportlab.co.uk> <864d37090410070250210881d2@mail.gmail.com> Message-ID: <41651359.9070900@cenix-bioscience.com> Carlos Ribeiro wrote: >On Thu, 07 Oct 2004 10:30:22 +0100, Robin Becker wrote: > > >>I seem often to allow list/tuple arguments to be a singleton. This leads to code >>of the form >> >>if type(arg) not in (type(()),type([])): arg = [arg] >> >>or alternatively >> >>from type import ListType, TupleType >>_seqTypes = ListType, TupleType >>...... >>if type(arg) not in _seqTypes: .... >> >>is there a 'best' way to do this? >> >> > >Depending upon the way you're using your sequence types, why don't you >check for __getitem__? As far as I'm aware, it's all that is needed to >support for loops. In some cases __len__ may also be needed. The >advantage is that you will accept any user defined type that supports >the sequence interface. > > > > Careful! If all you are doing is: for x in arg: do something with x Then arg only needs to support __iter__ and need not be a sequence type nor support __getitem__. Aaron From tundra at tundraware.com Sun Oct 17 21:09:20 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 17 Oct 2004 21:09:20 EDT Subject: ConfigParser shootout, preliminary entry In-Reply-To: References: Message-ID: Michael Chermside wrote: > A few weeks ago, the suggestion was made on Python-Dev that it might be time > to consider replacing the ConfigParser module and that we should hold a > "shootout" (ie ask for implementations and see what we get). > > Since then I've been playing around with this... not the parsing part (which > so far I have completely ignored) but the programmer interface. There needs > to be a well-thought-out data model for the information stored, and the user > interface needs to be very easy to use, yet not so "magical" that it becomes > difficult to understand. > > I have put together what I think is probably my best proposal. It is based > on a superset of ini config files and java .property files. There is a > convenient access mechanism ("config.my_app.some_value") as well as more > general approaches ("config.values['my_app.serviceByPort.80']"). I have > tried to consider issues like unicode (I permit fairly lenient mixing of > unicode and str), and unit testing ("... call config.clear_all() in the > tearDown() method of any unittests that use the config module..."). I have > even considered carefully what to leave OUT (converting to non-string data > types, interpolating values, things like that). > > I think that I am now at the point where I could really use some input from > others. So I'd like to invite people to review my design and send me your > suggestions. I'm not expecting this as a *useful* module yet (it doesn't > yet parse files!), but it seemed like a good stage at which to ask for > feedback. I'm attaching two files, config.py and configTest.py, and they > are also available from these urls: > > http://www.mcherm.com/publish/2004-10-17/config.py > http://www.mcherm.com/publish/2004-10-17/configTest.py > > Thanks in advance for reviewing this. > > -- Michael Chermside > I doubt it conforms to your thinking on the matter, but some time ago I wrote and released such a creature of my own invention: https://www.tundraware.com/Software/tconfpy/ -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From gandalf at geochemsource.com Mon Oct 11 10:28:34 2004 From: gandalf at geochemsource.com (Gandalf) Date: Mon, 11 Oct 2004 16:28:34 +0200 Subject: kinterbase and stored procedure In-Reply-To: <2svii1F1qc0k9U1@uni-berlin.de> References: <2svii1F1qc0k9U1@uni-berlin.de> Message-ID: <416A9892.1050106@geochemsource.com> > cursor = kinterbasdb.connect(...) > cursor.excute(SPSETUP) > > But it seems that anything has problems with "SET TERM !!" expression > . If I use the DB SQL console, everything seems to be OK (the proc is > setup) Yes, that is true. The "SET TERM" command is not really a command that is processed by the backend. Please note that the terminator is used to separate commands. However, you will (normally) execute only one command at a time with "cursor.execute". So you should create your procedure without the "SET TERM". InterBase will surely know that this is only one command. You can try to run the "SET TERM" command in a separate "cursor.execute", but probably that is not needed. I had the same problem with Oracle triggers before - you must not place the ending "/" character when createing Oracle triggers from your own program. Please let me know if it helps. Best, Laci 2.0 From ville at spammers.com Mon Oct 25 13:18:44 2004 From: ville at spammers.com (Ville Vainio) Date: 25 Oct 2004 20:18:44 +0300 Subject: GPL and Python modules. References: <417d18bc$0$1313$a1866201@newsreader.visi.com> <417d1fd7$0$45534$a1866201@newsreader.visi.com> Message-ID: >>>>> "Grant" == Grant Edwards writes: Grant> That just doesn't sound right. That sentence pretty much summarizes the issue of GPL'd libraries. The most practical approach is to rather post a question about "is there a non-GPL'd version of around?" -- Ville Vainio http://tinyurl.com/2prnb From steve at holdenweb.com Tue Oct 12 21:00:42 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 12 Oct 2004 21:00:42 -0400 Subject: mxDateTime package question In-Reply-To: <991e921f.0410121213.213f0807@posting.google.com> References: <991e921f.0410121213.213f0807@posting.google.com> Message-ID: Prashant Pai wrote: > I have a Julian (?) date string '2000238' (format YYYYDDD) which > corresponds to 2000/08/25 > > How do I create a correct DateTime object with this? > > thanks You could try >>> jd = "2000238" >>> y = int(jd[:4]) >>> d = int(jd[4:])-1 >>> yd = mx.DateTime.DateTime(y) >>> dinc = mx.DateTime.DateTimeDeltaFromDays(d) >>> result = yd+dinc >>> result >>> but there may well be more efficient ways. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From steve_erickson at hotmail.com Fri Oct 15 09:37:59 2004 From: steve_erickson at hotmail.com (Steve Erickson) Date: 15 Oct 2004 06:37:59 -0700 Subject: Problem with logging module References: <78406811.0410130851.5cf73a75@posting.google.com> <78406811.0410140401.4d466185@posting.google.com> Message-ID: <78406811.0410150537.5173afd0@posting.google.com> Thanks a bunch for your patience and explanations. It would be nice if there was a method of checking the logger or handler for an instance of it: logger = logging.getLogger(name) if not logger.handler(dir + '/' + name + '.log'): logger.propagate = False handler = logging.FileHandler(dir + '/' + name + '.log') logger.addHandler(handler) "Diez B. Roggisch" wrote in message news:... > Steve Erickson wrote: > > > Thanks. Coming from C++, I thought that the local logger instance in > > each test method would go away when I went out of the context of the > > method. Sounds like the logging class in Python maintains artifacts > > that affect instantiations in other methods. Or maybe I'm confused > > about how Python handles local versus class variables. > > Nothing to do with python - its the way logging is designed, and it makes > sense: if at one place you attach the logger named foo.bar to a handler, > and at another place obtain a reference to foo.bar to log some stuff, you > don't want to reiterate the whole handler-attaching stuff. > > So you simply abused the logging module - just set up the logger once, and > then obtain a reference to it using logging.getLogger whenever you need it > - that totally rids you of your logger class, that so far doesn't do much > anyway. Like this: > > ------ > logger = logging.getLogger(name) > logger.propagate = False > handler = logging.FileHandler(dir + '/' + name + '.log') > logger.addHandler(handler) > > class Test: > > def test_me(self): > logger = logging.getLogger(name) > logger.debug("test_me") > > ------ From macrocosm at fastmail.fm Mon Oct 4 19:56:04 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Mon, 04 Oct 2004 19:56:04 -0400 Subject: Python Macros In-Reply-To: <864d370904100411551f0629c@mail.gmail.com> References: <41616B9B.1080009@fastmail.fm> <864d370904100411551f0629c@mail.gmail.com> Message-ID: <4161E314.9050700@fastmail.fm> Carlos Ribeiro wrote: >On Mon, 04 Oct 2004 11:26:19 -0400, Arich Chanachai > wrote: > > >>How hard/easy is it to extend the Python syntax? Perhaps there are >>macro facilities for this? I'd like to add messages and message >>passing, for example. >> >> > >Python doesn't support macros. This same question was raised before in >slightly different ways, and the historical answer seems to be that >macros are not in the plans, and that there are better ways to solve >problems than with macros. In fact, Python is *very* flexible, and >allows the clear expression of several interesting ideas and paradigms >without the need for macros. Could you share more information about >why do you think macros are the best solution for your problem? > > > > I could implement them myself by writing a module that would serve as a layer to permit usage of this sort of language construct. The issue is that I want to be able to use this functionality transparently (without knowing anything about or making any references to this module). From peter at engcorp.com Thu Oct 21 06:49:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Oct 2004 06:49:41 -0400 Subject: python 2.1 and 2.2 In-Reply-To: References: Message-ID: Maurice Ling wrote: > I remembered reading somewhere that Guido had demonstrated a significant > speed increase from python 2.1 to python 2.2 (or something like that). > Anyone knows how is the test done? Is it using pystone.py? http://www.python.org/doc/2.3/whatsnew/node17.html#SECTION0001720000000000000000 See section on Optimization. From bob at codeblitz.com Tue Oct 12 18:50:05 2004 From: bob at codeblitz.com (Bob Follek) Date: Tue, 12 Oct 2004 18:50:05 -0400 Subject: list comprehension for splitting strings into pairs References: Message-ID: On Tue, 12 Oct 2004 16:11:45 -0600, Steven Bethard wrote: >Here's what I'm doing: > >>>> lst = ['1', '1:2', '3', '-1:4'] >>>> splits = [] >>>> for s in lst: >... pair = s.split(':') >... if len(pair) != 2: >... pair.append(None) >... splits.append(pair) >... >>>> splits >[['1', None], ['1', '2'], ['3', None], ['-1', '4']] > >Basically, I want to split each string into two items, substituting >None when no second item is specified in the string. (As you can see, >in my strings, the items are delimited by ':'). > >It seems like a simple enough operation that I should be able to write >a list comprehension for it, but I can't figure out how... Any >suggestions? > >Steve Here's a pretty nasty approach: >>> lst = ['1', '1:2', '3', '-1:4'] >>> splits = [(e.split(':') + [None])[:2] for e in lst] >>> splits [['1', None], ['1', '2'], ['3', None], ['-1', '4']] -- Bob Follek bob at codeblitz.com From irmen at -nospam-remove-this-xs4all.nl Mon Oct 11 17:44:55 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 11 Oct 2004 23:44:55 +0200 Subject: ANN: Snakelets 1.35 (simple-to-use web app server with dynamic pages) In-Reply-To: References: <416ae4b9$0$78749$e4fe514c@news.xs4all.nl> Message-ID: <416afed7$0$10528$e4fe514c@news.xs4all.nl> Alan Kennedy wrote: > Irmen, > > Thanks for your all your great work on Snakelets. You're welcome, it's been a pleasure to do so :) > Have you considered maybe porting Snakelets to WSGI? WSGI is a new > server/gateway standard for portability of python web frameworks, and is > specified in PEP 333. > > http://www.python.org/peps/pep-0333.html Errm, I was only very vaguely aware of something like the WSGI, and apparently totally missed the surfacing of PEP 333. Thanks for dropping the link, I will certainly study it. Based upon your comments below, I'm almost certain that there will be some form of WSGI in a future Snakelets version. Disclaimer for the next few questions: I haven't yet read PEP-333. > WSGI specifies a HTTP API which is implementable on most conceivable web > platforms. Code built on this API is fully portable to [...] Does it achieve this by providing a least common denominator featureset? How does it deal with the way the server is structured (threading, sessions, shared resources)? I'm sorry- if this is in PEP-333, I'll find out soon enough :) > Porting to WSGI would bring the following benefits > > 1. The ability to run Snakelets under any WSGI server/gateway, e.g. > mod_python, CGI, BaseHTTPServer, etc, etc. (No WSGI adapters seem to > exist for Twisted, Medusa or Zope though: the asynch API is still under > discussion on the web-sig). Users of asynch-API servers usually smile broadly when confronted with worried users of 'old-skool' multiprocessing or multithreading servers. It is my understanding that the latter server type (which Snakelets is also a part of) doesn't scale very well to many concurrent connections. If that is true, it seems to me that WSGI should somehow also provide for the asynch programming style, because the "big guys" will be using that one? Or am I way off here? > 2. The ability to factor out the need (and maintenance burden, security > exposure, etc) for a custom standalone server, i.e. instead use a > standard server, e.g. BaseHTTPWSGIServer, and get automatic threading or > forking support, etc. I'm not sure how WSGI should help me achieve this. I thought that it was an API for web application builders.... not for the implementors of the application server? > 3. Possibly run Snakelets on Java/Jython! The latter is only possible if > Snakelets is 2.1 compliant, i.e. does not use python 2.2 or 2.3 features. Too bad, I'm using generators (amongst others) and those are unavailable in Python 2.1. I have no intentions of backporting to Python 2.1. > I have high hopes for WSGI to help simplify the confusing landscape of > server platforms upon which python web frameworks can and cannot run. It certainly sounds promising. Cheers! --Irmen. From aleaxit at yahoo.com Fri Oct 22 15:20:30 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 22 Oct 2004 21:20:30 +0200 Subject: backslash plague References: <2tt4b2F24cffeU1@uni-berlin.de> Message-ID: <1gm2tuh.sg3fl11rm2newN%aleaxit@yahoo.com> Luis P. Mendes wrote: ... > I've already read many pages on this but I'm not able to separate the > string 'R0\1.2646\1.2649\D' in four elements, using the \ as the separator. x = r'R0\1.2646\1.2649\D' elements = x.split('\\') > and why must I write two '' after the \? If I hadn't used r I would > understand... A raw literal can't end with an odd number of backslashes (_some_ way has to be there to escape the quote char, after all). > how should I do it? I think the string's split method, as above, is the simplest, fastest way. Alex From kraus at hagen-partner.de Wed Oct 13 11:06:50 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed, 13 Oct 2004 17:06:50 +0200 Subject: convert string to list In-Reply-To: References: Message-ID: Jochen Hub wrote: > Hi, > > I am a real beginner in Python and I was wondering if there is a way to > convert a string (which contains a list) to a "real" list. > > I need this since I would like to give a list as an argument to my > Python script from the bash: > > #!/usr/bin/python > import sys > argument1 = sys.argv[1] > thelist = ???(argument1) > > and then call the script from the bash like this > > thescript.py ["A","B","C"] > > Thanks you, > Jochen If you are sure that the list always looks that way: >>> l = '["A","B","C"] ' >>> l[1:-2].replace('"','').split(',') ['A', 'B', 'C'] HTH, Wolfram From __peter__ at web.de Mon Oct 25 11:23:09 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 25 Oct 2004 17:23:09 +0200 Subject: Pythonic function composition References: <10nq3c4j3lst8e2@corp.supernews.com> Message-ID: Alan G Isaac wrote: > Given a list of functions, it seems there must be a > Pythonic approach to composition. Something like > > def compose(fns): return lambda x: reduce(lambda f,g: f(g),fns)(x) > > This will not work because the argument 'x' is not "inside". > What is the proper formulation? You need to pass a function that makes a function (a "factory") to reduce(): >>> fns = [lambda x: x+2, lambda x: x*2, lambda x: x*x] >>> def compose(f, g): ... def fog(x): ... return f(g(x)) ... return fog ... >>> g1 = reduce(compose, fns) >>> g1(2) 10 The same with lambdas: >>> g2 = reduce(lambda f, g: lambda x: f(g(x)), fns) >>> g2(2) 10 Peter From alikakakhel3 at hotmail.com Mon Oct 4 20:45:23 2004 From: alikakakhel3 at hotmail.com (Ali) Date: 4 Oct 2004 17:45:23 -0700 Subject: How do you write this in python References: <8f17f4bc.0410022000.e331cbe@posting.google.com> <41603d90_1@newsfeed.slurp.net> Message-ID: <8f17f4bc.0410041645.630ee821@posting.google.com> ok that looks close but can someone explain it to me section by section please? From adalke at mindspring.com Tue Oct 26 02:33:30 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 26 Oct 2004 06:33:30 GMT Subject: int/long unification hides bugs In-Reply-To: References: <940ee3e8.0410250456.65445bbd@posting.google.com> <1gm8jkc.7gtvc31avo0xhN%aleaxit@yahoo.com> <940ee3e8.0410252025.34e671d9@posting.google.com> Message-ID: <_cmfd.2728$kM.39@newsread3.news.pas.earthlink.net> Cliff Wells wrote: > Then Python clearly needs a special mode so that when a person's age is > entered large numbers are allowed, but when counting animals it throws > an exception if the number is greater than two. Unless of course the count is of a clean animal, in which case the exception limit is greater than seven. Andrew dalke at dalkescientific.com From somewhere at on_earth.in_space Wed Oct 20 23:53:28 2004 From: somewhere at on_earth.in_space (anonymous) Date: Wed, 20 Oct 2004 20:53:28 -0700 Subject: converting idl files to C++ question Message-ID: <1098330811.177193@news-1.nethere.net> Has anyone written a Python module to parse a folder for idl files, then convert to C++ source or headers? Can the module parse idl files referenced inside the idl file too? From carribeiro at gmail.com Wed Oct 20 07:35:02 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 20 Oct 2004 08:35:02 -0300 Subject: Free hosting for Python open-source projects In-Reply-To: References: <864d370904101914067b7a1728@mail.gmail.com> Message-ID: <864d37090410200435765736fb@mail.gmail.com> On Tue, 19 Oct 2004 15:35:19 -0500, John Hunter wrote: > >>>>> "Carlos" == Carlos Ribeiro writes: > > Carlos> I'm sure this question has been posted before, but the > Carlos> answer will probably be out of date, so here it goes. > > How about an October 11th posting on the same topic with 4 reponses > > Google is your friend > > 1) http://groups.google.com > > 2) hosting group:*python* -> "Google Search" > > 3) Sort by date > > The 5th or so link, "Where to host an open source project? > Sourceforge? " discusses hosting, with subversion information, etc.... Thanks for the reply, and sorry to waste bandwidth. BTW, your very own post is now #3 on my query. Fast to update the index, isn't it? http://groups.google.com/groups?q=group%3A*python*+host+open+source+project&hl=en&btnG=Google+Search -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From richie at entrian.com Thu Oct 7 10:07:50 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 07 Oct 2004 15:07:50 +0100 Subject: ctypes, error when calling function In-Reply-To: <4165275e$0$285$edfadb0f@dread12.news.tele.dk> References: <4165275e$0$285$edfadb0f@dread12.news.tele.dk> Message-ID: [Max] > caps = MIDIOUTCAPS() > [...] > print winmm.midiOutGetDevCapsA(deviceID, caps, sizeof(caps)) > [...] > ValueError: Procedure probably called with too many arguments (60 bytes > in excess) You need to pass byref(caps) rather than caps. The API expects a pointer to the structure, not the structure itself. -- Richie Hindle richie at entrian.com From grante at visi.com Mon Oct 25 16:52:00 2004 From: grante at visi.com (Grant Edwards) Date: 25 Oct 2004 20:52:00 GMT Subject: GPL and Python modules. References: <417d18bc$0$1313$a1866201@newsreader.visi.com> <417d4471$0$524$a1866201@newsreader.visi.com> <417d48f6$0$1324$a1866201@newsreader.visi.com> <2b-dnQaA6rzh0eDcRVn-gQ@powergate.ca> <417d4f75$0$45524$a1866201@newsreader.visi.com> <417d5862$0$45532$a1866201@newsreader.visi.com> Message-ID: <417d6770$0$513$a1866201@newsreader.visi.com> On 2004-10-25, Jorge Godoy wrote: > Grant Edwards writes: > >> On 2004-10-25, Peter Hansen wrote: >>> >>> Evil, nasty customers, we hates them! They asks us questions >>> and pays us money for our precioussssss time. >> >> Except they don't. (Pay that is.) > > And I thought that just us down here didn't get paid for work and had to > go after the customer to receive... It's not really that. The situation is more like: Customer orders A. Customer pays for A. Customer needs support for A. Customer gets support for A. No problem, so far. You give customer some GPL software B along with written statement that free support is not provided for B. Customer want's help with B. Sales is _not_ going to let you tell Customer that you don't provide support for B. -- Grant Edwards grante Yow! Is there something at I should be DOING with a visi.com GLAZED DONUT?? From jcarlson at uci.edu Thu Oct 21 15:20:51 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 21 Oct 2004 12:20:51 -0700 Subject: Actual memory used by an object --- How to Determine? In-Reply-To: References: Message-ID: <20041021122003.0AC5.JCARLSON@uci.edu> Peter Hansen wrote: > Josiah Carlson wrote: > > zooko at zooko.com wrote: > > > >>Here some some functions I've used to analyze memory usage in the past. > >> > >>http://mnetproject.org/repos/pyutil/pyutil/memutil.py > > > > The site is down. > > Worked from here, both before and after your post. Try again? It seems to be up from here now. Maybe my University's DNS is being ornery today. - Josiah From alan.gauld at btinternet.com Thu Oct 21 19:05:21 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Oct 2004 23:05:21 +0000 (UTC) Subject: Python + Java knowledge References: <4175ed72$1@news.unimelb.edu.au> Message-ID: On Wed, 20 Oct 2004 04:45:42 GMT, Maurice LING wrote: > I am amazed about people like Eric Raymond that can pick up and use a > dozen language, how did they do it? Not that amazing, most imprerative programming languages(which is most programming languages!) are very similar. Once you know how to do variable declarations, IO, loops, branches and functions you can start writing code. After that the big lhurdle is learning the library and thats down to practice mainly. > It is equally amazing that > programming jobs these days require half a dozen programming languages > known. Again not really. Most reasonable sized projects will use multiple languages. Certainly the minimum number of languages on a single project I've worked on was 5 (C, awk, c-shell, SQL, DOS) and I've been on several with over a dozen. The wackiest was 16 languages - but that was frankly excessive and an indication of poorly coordinated design more than necessity. > I came with a background in Pascal and bits of C, and some xBase > languages, then picked up Java and Python. Are you sure you don't know some SQL and DOS Batch language, or Unix shell dialects? And if you know Java and C then C++ is but a step away... Add those to your 5 and suddenly you know 9 and a dozen languages doesn't seem so far away does it? :-) > As mentioned in my post on 'reverse jython', I am envisioning the day > where mixed language programming is a reality. It already is and has been. Unix has always had easy intregration of C and Fortran. Topspeed used to sell PC compilers where C, C++, Pascal, & Modula 2 all shared the same object code format so you could mix n match modules easily. UCSD Pascal also apparently had a bytecode level compatibility with a couple of other languages but I never used that. And now .NET is playing the same game under Windows... There is nothing new under the sun. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From richardblackwood at cloudthunder.com Sun Oct 10 10:20:09 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 10 Oct 2004 10:20:09 -0400 Subject: Init a table of functions In-Reply-To: References: <1097371939.905273@mystique.esoterica.pt> <4168A727.6050606@cloudthunder.com> Message-ID: <41694519.3060004@cloudthunder.com> Michael Hoffman wrote: > Richard Blackwood wrote: > >> Now that I think of it some more, why did you add that object arg? >> That's not necessary. > > > It gets you a new-style class instead of an old-style class, and it is > a good habit to have. > > http://www.python.org/2.2.3/descrintro.html Why a necessary good habit? From ialbert at mailblocks.com Wed Oct 27 08:56:56 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 27 Oct 2004 08:56:56 -0400 Subject: Open Source License Question In-Reply-To: <2u9hklF24n4b1U1@uni-berlin.de> References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <2u9hklF24n4b1U1@uni-berlin.de> Message-ID: Joachim Bowman wrote: > These two don't go together. Read "6. No Discrimination Against Fields > of Endeavor" in "The Open Source Definition"[0]. > [0] http://www.opensource.org/docs/definition.php Yay, another thread on software licensing. By the way Fuzzy, just release your software with your own licensing scheme. If you don't like any of the available OSI licenses then don't use them, as simple as that. On one hand "OSI approved" means very little on the other people do not completely understand these licenses anyway, the long, recurrent GPL related threads demonstrate that. Istvan. From richardblackwood at cloudthunder.com Sun Oct 17 20:02:16 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 17 Oct 2004 20:02:16 -0400 Subject: Reimplenting Linux Kernel in Python In-Reply-To: <4172d7c8.69432128@news.oz.net> References: <10mrba51r9dql4f@corp.supernews.com> <10mt60mhr42rl09@corp.supernews.com> <10mu6uje93pk152@corp.supernews.com> <416f29c3.285069358@news.oz.net> <4172d7c8.69432128@news.oz.net> Message-ID: <41730808.1020507@cloudthunder.com> An HTML attachment was scrubbed... URL: From rattan at cps.cmich.edu Mon Oct 25 17:53:55 2004 From: rattan at cps.cmich.edu (Ishwar Rattan) Date: 25 Oct 2004 14:53:55 -0700 Subject: Global variables.. Message-ID: <938a4680.0410251353.64578a27@posting.google.com> Say I have two pythom modules in separate files: main.py -> contains main() modules and uses a global variable (say a) incr.py -> contains incre() that changes the value of global variable a (called in main()) Is there a way to reflect the change in main()? I tried it by placing variable a in a file of its own a.py which imported in both main() and incr(): ---main.py-- from a import * from incr import * def main(): global a print a incr() print a ---incr.py-- from a import * def incr(): global a a = a + 100 print 'incr: ', a ---a.py-- a = 123 --- Second print in main() displayes 123 -> as if a was not updated by incr() Any ideas to make it work? -ishwar From k04jg02 at kzoo.edu Fri Oct 8 15:27:03 2004 From: k04jg02 at kzoo.edu (dataangel) Date: Fri, 08 Oct 2004 15:27:03 -0400 Subject: Desactivating Python keywords and built-in functions In-Reply-To: References: Message-ID: <4166EA07.3090706@kzoo.edu> Andr? Roberge wrote: >In short: >Is there a simple way to desactivate Python keywords and built-in >keywords [e.g. eval()] > >Longer description: >I want to use a subset of Python as an embedded language and don't >want the users to have access to the rest of the language. One >approach I thought of using would be something along the following >lines: > >read in the script for the user; >scan for "forbidden" keywords or expression; >if found, give an error message and stop; >otherwise, let Python interpret the code. > >Before I jump and start coding, I thought I would ask people that know >more about these things than me >(which means probably 97.2% of the readership of comp.lang.python ;-) > >Andr? > > This doesn't exactly qualify as simple, but depending on how modular the source is, it might be possible to simply comment them out and recompile. There ought to be some way of doing this, I'd love to see a Python interface to Robocode :D From jcarlson at uci.edu Mon Oct 25 17:11:20 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 25 Oct 2004 14:11:20 -0700 Subject: Unqualified global vars, how? In-Reply-To: References: Message-ID: <20041025131103.0B1D.JCARLSON@uci.edu> "Christopher J. Bottaro" wrote: > > >From the python programming FAQ, I learned you can do this: [snip example] > But python complains that gv isn't defined yet. Is what I want to do > possible? I just want one module (file) with a bunch of globals vars and > to able to access those global vars without qualify them the module name. > > Thanks for the help. Quick answer: yes it is possible. Long answer: C:\Temp>cat > Globals.py class GV: val = 0 def __iadd__(self, arg): self.val += arg return self def __repr__(self): return repr(self.val) gv = GV() C:\Temp>cat > A.py from Globals import gv class A: def __init__(self): global gv print gv gv += 1 C:\Temp>cat > B.py from Globals import gv class B: def __init__(self): global gv print gv gv += 1 C:\Temp>cat > main.py import A import B a = A.A() b = B.B() C:\Temp>main.py 1 2 C:\Temp> From clifford.wells at comcast.net Thu Oct 21 21:43:32 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 21 Oct 2004 18:43:32 -0700 Subject: Some more notes In-Reply-To: <10ngn6n6tgd5k28@corp.supernews.com> References: <5c882bb5.0410211416.5a4a3c66@posting.google.com> <10ngn6n6tgd5k28@corp.supernews.com> Message-ID: <1098409412.6627.89.camel@devilbox.devilnet.internal> On Thu, 2004-10-21 at 18:07 -0700, Jeff Shannon wrote: > bearophile wrote: > > >I think some things are better in Delphi/Pascal > > > > They may well be better _in_ Delphi/Pascal. That doesn't mean that > adding them into Python will make Python a better language. (I love > garlic. I love chocolate. I do not want to eat chocolate-covered > garlic cloves, nor garlic-flavored chocolate bars.) Well, that's a matter of personal taste. Garlic is good on *everything*. > >2) Adding "case var of:" can be useful. > Not sure exactly what this is, but if you're referring to a case/switch > construct: using a dict of functions is (IMO) a better and cleaner way > of implementing the same idea. For many things this is true (and I use function lookup tables frequently). However it doesn't as conveniently cover all use cases that switch/case does (as it requires a function definition for each item). While it's also true that if/elif/else can be used instead for these other cases, I personally find switch/case far cleaner looking (when there are more than five or six conditions to test). Also, I'd be reluctant to claim that the dictionary lookup is cleaner (it looks more cluttered to my eye), but rather, more flexible (items can be dynamically added to the list). Regards, Cliff -- Cliff Wells From adijkstra at baanders NOSPAM consultancy.nl Thu Oct 7 03:46:47 2004 From: adijkstra at baanders NOSPAM consultancy.nl (duikboot) Date: Thu, 07 Oct 2004 09:46:47 +0200 Subject: End of file In-Reply-To: <6a13a506.0410062329.5de9e695@posting.google.com> References: <6a13a506.0410062329.5de9e695@posting.google.com> Message-ID: <4164f407$0$5963$d4d0a361@news.speedlinq.nl> Kat wrote: > Hi , > How do you identify the last line of a file? I am in a "for" loop and > need to know which is the last line of the file while it is being read > in this loop. > > Thanks > Kat f = open("test.txt").readlines() lines = len(f) print lines counter = 1 for line in f: if counter == lines: print "last line: %s" % line counter += 1 -- http://www.baandersconsultancy.nl | http://www.nosonis.com From emayo at home.com Thu Oct 21 13:02:55 2004 From: emayo at home.com (Pater Maximus) Date: Thu, 21 Oct 2004 13:02:55 -0400 Subject: How can I do French and English Spell Checking using MS Word from Python References: Message-ID: <5O2dnbI66-z9c-rcRVn-gw@comcast.com> I am a newbie to Python and do not understand COM so forgive the irrelevant details encluded below: Well I thought I had the problem solved, but it stopped working for both Dispatch and EnsureDispatch. The code is: import win32com.client import msword9 #msword = win32com.client.Dispatch("Word.Application") #msword.Selection.LanguageID=1033 msword = win32com.client.gencache.EnsureDispatch ("Word.Application") msword.Selection.LanguageID = 1033 Here is what happened. * I added German language spell checking to Word and started getting AttributeError: 'NoneType' object has no attribute 'LanguageID' * Since my source was unchanged, I figured I had better rebuild some stuff. Ran makepy as follows C:\Program Files\Microsoft Office\Office>"c:\program files\python\lib\site-packages\win32com\client\makepy.pyc" msword9.olb > "c:\program files\python\msword9.py" Generating to C:\PROGRA~1\PYTHON\lib\site-packages\win32com\gen_py\00020905-0000 -0000-C000-000000000046x0x8x1.py that is 1445KB It also produced the .pyc version of the above with 1542KB c:\program files\python\msword9.py with 0 bytes c:\program files\python\msword9.pyc with 218 bytes 00020905-0000-0000-C000-000000000046x0x8x1.py has "Selection" defined and "LanguageID" is a property but they are not being found. However, the following command seems to find the library >>> win32com.client.gencache.EnsureDispatch("Word.Application") What am I doing wrong??? Thanks... From martin at v.loewis.de Fri Oct 1 13:21:54 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Oct 2004 19:21:54 +0200 Subject: should these be fixed for python 2.4? In-Reply-To: References: Message-ID: <415d9229$0$18966$9b622d9e@news.freenet.de> Alexander Schmolck wrote: > 1. ``os.system`` (and co): Shouldn't ``os.system``'s signature really be > ``os.system(cmd, arg1, arg2,...)`` rather than ``os.system(some_string)``? No. This is a direct exposition of the system(3) function of the C library, and has precisely the same interface like this function. Use os.spawnv for what you want. > 2. pydoc's handling of overriden methods without docstrings: I really think it > should show the documentation of the method in the baseclass; the current > behavior really sucks when working with things like backends. Feel free to contribute a patch. > I currently use this to run e.g. latex, but it doesn't seem to work absolutely > reliably and is unix only. I'm pretty sure there must be a better way. I don't think there is. Regards, Martin From Doran_Dermot at emc.com Mon Oct 25 07:37:21 2004 From: Doran_Dermot at emc.com (Doran_Dermot at emc.com) Date: Mon, 25 Oct 2004 12:37:21 +0100 Subject: Implementing class attribute access methods via pseudo-functi on o verloading. Message-ID: <97B6410BE753D411894E00D0B77E6F7F018DCCFD@neam2mx1.isus.emc.com> Hi Michael, First of all thanks for letting some light penetrate the rock I've been hiding under :-) I'd completely ignored or forgotten about Properties. I'll study them and see if I like them. It's interesting to note that you prefer code like: theProblem.title = "The Title" However, I wonder if people coming from the Java/C++ world prefer: theProblem.title( "The Title" ) Obviously the first version is less typing! However, the second version might feel more natural to Java/C++ programmers. Just an observation! Cheers and thanks again!! -----Original Message----- From: python-list-bounces+doran_dermot=emc.com at python.org [mailto:python-list-bounces+doran_dermot=emc.com at python.org]On Behalf Of Michael Hoffman Sent: 25 October 2004 12:10 To: python-list at python.org Subject: Re: Implementing class attribute access methods via pseudo-function o verloading. Doran_Dermot at emc.com wrote: > I've seen lots of code in which the attributes of a class are accessed and > modified using two separate methods. For example: I think this is a great illustration of what properties can be used for: http://www.python.org/2.2.2/descrintro.html#property Then you can reduce your class to: class Problems: def __init__(self, refNum): self._refNum = refNum This is a LOT less code. And use theProblem.title, theProblem.problem without any apparent function calls. As far as those fancy accessor methods go, YAGNI. If you do need them later, you can always add them: def _get_title(self): return self._title def _set_title(self, title): assert isinstance(title, basestring) self._title = title title = property(_get_title, _set_title) I would much rather use theProblem.title = "the title" rather than theProblem.title("the title"). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list From ndbecker2 at verizon.net Thu Oct 7 07:34:32 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Thu, 07 Oct 2004 07:34:32 -0400 Subject: properties and inheritance Message-ID: It seems that properties, as implemented in 2.3, don't behave as I'd expect with respect to inheritance: class A (object): def f(self): print "A" doF = property (fget=f) class B(A): def f(self): print "B" b = B() b.doF : prints "A" Is there a rationale for this? I would have thought that if properties are a shorthand for calling functions, and functions are polymorphic, then why are properties not? Doesn't that make properties behaviour inconsistent with other attributes? From danperl at rogers.com Wed Oct 6 19:08:13 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 6 Oct 2004 19:08:13 -0400 Subject: difficult zipefile Question References: Message-ID: I'm going to take a break and have dinner. My words are what's on the menu. Dan "Michael Hoffman" wrote in message news:ck1tfn$q64$1 at gemini.csx.cam.ac.uk... > matthiasjanes wrote: >> def zipit(path, ziper): >> >> for root, dirs, files in os.walk(path): >> >> for anyFile in files: >> >> fullname = os.path.join(root, anyFile) > > Where is the "ziper" variable used? I don't see how this code does > anything except create an empty zipfile. > > $ python samplecode.py > > $ unzip test.zip > Archive: test.zip > warning [test.zip]: zipfile is empty > > If you Google for you will find a python-list thread with > this solution in it: > > http://mail.python.org/pipermail/python-list/2003-June/170526.html > > Alternatively you could submit a patch or a bug. > > HTH, > -- > Michael Hoffman From aleaxit at yahoo.com Tue Oct 19 04:58:12 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 19 Oct 2004 10:58:12 +0200 Subject: Python capability do like plugins ? References: <1glurfj.zi6798qu4p2fN%aleaxit@yahoo.com> Message-ID: <1glwgve.20tqi2sdvlc0N%aleaxit@yahoo.com> Leon wrote: > Thanks..... > I use a simple method... > > sys.commands module --> get file list > re module --> filter file name and path > imp module --> load module > getattr() --> get varabiles > > because none dll for unix, I don't know how to use *.pyd > and how to make *.pyd from *.py Not sure what you mean by "because none dll for unix". A *.pyd on Windows is a DLL (meant for Python extension); you cannot make it from a *.py, you make it from a *.c or the like. Equivalent on different Unix variants are *.so, *.dynlib, and others yet. Alex From jeff at ccvcorp.com Wed Oct 6 14:44:01 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 06 Oct 2004 11:44:01 -0700 Subject: Embedding python with debugging features In-Reply-To: References: Message-ID: <10m8f48jrj8lc42@corp.supernews.com> Peter wrote: >I'm considering to embed python in an application written in c++ and use it >as a scripting language. >Is it possible to provide debugging features? > > Is your intent that your host (C++) application be able to be controlled by (internally run) Python scripts, and that you want said host application to support debugging of the Python scripts? In that case, though I don't know any details, I would say "Yes," this is possible to do. Given that PythonWin (a mixed C++/Python app) supports a fairly decent debugger, I can't imagine any technical reason why your app couldn't do much the same thing. Indeed, you might do well to study PythonWin's debugging code to get some ideas about implementing your own. (IIRC, PythonWin should be available under the standard Python license, which I believe would allow you to legally borrow from its code... though you might want to verify this before you go digging.) Jeff Shannon Technician/Programmer Credit International From JSmuts at clover.co.za Tue Oct 5 03:25:11 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Tue, 5 Oct 2004 09:25:11 +0200 Subject: New to Python: Features (way OT) In-Reply-To: <41622c67$0$59863$a1866201@newsreader.visi.com> Message-ID: Thanks guys, I must admit I found the c# grammer school more entertaining, but this one was fun too. jaco -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Sat Oct 23 05:37:58 2004 From: bearophileHUGS at lycos.com (bearophile) Date: 23 Oct 2004 02:37:58 -0700 Subject: Some more notes References: <5c882bb5.0410211416.5a4a3c66@posting.google.com> Message-ID: <5c882bb5.0410230137.6c82768f@posting.google.com> Istvan Albert: >No you can't. Your suggestions are driven by nothing else >but your desire to make Python resemble Pascal since >that is the language that you are accustomed to. You are right, I'm just a newbie in Python, and there are other languages than I know a bit better, like Delphi. Like natural languages, computer languages have a personal "soul" (grammar core, etc), but they also keep copying other languages, to improve, etc. ----------- Cliff Wells: >Actually, since the assignment operator is used far more often than the >equality operator, making it require three keystroke rather than just >one is a bad idea. Right, still, from a mathematical/formal point of view, Pascal syntax is better here :-] >Use string interpolation. Okay, I'll learn to use it more often. >>2) Adding "case var of:" can be useful. >Not familiar with this construct. If you mean "switch/case" as in C (or >some variation of same), then I absolutely agree. Yes, it's the Delphi/Pascal version of it. >Occasionally useful. Not enough to put it high on my list of things I'd >like to see in Python, but I can see its utility for making *slightly* >more logical code (versus the "while True: if x: break" idiom). I agree, it's not essential, but it can be useful :-) >Why not just use "/"? Okay, I'll use os.path.normcase to convert them. >but there are plenty of things to confuse newbies, Reducing non-obvious, magic or not-standard behaviours is quite necessary inside a language, it helps non-newbies too, making the language more conceptually transparent. Sometimes such non-standard behaviours can be useful to improve language speed or other things, but they have to reduced to the minimum possible. Python often prefers transparency, even when there are many (worse and more opaque, but maybe faster) ways to do things. This is positive for a hi-level language. So making a hi-level language like Python more transparent can be a way to improve it :-) Mathematica is more transparent than Python (its hashes can process everything, it has just a mutable list type and not tuples, assignment copies the object, and it's more functional so there are much less problems with globals and side effects, etc. but it can still be used with imperaive programming) and often it's also faster, but it's far from free (and its can be worse to do "real" programming, etc) :-] Note: Mathematica can be used with a quite powerful "pattern matching programming", I don't know if such thing (or a subset of it) can be useful to add to Python. >there is a logical explanation that suffices in >place of breaking tons of Python code. There are logical explanations for everything (because everything must be executed by the processor), but for humans some things are more logical than others :-) Python 3.0 already breaks lots of things, even division operators, so that's the best occasion to improve/change/fix things. ----------- Jeff Shannon: >using a dict of functions is (IMO) a better and cleaner >way of implementing the same idea. I don't know... The Case syntax can be something like: Case : 1: DoSomething1 range(2,23): DoSomething2 else: DoSomething3 (Etc. There are many other possibilities, like the Switch, etc). >it's not hard to achieve the same thing with >'while 1: if cond: break' . Python's designer made a deliberate >decision to minimize number of different types of loop structures to >use, since they tend to be very easy to convert between and fewer types >means less to learn. So we have two -- one that loops based on the >status of a condition, and one that iterates over each object in a >sequence. Minor variations on these themes are (according to Python >philosophy) better done by explicitly stating the rules, rather than by >creating new syntax for each variation. Okay... I'll use the 'while 1: if cond: break' >Except that having mutable types be shared this way can be a useful feature.< It looks more dangerous than useful. And assignments of non-mutable types can still be accepted. >Having a += x mean in-place modification >while a = a + x creates a new object allows both options to be >easily accessible without function-call syntax. Okay, the manual I've read wasn't clear enough about this :-) >Having these >as functions instead of methods is much simpler for Python's dynamic >type system. For example, >new sequence types don't need to define min() >and max() methods -- the existing builtins just work. It also means >that implementation details of the function can be improved without >requiring a rewrite of every class that has ever defined a len() method, Okay. Thank you for the info. I still prefer Python to Ruby (a more pure OO language, I think). >Remember, there's a lot more to good language design than just "Ooh, >this piece might be useful!" You also have to consider how all the >pieces fit together, I agree, sometimes adding things is positive, and sometimes it's not good. Things have to be discussed by people expert on the language (and I'm a newbie), but I am here to learn too :-) ("pattern matching programming" can be one of such things.) ----------- Cliff Wells: >While it's also true that if/elif/else can be used instead for >these other cases, I personally find switch/case far cleaner looking >(when there are more than five or six conditions to test). >[...] >Also, I'd be reluctant to claim that the dictionary lookup is cleaner >(it looks more cluttered to my eye), but rather, more flexible (items >can be dynamically added to the list). I agree. ----------- David M. Cooke: >Also, adding a , to the end of the print statement will suppress the >newline (although, not the space between the two calls). Right, I've forgot it :-) >"can be" is the operative phrase here. It's not necessary.< Well, OOP and lots of other things (inside Python too) aren't necessary. I was discussing mostly about things that can be useful. >Chained if/elif/elif works fine for small cases; for larger, >you should probably use a dict, or rewrite to use a class. Uhm... I'll try with the dictionary. >Really, while loops and repeat until loops are special cases of the >much more useful loop-and-a-half: >while True: > ... some stuff ... > if condition_true: > break > ... more stuff ... I'll use it, but I think it's really ugly. It looks like the old spaghetti code with GOTOs :-] Thank you for the answers and explanations, a handshake to Cliff and bear hugs to everybody else, bearophile (remove HUGS if you want to mail me directly) From peter at engcorp.com Tue Oct 19 16:44:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 19 Oct 2004 16:44:01 -0400 Subject: Python Newbie In-Reply-To: References: Message-ID: abhay wrote: > I am confused between learning Python or learning Perl. Please any view, > opinions and suggestions are welcomed. While I trust you are aware of the likely answer you'll get, asking in a Python newsgroup whether one should learn Python, it would be most helpful if you offered up at least one tiny, small snippet of information about what you want to *accomplish* with your chosen language... If, for example, you need to use Perl in a school environment, I wouldn't hesitate to suggest that you... (guess)... learn Perl! -Peter From aleaxit at yahoo.com Mon Oct 25 15:22:54 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 25 Oct 2004 21:22:54 +0200 Subject: Python vs PHP References: <41790054$0$203$edfadb0f@dread12.news.tele.dk> <8LidnXE_n6jmm-TcRVn-1A@giganews.com> <1gm2nnu.pulnabm1193eN%aleaxit@yahoo.com> <1gm2vee.o0lwqk1h3npjsN%aleaxit@yahoo.com> <1gm4rq5.1c25kfc12o6jivN%aleaxit@yahoo.com> <417cb790$0$226$edfadb0f@dread12.news.tele.dk> Message-ID: <1gm8d6x.hvrljyulw27dN%aleaxit@yahoo.com> Valentino Volonghi aka Dialtone wrote: > Max M wrote: > > Zope Page Templates has a far better approach to this imho. Where you > > define reusable markup in a macro. > > > > The box could then be defined with title and content slots like:: > > > >
> >
The title
> > This is example > > content > >
Hmmm, isn't this HTML malformed? the second metal:block seems to be self-terminated and then terminated again by a . I'm going to assume a typo (apologies if it's a ZPT feature instead). > > This approach makes it relatively easy to reuse markup as well as logic. > > It is possible use arbitrarily complex markups as "parameters" to the > > slots in the template. Wich makes it very nice for larger systems. > > Which with Nevow is perfectly natural since you can do: > >
> >
> > and then in the code: > > def render_content(self, ctx, data): > ctx.tag.fillSlots('content', My_Fragment()) > return ctx.tag OK, but the problem is, who supplies My_Fragment, and how is said fragment going to be parameterized. > Just like I've done in weever (on berlios) where there is a main file that > defines the base class for all the pages and requires a content fragment as > argument with which it will fill the empty slot to render the whole page. > > Then I subclass the main page class to give the behaviour I need, and then I > pass the content 'page' to have it rendered in the output. Still, this doesn't let the author of the markup (only), who by definition is not going to touch the code, define his/her own macros. Nevertheless, I think you _could_, in nevow, define the renderers needed to let the markup-only person code, once:
which stashes away the contents and renders nothing, and then, as many time as desired, stuff such as: The title of this box The title of this box, an arbitrary piece of text and/or various markup. which expands the previously-stashed-away contents, with slot-filling. Still, render_define_macro and render_expand_macro do not come predefined with nevow (at least so far). It probably wouldn't be too difficult to code them, of course, but _designing_ them just right is both harder and more important -- I'm anything but sure that the architecture implied in this example-use sketch is best (the ZPT example leaves me far from sure it's really all that well designed, either;-). This, I believe, is part of nevow not being fully mature yet; at release 0.3, of course, full maturity should not yet be expected, either. ZPT is older and wiser. Nevertheless, the fundamental architecture of nevow appears to be sound and very promising (for the templating part, at least; I'll reserve my opinion about the other parts!), and if the worst that could be said of it is that it may still lack some convenience predefined general-purpose renderers such as define_macro and expand_macro, well, that sure won't be very hard to remedy (getting such convenience add-ons designed right is the interesting challenge; the coding, with nevow's power at hand, is the easy part). Alex From anhtt at hotmail.com Sun Oct 10 04:41:06 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 10 Oct 2004 01:41:06 -0700 Subject: Sorting and list comprehension Message-ID: Hi all, I would like to do the followings, but I am quite new to Python hence have not figured it out how... salary = dictionary salary["Bob"] = 11 salary["Marry"] = 4 salary["me"]= 45 How can I have a sort_value() function acts like this: result = sortvalue(salary) result = ["Marry","Bob","me"] In sort, I would like to sort the key according to the values. Regarding the list construction, how can I do this: list = [item for item in list1 if for all item2 in list2 NOT bad_condition(item, item2] Anyone has any idea? Thanks a lot! Tuan-Anh From grante at visi.com Tue Oct 5 15:17:52 2004 From: grante at visi.com (Grant Edwards) Date: 05 Oct 2004 19:17:52 GMT Subject: New to Python: Features References: <20041005101730.ECD4.JCARLSON@uci.edu> <4162E3CC.3080200@cloudthunder.com> <20041005111159.ECE0.JCARLSON@uci.edu> Message-ID: <4162f360$0$55262$a1866201@newsreader.visi.com> On 2004-10-05, Richard Blackwood wrote: >>Take for example if I were to claim that I were a graduate student in >>computer science theory at the University of California, Irvine. A >>little bit of investigation would lead you to discover that I am >>likely the person I claim to be (header examination, university search, >>etc.). >> > I could care less honestly. I've always been curious about that phrase. It seems to imply that you _do_ care, since it would be possible for you to care less than you do. Shouldn't the expression be "I couldn't care less"? > I'll come back to usenet when I have more explicit and > specific questions relating to Python. You can ask general and broad-reaching questions if you want to, but you're expected to do a modicum of research on your own to try to find the answers. -- Grant Edwards grante Yow! LOOK!!! I'm WALKING at in my SLEEP again!! visi.com From theller at python.net Thu Oct 7 14:40:13 2004 From: theller at python.net (Thomas Heller) Date: Thu, 07 Oct 2004 20:40:13 +0200 Subject: Ctypes error References: Message-ID: <1xga4bjm.fsf@python.net> Michele Petrazzo writes: > I'm using ctypes v 0.9.1 on linux for the first time. > > Then I try to use create_unicode_buffer(), I receive this error: > > File "/usr/lib/python2.3/site-packages/ctypes/__init__.py", line 74, > in create_unicode_buffer > buftype = c_wchar * init > NameError: global name 'c_wchar' is not defined > > In __init__ file I see that at line: > 208 if _os.name == "nt": > 214 class c_wchar(_SimpleCData): > > This class if only for "nt" ? > > Thanks, > Michele Petrazzo Ok, it seems I missed to put the create_unicode_buffer inside an if: if os.name == "nt": The deeper issue is that the unicode stuff in ctypes is only compiled in when the Python header files define the HAVE_USABLE_WCHAR_T symbol. Of the systems I build and test on, only Windows defines this. I'm not really sure that this is really the right thing to do, maybe this should be sufficient: #if Py_UNICODE_SIZE == 2 Thomas From michael at stroeder.com Mon Oct 18 03:38:10 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 18 Oct 2004 09:38:10 +0200 Subject: Python Library Reference is tutorial, not reference In-Reply-To: References: Message-ID: <3g8c42-692.ln1@nb2.stroeder.com> Josiah Carlson wrote: > > Having used (read and written) pydoc/javadoc-style documentation before, > I am personally not a big fan of them. I much prefer the conversational > and sometimes tutorial style of standard Python documentation, to an > arbitrary API reference. Me too. Ciao, Michael. From guettli at thomas-guettler.de Mon Oct 11 07:29:30 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 11 Oct 2004 13:29:30 +0200 Subject: Linenumbers: inspect.getinnerframes vs. traceback.format_exception Message-ID: Hi, the line numbers of inspect.getinnerframes are different from traceback.format_exception. This results in wrong lines being shown in cgitb. An example is below. I looked at the source of both methods. One uses f_lineno (wrong) the other tb_lineno (correct). I use python 2.3.3 Is this fixed in a newer version? See: ===> python tb.py Correct traceback (traceback.format_exception) Traceback (most recent call last): File "tb.py", line 34, in ? main() File "tb.py", line 18, in main printtb() File "tb.py", line 13, in printtb assert(0) AssertionError Wrong traceback (inspect.getinnerframe) File "tb.py", line 34, ... if __name__=="__main__": File "tb.py", line 18, ... printtb() File "tb.py", line 15, ... pass tb.py: #!/usr/bin/env python # -*- coding: iso-8859-1 -*- # Python Imports import os import sys import inspect import traceback def printtb(): try: assert(0) except ValueError: pass def main(): printtb() class Hook: def __call__(self, etype, evalue, etb): print "Correct traceback (traceback.format_exception)" print ''.join(traceback.format_exception(etype, evalue, etb)) print print "Wrong traceback (inspect.getinnerframe)" context=5 records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: print ' File "%s", line %s, ...\n%s' % ( file, lnum, lines[context/2].rstrip()) if __name__=="__main__": sys.excepthook=Hook() main() From nick at craig-wood.com Thu Oct 7 12:29:57 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 07 Oct 2004 16:29:57 GMT Subject: Tracking Users By IP Address References: <71fam01oatd8g87d6dpacbn2mcku9pe4j1@4ax.com> Message-ID: Paul McNett

wrote: > > Some (many? all? negligibly few? I don't know) proxy > > firewalls will tell you which internal address the request > > came from, so you can combine the two to get a unique address > > for that user. > > I'd say "negligibly few", since there really isn't good reason > to give the world your internal ip address. Anyway, you can't > count on it, and you wouldn't have a basis to know what > percentage weren't unique. An awful lot of proxies do do exactly that (I used this technique before). HTTP_X_FORWARDED_FOR and REMOTE_ADDR are the headers you want Its not safe to use this as a unique address for a user but if you are interested in exactly where your users are (for fraud checking purposes) its a useful technique. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From vinay_sajip at yahoo.co.uk Fri Oct 29 07:00:14 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 29 Oct 2004 04:00:14 -0700 Subject: logging question References: Message-ID: <2e37dc1.0410290300.13191094@posting.google.com> > Whether there is a way to automatically replicate a logger hierarchy I don't > know. Peter is right about the formatting. I'm not sure what's meant by 'replicate a logger hierarchy' - if you mean complete with handlers, formatters, etc. then the only ways of doing this are by using the same API calls on both sides, or loading the configuration of both sides from a shared configuration file. If you are sending logging events across a network, then the normal configuration is to just have a socket or datagram handler on the source side of the connection, and on the sink side the messages are handled as per Peter's code - formatted, written to file, emailed or whatever. However, you can use any logger name you like on the receiving side - the one that came in on the LogRecord, or something prepended/appended to the logger name in the LogRecord. Regards, Vinay Sajip From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Oct 15 13:21:27 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 15 Oct 2004 18:21:27 +0100 Subject: operation with strings and numbers In-Reply-To: References: Message-ID: Hellas wrote: > Could you help me please? > thanks a lot I suggest you read this: http://www.catb.org/~esr/faqs/smart-questions.html And then read this: http://www.python.org/doc/2.3.4/lib/typesseq-strings.html If you still can't figure it out, use the hints in the first document and ask again. -- Michael Hoffman From noone at here.com Tue Oct 5 13:49:35 2004 From: noone at here.com (M. Clift) Date: Tue, 5 Oct 2004 18:49:35 +0100 Subject: Alex if you have any patience left please look at this References: <1gl5l5t.k9lpmq1rn8gt5N%aleaxit@yahoo.com> <1gl776a.6zkpal1d31a01N%aleaxit@yahoo.com> Message-ID: Hi Alex, A quick reply, thankyou. I'd been experimenting with it to see how it worked and didn't put it back together right... It now works perfectly. All the best, Malcolm From peter at engcorp.com Fri Oct 29 09:31:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Oct 2004 09:31:03 -0400 Subject: ctypes 0.9.2 released In-Reply-To: References: <1gmeuqj.1p0mkh41y1zvfcN%aleaxit@yahoo.com> Message-ID: Just wrote: > In article <1gmeuqj.1p0mkh41y1zvfcN%aleaxit at yahoo.com>, > aleaxit at yahoo.com (Alex Martelli) wrote: >>Seconded! Python 2.5 should be mostly about standard-library >>enhancements, and ctypes would be a huge enhancement to Python's stdlib. > > In general, Guido is very reluctant to accept thing which make is easy > to cause segfaults. I predict you'll have a very hard time convincing > him... That's too bad, because it's really not that easy to cause segfaults with it. I'm speaking practically, as someone who has used ctypes in a dozen different utilities and applications, and who hasn't always read the docs, and who has experimented sometimes in ways that in a language like C would cause segfaults, but with ctypes: no segfaults to date. I'm obviously not saying it's not possible to cause segfaults with ctypes. Almost anyone could probably come up with a way in a few minutes or less. I _am_ saying that casual use over the period of several years has not led to any segfaults for _me_, and the benefits have been huge. Nobody is forcing someone to use ctypes, and I suppose if one chooses to use it, one probably has some idea of the dangers of what one is doing. Of course, nobody is forcing anyone to include ctypes in the standard distribution either, but it seems that the choice should be made based more on what ctype's *users* think about it than what someone who perhaps has rarely or never actually used it thinks. Or is Guido a regular ctypes user (and presumably one who has often triggered unexpected segfaults, at that)? -Peter From luismg at gmx.net Mon Oct 11 00:52:28 2004 From: luismg at gmx.net (Neuruss) Date: 10 Oct 2004 21:52:28 -0700 Subject: [ANN] Boo 0.4.3 - python-like language for .NET/Mono References: <8PGdnS7wN_uwg_rcRVn-qw@comcast.com> Message-ID: <278de0e.0410102052.693297d7@posting.google.com> > "Python-like" means very little. Make it run python code > then you'll see a lot more interest from this group. I find it very interesting. From ville at spammers.com Sat Oct 9 10:30:51 2004 From: ville at spammers.com (Ville Vainio) Date: 09 Oct 2004 17:30:51 +0300 Subject: proposals for having more fun with map References: Message-ID: >>>>> "Tom" == Tom Anderson writes: Tom> wanting to do all the time, so i either end up throwing lambdas all over Tom> the place to glue the dicts into map, or writing a little helper function Tom> like so: Tom> def functor(dict): Tom> return lambda arg: dict[arg] See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305318 #itemgetter: also of course works with dictionaries data= ( {'name':'fred','score':50},{'name':'betty','score':75}) print map(operator.itemgetter('name'),data) >>> ['fred', 'betty'] Tom> this isn't hard, of course, but it's the sort of thing that Tom> ought to be done once and only once. Indeed ;-). Tom> again, trivial, but if i'm writing this out in almost every Tom> program i write, other people must be too, so it's worth Tom> putting in the core. Actually, the more likely future of map is moving *out* of the core, to a "functional" module of some sort. List comprehensions (and soon genexps) are the recommended approach. -- Ville Vainio http://tinyurl.com/2prnb From bac at OCF.Berkeley.EDU Sat Oct 16 22:27:07 2004 From: bac at OCF.Berkeley.EDU (Brett C) Date: Sat, 16 Oct 2004 19:27:07 -0700 Subject: python-dev Summary for 2004-09-16 through 2004-09-30 Message-ID: <4171D87B.2000306@ocf.berkeley.edu> python-dev Summary for 2004-09-16 through 2004-09-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from September 16, 2004 through September 30, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the forty-ninth summary written by Brett Cannon (Wow, my thesis gives an entire .5% speed-up on pystone at the moment; ain't that grand...). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-09-01_2004-09-15.html .. _original text file: http://www.python.org/dev/summary/2004-09-16_2004-09-30.ht ===================== Summary Announcements ===================== Wow. This must have been the easiest summary I have ever done. Why can't they all be like this? I didn't even skip that much! This summary also marks the first instance of having a contributing writer (ignoring the time when Raymond Hettinger was guest writer and wrote the whole summary himself). So thanks to Michael Chermside for writing up those summaries. And this is open to anyone, so if you feel that one of the skipped threads is worth summarizing and you catch it on the draft I send out of the Summary please mail them to me and it will probably get included. ========= Summaries ========= ------------------------------------------ Assume nothing when mutability is possible ------------------------------------------ Tim Peters discovered a new way to create an infinite list thanks to generator expressions. But what really came out of this whole discussion came about when someone else came up with an example that exposed a bug in list.extend(). The first thing was that "you can't assume anything about a mutable object after potentially calling back into Python." Basically you can't assume the state of any mutable object was not changed if you execute Python code from C. While it might seem handy to store state while in a loop for instance, you can't count on things not changing by the time you get control back so you just have to do it the hard way and get state all over again. Second was that you need to be careful when dealing with iterators. If you mutate an iterator while iterating you don't have a guarantee it won't explode in your face. Unless you explicitly support it, document it, and take care to protect against it then just don't assume you can mutate an iterator while using it. Contributing threads: - `A cute new way to get an infinite loop `__ - `More data points `__ ----------------------------- The fewer licenses the better ----------------------------- The idea of copying some code from OpenSSH_ for better pty handling was proposed. This was frowned upon since that becomes one more legal issue to keep track of. Minimizing the licenses that Python must keep track of and make sure to comply with, no matter how friendly, is a good thing. .. _OpenSSH: http://www.openssh.org/ Contributing threads: - `using openssh's pty code `__ ----------------------------------------------------------------------- Trying to deal with the exception hierarchy in a backwards-friendly way ----------------------------------------------------------------------- Nick Coghlan came up with the idea of having a tuple that contained all of the exceptions you normally would not want to catch in a blanket 'except' statement; KeyboardInterrupt, MemoryError, SystemExit, etc.). This tuple was proposed to live in sys.special_exceptions with the intended usage of:: try: pass # stuff... except sys.special_exceptions: raise # exceptions that you would not want to catch should keep propogating up the call chain except: pass # if you reach here the exception should not be a *huge* deal Obviously the best solution is to just clean up the exception hierarchy, but that breaks backwards-compatibility. But this idea seemed to lose steam. Contributing threads: - `Proposing a sys.special_exceptions tuple `__ -------------- Built on beer! -------------- by Michael Chermside In this short thread Guido admits that Python *is* really built on beer: "...it's true! During the early days, when hacking on Python, I often lived on stroopwafels and beer." Contributing threads: - `built on beer? `__ ----------------------------------- Docs still available in gzip format ----------------------------------- by Michael Chermside Fred Drake suggested that we stop providing the Python documentation in gzip format. We offered the zip and bzip2 formats which have unique advantages (bzip2 compresses better and zip has a directory built in so individual files can be extracted) over gzip and he wanted to reduce the number of different formats offered. However, there was much dissention, so the final decision was to retain the format. Contributing threads: - `Planning to drop gzip compression for future releases. `__ --------------------------------------------------------- Making running stdlib modules as scripts that much easier --------------------------------------------------------- Nick Coghlan contributed a patch for a new command-line option, ``-m``, that will search sys.path for a module of that name and execute it as a ``__main__``. This can be really handy for things such as checking the docstrings of a module (``python -m pydoc heapq``) and such. Currently, though, it only for top-level modules in sys.path and thus ignores packages. If you want that functionality there is a recipe by Nick on the Python Cookbook at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307772 . There is also discussions going on python-dev about how to possibly add this in the future. Contributing threads: - `Running a module as a script `__ =============== Skipped Threads =============== - Decimal, copyright and license - Noam's open regex requests - Socket/Asyncore bug needs attention - open('/dev/null').read() -> MemoryError - Finding the module from PyTypeObject? - Odd compile errors for bad genexps From rkern at ucsd.edu Fri Oct 29 23:32:21 2004 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 29 Oct 2004 20:32:21 -0700 Subject: Open Source License Question In-Reply-To: References: Message-ID: Donnal Walter wrote: [snip] > 1. Is there a compelling reason for PA *not* to use a CL license (say > Gnu GPL) for OApps and BigApp? These are "end-user" applications, not > system components. Not terribly compelling to my mind, but: Some people avoid copylefted works out of (pick one or more: habit, ignorance, irrational fear, rational avoidance of licensing complexity/uncertainty, any number of things I can't think of off the top of my head). CApp authors will almost assuredly use OApps as examples for using the framework. A license like the GPL for BigApp could limit which CApps you can include because of incompatibilities. > 2. Am I right in thinking that the license for FW will have little or no > legal bearing on the licenses contributors choose for CApps? If the license you use for the framework is strong copylefted (e.g. GPL) as opposed to weak copylefted (e.g. LGPL), then the license *will* have a strong bearing on the license used for contributed apps. > 3. Am I right in thinking that a CL license for BigApp would encourage > (but not require?) using CL for CApps (if they want them included)? *shrug* I think that strongly depends on the community that you build around your software. If I'm not involved in the community, I'm more likely to choose a license for my apps which is in my best interests/desires and meets the requirements of the licenses of the libraries I am using. Only if there is a strong community that pushes for a particular license am I likely to deviate from that preference. BigApp's license alone wouldn't do that for me. > 4. Will either a CL or NCL license for FW affect the likelihood of > receiving improvements from programmers outside the field of interest? Probably, but I would doubt that anyone can tell you how either choice will affect contributions. Many people will come up with arguments for either position ("GPL will drive programmers away!" "GPL will gives programmers assurance that everyone will give back to the community!"). Ignore them. They know less than you. > 5. If PA chooses a CL license for FW, can it later be changed to NCL in > order to be combined with FW2? If you not only are the principal author but also the sole copyright owner, then yes. If you fold in changes from other people without having them assign copyright to you or have them license those changes under a permissive license (BSD, MIT, PSF, and the like), then you must obtain permission to relicense from each of them. This can be a problem sometimes. > 6. If PA choses a NCL license for FW, can it later be changed to CL in > order to be combined with FW3? Similar answer as above. If the non-copyleft license is permissive like BSD, etc. then your headaches are greatly reduced. IANAL. TINLA. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rkern at ucsd.edu Thu Oct 28 16:22:30 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Oct 2004 13:22:30 -0700 Subject: Open Source License Question In-Reply-To: References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <97-dnSRAYPEwPuLcRVn-rA@rogers.com> Message-ID: Donnal Walter wrote: > Thanks for this reference and the one to Creative Commons. Is there a > good mailing list or on-line forum appropriate for discussing licensing > issues? I wouldn't mind discussing my questions here as I have the > highest regard for the participants in c.l.p, but my questions are > mostly off topic for this list. I'm still struggling with the copyleft > vs non-copyleft issue, for example, and there may be a more appropriate > place to discuss this. http://www.opensource.org/licenses/#email I do recommend reading some of the archives first. Some of your questions have been tread over many times on that list. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jcarlson at uci.edu Mon Oct 18 16:46:28 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 18 Oct 2004 13:46:28 -0700 Subject: By value or by reference? In-Reply-To: <1glvhih.mackqd12vhs62N%aleaxit@yahoo.com> References: <1glvhih.mackqd12vhs62N%aleaxit@yahoo.com> Message-ID: <20041018133211.0A4B.JCARLSON@uci.edu> > The key point is that, in both languages, a function's arguments are > just like local variables pre-initialized by the caller with assignment > statements. In both languages, if the function reassigns an argument > it's just playing with its own local variables, the caller is never in > any way affected by that. In both languages, there are other ways > except plain barename assignments to possibly "affect the caller" (in C > you basically need to have been passed a pointer, and dereference that > pointer or another pointer computed from the first by pointer > arithmetic; in Python you basically need to have been passed a mutable > object, and call mutating methods on that object). Again, in both cases > I see simplicity and consistency, everything pretty explicit... I agree with most everything you have said, though consider the pointer vs. value of C to define the semantics of the passing. That is, if you get a pointer in C, it is by reference. If you don't get a pointer, it is by value. I also agree that everything is pure and explicit in both languages, it took me a few minutes mucking around with the interpreter my first time to understand how Python deals with the base types. I'm trying to point out that if you toss the standard C semantic definition of "pass by value" and "pass by reference", by merely pretending that the definitions have not been given in the history of computer science, and just look at how Python does actual name binding in namespaces/scopes, you can understand what Python does much better than to get into a "Python does pass by reference" vs. "Python does pass by value" argument. - Josiah From jcarlson at uci.edu Tue Oct 12 23:52:31 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 12 Oct 2004 20:52:31 -0700 Subject: Secure Python code - volunteers for code review? In-Reply-To: <1097637663.543580.126100@z14g2000cwz.googlegroups.com> References: <1097637663.543580.126100@z14g2000cwz.googlegroups.com> Message-ID: <20041012205021.091B.JCARLSON@uci.edu> > I would really value it if any security aware Python guru was able to > review the code from a security perspective. It would be good to > ensure that python or sql code planted in an email or an attachment > could not execute and break out of the script - or that any other > security issue might arise. But how - I don't have anything near the > level of Python expertise required to properly assess this script for > security risk? If someone has the time to do a code review it would be > much appreciated. You can save yourself many concerns by encoding your data in some fashion that cannot be understood by the database to mean anything. Hex works well for that. In terms of general script security, you should be more specific about what you are worried about. - Josiah From jeff at ccvcorp.com Tue Oct 5 16:53:27 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 05 Oct 2004 13:53:27 -0700 Subject: New to Python: Features In-Reply-To: References: Message-ID: <10m62atl8vmk576@corp.supernews.com> Dan Bishop wrote: >Richard Blackwood wrote in message news:... > > >>44. Case or Switch statements with functionality as such: >>case score >>when 0...40 >> puts "Horrible!" >>when 40...60 >> puts "Poor" >>when 60...80 >> puts "You can do better!" >>when 80...95 >> puts "Now that's acceptable" >>when 95..100 >> puts "That the best you can do? j/k" >>else >> puts "Didn't take the test?" >>end >> >> > >Python does not have a switch/case construct. Your example would >normally be written as an if...elif...else ladder. > > Or, in situations where the case conditions can be narrowed to a single value (possibly with the aid of a custom classification function), one could use a dictionary dispatch. def func1(): print "Func1" def func2(): print "Func2" def func3(): print "Func3" dispatcher = { 0: func1, 1: func2, 2: func3 } i = int(score / 10) myfunc = dispatcher[i] myfunc() This idiom requires a bit more in the way of setup (you're choosing an object, not a statement, so statements must be wrapped in functions/classes; the selection criteria must be a hashable value), but the result is (imho) a much cleaner structure. Jeff Shannon Technician/Programmer Credit International From gandalf at geochemsource.com Tue Oct 12 04:32:35 2004 From: gandalf at geochemsource.com (Gandalf) Date: Tue, 12 Oct 2004 10:32:35 +0200 Subject: httplib ResponseNotReady Message-ID: <416B96A3.2010400@geochemsource.com> Hi All, There was a discussion about a bug in httplib. After 100 (continue), when you want to GET a page, you will get a ResponseNotReady exception instead. I'm having the same problem here. I'm using Python 2.3.2. Does anyone know if this problem has been solved? Are there patches? Kind regards, Laci 2.0 From michele.simionato at gmail.com Thu Oct 14 15:18:34 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Oct 2004 12:18:34 -0700 Subject: ANN: curses-extra 0.2 References: Message-ID: <4edc17eb.0410141118.6d3ac74d@posting.google.com> Riccardo Galli wrote in message news:... > First official release :) > > curses-extra offers various widgets wrotten using curses module. > I always wanted something like that! I wish I had the time to try it out ... Question: would it be very difficult to run it on Windows using the F-bot console module as a curses replacement? Michele Simionato From koko9991 at compuserve.de Fri Oct 29 04:59:46 2004 From: koko9991 at compuserve.de (Konrad Koller) Date: Fri, 29 Oct 2004 08:59:46 GMT Subject: Ubuntu Linux loves Python: What is pysqlite? References: Message-ID: <4182047c.929435750@news.compuserve.de> >Installation is short and sweet, the Gnome desktop is functional and >nice to look at and the debian package system is awsome. BUT I've >allready found some outdated packages, like pysqlite, which doesn't >work with code I've made on Windows using pysqlite 1.0. >Download and install it now!!! ( And make an updated ubuntu-package of >pysqlite while you're at it ;-) ) Sorry, but I do not know what pysqlite is. From zathras at thwackety.com Sat Oct 16 10:42:22 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 16 Oct 2004 15:42:22 +0100 (BST) Subject: Eric3 + Qt licensing [was Re: The IDE question] In-Reply-To: Message-ID: On 16 Oct 2004, Ville Vainio wrote: > >>>>> "Michael" == Michael Sparks writes: > > Michael> Being more specific though... It also frustrates me that > Michael> I can write something I find useful and then cannot > Michael> afford to pass it onto friends who use windows, even if > Michael> there's no commercial value in it. > > What we are seeing here is a horrible waste of coding - 95% of the > desktop world runs on Windows, and if a piece of software is unusable > for 95% of the potential userbase... that just sucks. What if the developer only intended to write the tool for himself, and happens to make it available to that extra 5% though? That's a net gain from 1 person surely? That's the way I personally tend to look at it. :-) Michael. From skywalkerpackage at hotmail.com Thu Oct 7 04:14:34 2004 From: skywalkerpackage at hotmail.com (Johannes Eble) Date: Thu, 07 Oct 2004 10:14:34 +0200 Subject: Python-Matlab extensions: Comparisons? References: Message-ID: Hi Robert, thanks very much for your advice. I will start with SciPy and IPython. Best regards Johannes From grante at visi.com Thu Oct 7 10:09:55 2004 From: grante at visi.com (Grant Edwards) Date: 07 Oct 2004 14:09:55 GMT Subject: Problem with telnetlib dropping receive bytes. References: <41649ff5$0$59533$a1866201@newsreader.visi.com> Message-ID: <41654e33$0$59540$a1866201@newsreader.visi.com> On 2004-10-07, Eddie Corns wrote: > Grant Edwards writes: > >>Why are NUL and DC1 characters being deleted from the recieve >>data stream at lines 431 and 433? They're both perfectly legal >>characters. I can't find anywhere in RFC 854 where it says to >>do that, and it's breaking my program. Some of the other >>telnet features (e.g. RFC 2217) specifically use those two byte >>values. > > Looks like a bug to me. Telnet requires that ALL 7 bit > characters can be used. Since it's all handled in Python I > can't think of any reason why those characters would be a > problem. That's what I thought, but since somebody went out of their way to drop those two characters, I thought I'd better check. I'll submit a patch once I've spent some more time with telnetlib. -- Grant Edwards grante Yow! Are you still an at ALCOHOLIC? visi.com From none at pacbell.net Mon Oct 11 12:19:41 2004 From: none at pacbell.net (Richard) Date: Mon, 11 Oct 2004 16:19:41 GMT Subject: DISLIN or gnuplot.py References: Message-ID: On Mon, 11 Oct 2004 08:12:16 -0500, John Hunter wrote: >>>>>> "Richard" == Richard writes: > > Richard> I am going to need to plot some data and formula results > Richard> from Python. > > I suggest looking at matplotlib. Although it is not as mature as > DISLIN and gnuplot, it is progressing rapidly and supports most 2D > plotting needs, with the remaining gaps closing quickly (see > http://matplotlib.sourceforge.net/screenshots.html for a quick > snapshot of capabilities). > > > http://matplotlib.sourceforge.net > > > JDH Thank you for the reply. It looks like matplotlib will handle my immediate plotting from Python needs. The 'goals' page on the matplotlib web site state that there has been some 'proof-of-concept' work completed on 3-d visualization. Any estimate on when there might be some 3-d plotting support? Richard From aahz at pythoncraft.com Fri Oct 22 19:05:21 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 Oct 2004 19:05:21 -0400 Subject: Include pysqlite2 into Python 2.5? References: Message-ID: In article , John Fabiani wrote: > >My only question is what happens when SQLLite becomes out of favor >i.e. TK is today? Tkinter isn't precisely out of favor, even now. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From jcarlson at uci.edu Thu Oct 21 13:55:35 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 21 Oct 2004 10:55:35 -0700 Subject: Actual memory used by an object --- How to Determine? In-Reply-To: References: Message-ID: <20041021100616.0AB2.JCARLSON@uci.edu> zooko at zooko.com wrote: > Here some some functions I've used to analyze memory usage in the past. > > http://mnetproject.org/repos/pyutil/pyutil/memutil.py The site is down. > There may be bugs. If so, please fix them or at least report them. I'd look if I could get it. - Josiah From aleaxit at yahoo.com Fri Oct 22 10:23:10 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 22 Oct 2004 16:23:10 +0200 Subject: Method Underscores? (and a 'solution') References: <9dIdd.3712$EL5.3057@trndny09> <1gm17go.1r662ynelfha7N%aleaxit@yahoo.com> <1gm1um6.zgqbbe8x559fN%aleaxit@yahoo.com> <4178F24C.5010004@holdenweb.com> Message-ID: <1gm2fs0.1wc9vf61okndnvN%aleaxit@yahoo.com> Steve Holden wrote: ... > > tell application "Microsoft Word" > > open "MyWordFile" > > set selection to paragraph 1 > > data size of selection as string > > end tell ... > > were cross-platform, it might perhaps make an even better beginners' > > language than Python (and I think that of few languages). It doesn't > > scale up as well as Python, though, it appears to me. > > > Yeah, it does have that Logo-like quality about it, doesn't it? For > beginners, of course, it's typically more interesting to be able to > write scripts to get their computers to do things they'd otherwise have > to do themselves, so AppleScript-for-Windows might be a good Python project! Yes, but mapping the simple "apple events" on which applescript is based (and which are widespread in applications as well as the OS on the Mac, e.g. MS Office apps implement them) to COM's richer and more complex ways (and COM/Automation enjoys a similar prominence on Windows and its applications) sounds like quite a task, requiring deep understanding of both platforms. Maybe I'm being pessimistic... Alex From nid_oizo at yahoo.com_remove_the_ Wed Oct 13 15:59:14 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 13 Oct 2004 15:59:14 -0400 Subject: Order in metaclass In-Reply-To: <4qky5s8r.fsf@python.net> References: <416cf48f.140377111@news.oz.net> <4qky5s8r.fsf@python.net> Message-ID: Thomas Heller wrote: > In this case, you could also look at the ctypes module, it implements C > compatible structures and unions. > > And for your original question: why do you insist on your new syntax, > why don't you simply (as ctypes also does it) define the attributes in a > list, when they have to have a certain order? I just looked at ctypes, and yes, that's exactly what I'm doing. I want the structures definitions to be modified by C++ programmers and I find the metaclass mechanism much more readable and easy to modify (and it's not a lot of code to make everything work). I agree everything can be done using normal Python code, but my goal here is really to make a pseudo-language to define our formats, and the pseudo-language is just a simpler solution than XML in my specific case. Probably all cases of such using of metaclasses are like that... Regards, Nicolas From kdahlhaus at yahoo.com Thu Oct 28 10:55:16 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 28 Oct 2004 07:55:16 -0700 Subject: Reading XML like Python! References: Message-ID: <283adf56.0410280655.1f40f09e@posting.google.com> Dave Cook wrote in message > Check out xmlobject: I was looking for something exactly like this last week. Amazing how much code it cuts out. Thanks for posting the link. From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Oct 16 08:18:46 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sat, 16 Oct 2004 13:18:46 +0100 Subject: Efficient String Lookup? In-Reply-To: References: Message-ID: Chris S. wrote: > I have a number of strings, containing wildcards (e.g. 'abc#e#' where # > is anything), which I want to match with a test string (e.g 'abcdef'). > What would be the best way for me to store my strings so lookup is as > fast as possible? If it were me, I would store them as compiled regular expressions. See the re module documentation and use re.compile(). If you want a better solution, it might help if you supply a little more information about your problem and why this solution is unsuitable (maybe it is :]). -- Michael Hoffman From aleaxit at yahoo.com Thu Oct 7 13:56:10 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 7 Oct 2004 19:56:10 +0200 Subject: Parallelization on muli-CPU hardware? References: <6db3f637.0410042045.2171ad5f@posting.google.com> <6db3f637.0410052100.31bbe86f@posting.google.com> <1glatga.8upk9brifr2qN%aleaxit@yahoo.com> Message-ID: <1glawed.1e83ntp1ck15pvN%aleaxit@yahoo.com> Aahz wrote: > In article <1glatga.8upk9brifr2qN%aleaxit at yahoo.com>, > Alex Martelli wrote: > >Aahz wrote: > >> > >> The problem is that CPython doesn't have thread-local storage. > > > >In 2.4 it does -- see threading.local documentation at > > (and > >even better, the docstring of the new _threading_local module). > > IIUC, that's not thread-local storage in the sense that I'm using the > term (and which I believe is standard usage). Values created with > thread-local storage module are still allocated on the heap, and it's > still possible to use introspection to access thread-local data in > another thread. Is it...? Maybe I'm missing something...: import threading made_in_main = threading.local() made_in_main.foo = 23 def f(): print 'foo in made_in_main is', getattr(made_in_main, 'foo', None) print 'in main thread:', f() t = threading.Thread(target=f) print 'in subthread:', t.start() t.join() print 'back in main thread:', f() What I see is: kallisti:~/cb/little_neat_things alex$ python2.4 lots.py in main thread: foo in made_in_main is 23 in subthread: foo in made_in_main is None back in main thread: foo in made_in_main is 23 so how does a subthread introspect to 'break the rules'...? (preferably in a platform-independent way rather than by taking advantage of quirks of implementation or one or another platform) > Don't get me wrong; I think it's a brilliant addition to Python. > Unfortunately, it doesn't help with the real issues with making the > Python core free-threaded (or anything more fine-grained than the GIL). I'm not claiming it does, mind you! It's just that it DOES seem to me to be a "true" implementation of the "thread-specific storage" design pattern, and I don't know of any distinction between that DP and the synonym "thread-local storage" (Schmidt et al used both interchangeably, if I'm not mistaken). Alex From d-hanst at online.no Fri Oct 22 15:56:16 2004 From: d-hanst at online.no (Dag Hansteen) Date: Fri, 22 Oct 2004 21:56:16 +0200 Subject: Connecting to IRC using socket module Message-ID: <002801c4b871$3119dbd0$4e01a8c0@dagan> Hello! Somehow I dont make this work, can anyone please correct me? There is no error, but it just kinda halts after I get "NOTICE AUTH: *** Found your hostname", I assume theres something with the PONG reply, but I can't figure it out. # CODE: from socket import * host = "oslo.no.eu.undernet.org" port = 6667 buf = 1024 addr = (host, port) first = 'NICK dagan' second = 'USER dag "" "oslo.no.eu.undernet.org" :python bot' sock = socket(AF_INET, SOCK_STREAM) sock.connect(addr) sock.sendto(first, addr) print "-> "+first sock.sendto(second, addr) print "-> "+second while 1: data, addr = sock.recvfrom(buf) f = open("debug.txt", "w") f.write(data+"\n") if data.startswith("PING :"): sock.send("PONG :"+data[6:]) break else: print "<- "+data print addr print "I hope I soon will see this message.. yes, this message! woohoo" sock.send("join #scripting") while 1: data, addr = sock.recvfrom(buf) print "<- "+data -------------- next part -------------- An HTML attachment was scrubbed... URL: From nhodgson at bigpond.net.au Thu Oct 28 08:49:32 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 28 Oct 2004 12:49:32 GMT Subject: Open Source License Question References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <2u9hklF24n4b1U1@uni-berlin.de> <_-adnfiRi4tmPOLcRVn-1A@powergate.ca> Message-ID: Peter Hansen: > I haven't been trying to keep up to date on this issue, but these > guys seem to feel there is something along those lines that can be done: > http://creativecommons.org/ (Specifically, > http://creativecommons.org/licenses/publicdomain/ ) > > By how far does that miss your mark? It appears to be the same as just declaring that your work is in the public domain. Since you still own and can not relinquish copyright, there is nothing to stop you changing your mind and requiring payment from those who believed your declaration. Neil From strombrg at dcs.nac.uci.edu Thu Oct 28 21:27:47 2004 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Thu, 28 Oct 2004 18:27:47 -0700 Subject: comparing multiple copies of terrabytes of data? References: Message-ID: Folks, I'm a little overwhelmed by how helpful this thread has been to me - thanks a bunch. I'd like to point out that I have some code written up that I hope to use correctly the first time, in verifying that our three copies of a 3+ terrabyte collection of data... well, that the first copy is a (not-necessarily-proper) subset of the other two copies. Once we sign off, saying "the data copies look correct", then IBM's going to say "OK, for better or worse, it's your storage system now, problems and all." This storage system is the first of its kind in the known universe (as far as the filesystem software combined with very high storage density linux boxes), and I'm guessing that there's around $500K sunk into it, just on hardware. -But-, it's far cheaper than almost any other solution of its size. I'll add that both the system we are transitioning from is opensource from Redhat, and is apparently pureplay GPL, and the system we are transitioning to is from ClusterFS, which has a dual-license GPL/Closed source thing going on (where the Closed source stuff is transitioned to GPL eventually, kind of like Alladin ghostscript). Rather than letting the specifics of the situation creep into the code too much, I've tried to make it into a fairly general, reusable tool that others might be able to benefit from as well. You basically give the program a sampling frequency (number of files to skip before checking one), and a list of directories. It uses md5 hashes to keep resource utilization down. I'm basically soliciting additional eyeballs for what I hope I've persuaded you is a good cause for more than one reason, if you find yourself with some time and curiosity. It's 108 lines of code (including the usage() function), and 15 lines of comments. The URL is http://dcs.nac.uci.edu/~strombrg/verify.html Thanks for even considering looking at this with me! From loritsch at gmail.com Sat Oct 16 13:34:53 2004 From: loritsch at gmail.com (Michael Loritsch) Date: 16 Oct 2004 10:34:53 -0700 Subject: automatic accessors to a member var dict elements? References: Message-ID: Nick Craig-Wood wrote in message news:... > Christopher J. Bottaro wrote: > > If I have the following class: > > > > class MyClass: > > def __init__(self): > > m_dict = {} > > m_dict['one'] = 1 > > m_dict['two'] = 2 > > m_dict['three'] = 3 > > > > Is there anyway to generate automatic accessors to the elements of the dict? > > For example, so I could say: > > > > obj = MyClass() > > obj.one # returns obj.my_dict['one'] > > obj.one = 'won' # same as obj.my_dict['one'] = 'won' > > > > By automatic, I mean so I don't have to write out each method by hand and > > also dynamic, meaning if m_dict changes during runtime, the accessors are > > automatically updated to reflect the change. > > Here is an old style class way of doing it. I think there might be a > better way with new style classes but I'm not up to speed on them! > > Note care taken to set m_dict as self.__dict__["m_dict"] rather than > self.m_dict otherwise the __setattr__ will recurse! You can put a > special case in __setattr__ if you prefer. > > class MyClass: > def __init__(self): > self.__dict__["m_dict"] = {} > self.m_dict['one'] = 1 > self.m_dict['two'] = 2 > self.m_dict['three'] = 3 > def __getattr__(self, name): > return self.m_dict[name] > def __setattr__(self, name, value): > self.m_dict[name] = value > > >>> obj = MyClass() > >>> print obj.one > 1 > >>> obj.one = 'won' > >>> print obj.one > won To me, it appears the Christopher is simply looking for a way to get/set members of a dictionary using a different syntax. That being the case, why not create a pythonic solution like the one above using new style classes, as we can derive directly from the dict type? In this case, we will just forward the __getattr__ and __setattr__ calls to __getitem__ and __setitem__, respectively. Here is the equivalent solution: class MyClass (dict): #New style class derived from dict type #Use same get/set syntax desired during construction def __init__(self): self.one = 1 self.two = 2 self.three = 3 #Get/set syntax changed with simple forwarding functions def __getattr__(self, key): return self.__getitem__(key) def __setattr__(self, key, value): self.__setitem__(key, value) Isn't this the type of thing that Guido van Rossum envisioned in trying to unify types and classes? Michael Loritsch From usenet at mail-2-me.com Thu Oct 14 16:21:39 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: Thu, 14 Oct 2004 22:21:39 +0200 Subject: Search-Filter for LDAP (MS Active Directory) In-Reply-To: References: Message-ID: Ames Andreas (MPA/DF) schrieb: > Hello, > > Dirk Hagemann wrote: > > >>I'd like to know how to set up a query for all computer-accounts in >>a special part of Active Directory by using LDAP. >> >>Example: >>all computers with a name like "ABC*" at "..., ou=Production, >>DC=business,DC=company,DC=com" >>>From these computers I want to get their OS, Service Pack and some >>other information. > > > I use python-ldap (http://python-ldap.sf.net/) to access Active > Directory. Example: > > # ----------------- code start ----------------- > import ldap, ldapurl > > proto = 'ldap' > server = 'youradserver.yourdomain.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('', > '') > > # search only within given subtree > base = 'ou=Production, DC=business, dc=yourdomain, dc=com' > > # search scope see rfcs for explanation; in your case it's probably: > scope = ldap.SCOPE_SUBTREE > > # this is the beef, i.e. the rfc2254 filter the following matches all > # entries in the directory, which might be many. OTOH, you often have > # server site limits on how much search hits may be returned for a > # single query; I dunno how this is changed within the query (probably > # some filter extension magic I haven't used yet) > query = '(objectclass=*)' > > # now your job is to find out the right query string; I don't know if > # for example computer accounts have a special objectclass, so I'll > # just assume it is called 'cAccount'. Further I don't know which > # attribute type denotes the name of the computer account you > # mentioned; I'll just assume its type is called 'displayname'. Under > # these assumptions your example above would translate to the > # following query (which won't work because my assumptions are > # certainly wrong): > # query = '(&(objectclass=cAccount)(displayname=abc*))' > > # limit the attribute types which you want to see in the result > # the following will give you the values of all attribute types of > # all matching directory entries > res_attrs = ['*'] > > res = ldap_obj.search_ext_s(base, scope, query, res_attrs) > print res > # ----------------- code end ----------------- > > > I haven't tested this special code but I'm using similar code on a > daily basis. > > If you are like many people and don't like plaintext passwords on the > wire you have at least two alternatives: TLS and SASL. TLS in Active > Directory means you'll want to use 'ldaps' as the urlscheme (start_tls > doesn't work yet, AFAIK). > > I had no luck with sasl (only GSSAPI available in my case). Although > I can get a TGT with MIT's kinit from my Active Directory server (this > is debian, I dunno how to get the TGT on a Micros~1 platform, but the > MIT's Windows port of their client tools seems to have some support), > there seems to be a bug related to packet sizes (either in AD or in > openldap's libldap). Maybe > http://www.openldap.org/lists/openldap-devel/200211/msg00035.html > could get you going. > > > HTH, > > andreas > Hi! I think I will not have to care about authentification in this code, because the script will run under user-context with domain-admin-rights. Thanks for the code - I'll try to test it tomorrow. :-) Dirk From richardblackwood at cloudthunder.com Sat Oct 9 23:06:15 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sat, 09 Oct 2004 23:06:15 -0400 Subject: Init a table of functions In-Reply-To: References: <1097371939.905273@mystique.esoterica.pt> Message-ID: <4168A727.6050606@cloudthunder.com> Robert Kern wrote: > Paulo da Silva wrote: > >> How do I program something like the folowing program? >> PYTHON claims it doesn't know about 'foo' when initializing K! >> The only way I got this to work was doing the init of K in >> the __init__ func. But this runs everytime for each object! >> When using the name of the function without 'foo', I don't >> know how to call it! >> >> Thanks for any help. > > > Move the table outside of the class definition > > class foo(object): > def f1(): > print 'f1' > f1 = staticmethod(f1) > > foo.K = {'f1': foo.f1, > } > > foo.K['f1']() > Right Right Right. Notice how he added the "object" as an arg to class foo. From jcarlson at uci.edu Fri Oct 8 15:30:17 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 08 Oct 2004 12:30:17 -0700 Subject: (solved) smtplib, capturing output from set_debuglevel ?? In-Reply-To: <01ee01c4ad65$396ec780$ccbefea9@twilliams> References: <00e701c4ad3f$b5e78390$ccbefea9@twilliams> <01ee01c4ad65$396ec780$ccbefea9@twilliams> Message-ID: <20041008122130.EDA1.JCARLSON@uci.edu> > I decided to bite the bullet and have a look at the code for smtplib, > (after being scared of changing it before), and of course its what I > should have done in the first place. I hope you didn't change your own copy of smtplib, but just subclassed it. Changing a standard module is a good way to get bitten in the ass, especially during Python upgrades. In regards to changing the standard library's smtplib permanently, you may or may not find support. A good way to find out is to post here with the subject "proposed change to smtplib in standard library", describe your changes, and if it has support, head to sf.net/projects/python, list it as an RFE, and offer the code you have written yourself. - Josiah P.S. Did you get my post with the multi-threaded output? You get the entire stream of debug data for a particular smtp thread in a single string. From deetsNOSPAM at web.de Mon Oct 25 08:23:29 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 25 Oct 2004 14:23:29 +0200 Subject: Implementing class attribute access methods via pseudo-functi on o verloading. References: Message-ID: > It's interesting to note that you prefer code like: theProblem.title = > "The Title" > > However, I wonder if people coming from the Java/C++ world prefer: > theProblem.title( "The Title" ) > > Obviously the first version is less typing! However, the second version > might feel more natural to Java/C++ programmers. Just an observation! > The reason java introduced the bean-convention with set*/get* methods (and maybe has/is on boolean values) was to allow to introduce a property-like concept in java - as its missed at syntactical level - with the assumption beenig that a get/set paired name is an actual property. There are apis for that, and e.g. gui-editors use it it create dialogs for configuring controls. So what you assume looking more natural and less awkward to java-people is an akward convention introduced to circumvent missing language capabilities - at least IMHO :) C# OTH has properties built in, as well as VB - and the make code look definitely nicer (apart from VBs ridiculous "let" statement and the general pains of that language...) -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Thu Oct 28 18:44:06 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 29 Oct 2004 00:44:06 +0200 Subject: New to Python: Features References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> <1gl6fnk.m1zq7z1fm0nhbN%aleaxit@yahoo.com> <3064b51d.0410260928.1873a20d@posting.google.com> Message-ID: <1gme4mk.1rlz70v1cswu9zN%aleaxit@yahoo.com> wrote: > aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gl6fnk.m1zq7z1fm0nhbN%aleaxit at yahoo.com>... > > > > No, no, I want the C speed. > > > > Then use C: no other portable language (including C++ when properly > > used) quite matches C's speed across the board. > > I doubt this assertion -- Fortran is portable and is easier to > optimize than C, in part because pointers are used less. For numeric computing, yes. "Across the board", no. I've done almost as much Fortran as C in my life... but while it was fully appropriate back when I was in IBM Research doing (what at the time was called) "supercomputing", when I moved to a small SW house doing CAD for mechanical engineering, I soon determined that Fortran's limitations were costing us a lot in both development time and runtime efficiency. There's a reason Fortran use has been steadily declining, while C's still number one despite the many languages that exist at its side or on top of it: even in technical areas such as CAD, the fraction of code that does strictly numeric computing is pretty small, overall. If you are blessed with superb Fortran coders and super Fortran compilers, there may be a case for mixed C/Fortran programming, where some strictly computational kernels are in Fortran while the rest of the programs' various bottlenecks are in C. Unfortunately, with the exception of a few platforms and social niches, superb compilers _and_ coders for/in Fortran are getting pretty hard to find, so this strategy can be hard to defend in most cases. "Strictly numeric computing" isn't even narrow enough. I regularly do (for my own private and personal research) huge unlimited-precision computations with integers and rationals, which of course _IS_ "strictly numeric" work, to the letter. Yet _this_ strictly numeric work isn't really in the field where Fortran enjoys any advantage, to the contrary. The computational kernels are best coded in C and machine language, and best coordinated/glued from Python. When my code is spending 80% of its time obsessively repeating a mere thousand or so lines of machine code, it would be just silly to spend time and energy, and decrease flexibility, by turning the few hundreds lines of Python that do all of the algorithmic coordination into thousands of lines of any lower-level language. > Fortran 95 and Python with Numeric or Numarray are comparably high > level languages, but Fortran has a performance edge of 2-100 in the I disagree on the level -- Numeric reminds me much more of APL, which was regularly used for exploratory numeric computing in IBM Research, before the most promising approaches, needing to run on frightening amounts of data, got recoded in Fortran (contradicting your assertion that "good programmers don't want to recode": if they're good, they _are_ in fact quite willing to, if and when top performance is needed in some computational kernel). Moreover, Python is definitely higher level (than even APL used to be) for all the _non_-numeric needs that scientific programs typically have nowadays, in addition to their computational kernels. If, for your range of problems and machines of interest, Numeric's computational kernels are so inefficient compared to identical computational kernels coded in Fortran, that's surely interesting -- and part of the reason a couple toolkits exist to facilitate gluing Fortran code to Python+Numeric programs (the other part, of course, is enabling reuse of the great mass of excellent existing Fortran libraries - reuse is good, and even if performance were identical with a recode, it would be silly to recode rather than reuse solid, fast, field-tested codes). That's part of Python's strength in numerical computing: neatest glue in the world between existing or specially coded computational kernels, be they in Fortran, C, C++, or machine language as in my (unlimited precision rationals) case -- _plus_ all the exploratory flexibility one may want, both in the classic numerical parts (via Numeric/numarray) and in such tasks as database access, visualization, monitoring, checkpoint and restart, and so forth. > tests I have run (several posted to comp.lang.python). According to > the Pyrex web site http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > the latest version is 0.9.3 -- this version number implies that Pyrex > is not mature. Fortran 95 compilers are mature. Nowadays, applications I've used pyrex for production work without any problems, but yes, once Open Source authors decide their work is mature they typically tag it as 1.0. However, not being subject to commercial pressures or deadlines, they're typically in no hurry whatsoever to reach that milestone; you should really read Eric Raymond's penetrating analysis of that fact in his excellent book "The Art of Unix Programming" (also available for free online reading). > where performance is critical are often run on Linux clusters (often > of AMD Opteron processors), and Fortran compiler vendors are > supporting these platforms. Are Pyrex and other Python projects being > customized in this way? I'm not sure what (if anything) is being done with Pyrex in the area of cluster computing, but there are quite a few other Python projects there, such as Pycluster. I don't know much about them, since I don't have a cluster at hand to try them on -- but you can sure find others here who do, if you post with more appropriate subjects to catch their attention. > > If you don't need portability, C's speed isn't optimal anyway; psyco (a > > just-in-time optimizer for Python) can sometimes beat C by going > > directly to machine language (but it only works for intel and compatible > > CPUs, not for example for the PowerPC chips used in Apple's Mac > > computers -- that is the downside, of course). > > There are optimizing Fortran 95 compilers for Intel Windows, Intel > Linux, AMD Opteron on Linux, PowerPC etc., listed at > http://www.dmoz.org/Computers/Programming/Languages/Fortran/Compilers/ > . You are conceding that Python is less portable if you demand > performance. No, I'm not: where the (expletive deleted) do you read that?! All I'm saying is that _psyco_ currently targets only Intel and compatible CPUs, so those are the ones where you can get psyco's own sometimes-beats-C performance, for now. Throughout my post, up to here, I was speaking about _portable performance *across the board*_ (where, generally, C yet can't be beaten -- although I _have_ seen some claims to the contrary by fans of Common Lisp and O'Caml, at least for some cases). Here, I'm explaining that, if and when you do not need portability, then there may well be even faster alternatives to C (still "across the board" in terms of application areas, but not necessarily of platforms). > There is even a free, fast compiler called G95 for these > platforms -- see http://www.g95.org . Are you claiming this is _MATURE_ while pyrex isn't? Literally speaking, you are, since you earlier stated, baldly and without any qualification, that "Fortran 95 compilers are mature", and here you appear to be implying that G95 is a Fortran 95 compiler -- so, the sillogism is compelling. Well, I've visited that huge, rambling homepage - and couldn't find a release number nor a pointer to the sources. I did easily find a kind of blog with all sorts of interesting news, such as (less than a month ago) the wrong sources getting compiled and causing confusion, etc; if these are signs of a mature project, we must be using a very different definition of the word "mature". And a list of binaries, of which zero (count'em, zero) are listed for any PPC CPU -- there is a claim later that the program works on G4 (a PPC CPU, though 32-bit; for power computing, one would typically be using G5, the newer 64-bit one, these days; Apple is even putting it in cheap home/consumer computers, and Virginia's supercomputer, one of the world's most powerful ones it seems, uses G5 PPC CPU's, too), but I couldn't find any useful link. Don't get me wrong: I'm overjoyed if open source is reaching good results in the world of Fortran compilers, at last (the g77 free Fortran compiler, way back when, was surely anything but a speed demon!-). But I think it's dishonest to claim or imply "maturity" for this project while asserting pyrex is "not mature". Do you really believe that not having a release number, or hiding it well, enhances a project's maturity? I don't see how you could state this in good faith. Alex From reinhold-birkenfeld-nospam at wolke7.net Sat Oct 30 10:03:49 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Oct 2004 16:03:49 +0200 Subject: Plugin system In-Reply-To: <41839c8b$0$78279$e4fe514c@news.xs4all.nl> References: <2uhjppF2a61u6U1@uni-berlin.de> <41839c8b$0$78279$e4fe514c@news.xs4all.nl> Message-ID: <2uhla5F2ahviqU2@uni-berlin.de> Irmen de Jong wrote: > Reinhold Birkenfeld wrote: > >> How would you implement a plugin system (for a web-based application)? > > This is so general a question that I cannot think of anything concrete to answer. > Please ask again, with more detail about what you want/need/have in mind. Okay, the question is too open: My focus is on how you would structure the plugin code (directories, files) and how you would write code to load these plugins. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From rakis at gmpexpress.net Mon Oct 4 22:16:36 2004 From: rakis at gmpexpress.net (Tom Cocagne) Date: Mon, 04 Oct 2004 22:16:36 -0400 Subject: Embedding Python References: <4audnXFO7feC3MPcRVn-vg@rogers.com> Message-ID: <10m417q6j9hosef@corp.supernews.com> I've?recently?been?working?with?both?extending?and?embedding?Python?and have been wondering about some similar issues. Something that just recently occurred to me is that you might be able to use Python's Global Interpreter Lock to implement a fairly simple multi-threaded lock-step solution. Consider the following: 1. Your program starts up, Initializes the Python interpreter, and acquires the GIL (Global Interpreter Lock). 2. The program then creates a new thread to run the Python scripts. In theory, this thread will immediately block in an attempt to acquire the GIL 3. In your main GUI loop, you set a periodic timer that expires at a rate of say.... 20 Hz (this would likely need tuning) that, upon expiry, uses the following pseudo-code: ?global_interpreter_lock.unlock() ?#?Give?Python?approximately?20?msec?of?execution?time ?main_application_thread.sleep(20?milliseconds) ?global_interpreter_lock.lock() ?....?continue?normal?QT?processing?..... I haven't put a whole lot of thought into it yet but on the surface it seems like an approach along these lines would be fairly easy to implement and should guarantee that only 1 thread is ever accessing your application. Using this approach would involve at least three tuneable parameters. The GUI timer to indicate how often Python should be given some CPU time, the delay to determine how long the Python interpreter should be allowed to run, and byte-code check interval Python uses to release the GIL (described in the C-API documentation on Python+threads). Getting all these right might take some time. ??Again,?I?have?never?actually?tried?this?so?there?could?be?some?demons lurking in the shadows. Anyone see problems with this approach? ?Cheers, ?Tom Martin wrote: > Greetings, > > I am new to python and wish to embed python in an 3D graphics > application to provide application automation. The high level goal is to > be able to drive my app from a script for batch job like behavior rather > than via the GUI (ie. I would like to run a script and see those changes > reflected in the GUI as if the user had clicked buttons, etc.) The > application is written in C++ and uses QT for the GUI. > > I have read the python docs on python.org and (using SWIG) have been > able to create Python shadow wrappers around the C++ classes I want to > allow users to have been able to call them via python scripts. This part > works well. However in terms of embedding, I feel like I am missing > something. > > For those of you familiar with QT, you know that QT apps run in a > single-thread (essentially). Although QT supports threads, a > QApplication based program is (by default) single-threaded. Callbacks > (slots in QT speak) can be hooked up based on a users actions, but these > callbacks all run in the main program thread. > > So here is my question ... What's the best way to integrate Python into > an app such as the one I am describing. > > Here's what I have though of ... > > Alternative #1 > Add boiler plate python embedding code (ie. Py_Initialize, > PyRun_SimpleFile(...), Py_Finalize) in a QT callback. Unfortunately, > since the QT app is single threaded, this will wedge up the GUI, until > the script is done. Not good. > > Alternative #2 > Keep the app as a single threaded app and interpret the script piece > meal (ie. one statement at a time) at some timed interval. Allow for GUI > updating between statement interpreting. Unfortunately, groveling over > the Python C API, this does not look particularly easy either and would > more or less require cutting/pasting much of the interpreter guts in my > app. Furthermore, incomplete statements (ie. lines ending in : ) seem to > present a problem to PyRun_SimpleString. > > Alternative #3 > Split the app up so that it is broken up into 2 threads (GUI and guts). > The interpreter would run in the gut thread and change the internal data > store. The GUI would then have to be smart enough to update itselft. > Unfortunately, this requires major app re-architecting (something I am > trying to avoid). > > Alternative #4 > Spawn an interpreter thread using multi-threaded interpreter calls. This > would then require locking/unlocking shared resources between > Interpreter thread and the rest of the app. It feels like if I am going > to do this #3 may be a cleaner approach. > > I am sure someone out there has done this before. > > For me, the key point is that I want to add this functionality without > disrupting the entire product. I am trying to evaluate what is > architecturally the best approach and what will give me the most bang > for my buck. > > Any help would be appreciated. > > Cheers and Thanks, > > Martin From richardblackwood at cloudthunder.com Tue Oct 5 17:54:56 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Tue, 05 Oct 2004 17:54:56 -0400 Subject: New to Python: Features In-Reply-To: <20041005132902.ECE3.JCARLSON@uci.edu> References: <20041005111159.ECE0.JCARLSON@uci.edu> <4162F271.9060407@cloudthunder.com> <20041005132902.ECE3.JCARLSON@uci.edu> Message-ID: <41631830.2000401@cloudthunder.com> >Ahh, but here's the rub; I posted responses to your questions that were, >on the most part, helpful. Had I broken the law in my post (a >surprisingly easy thing to do in the states), knowing that I was who I >claimed to be would be particularly useful. > > How might you break the law and how might I be interested in such law-breaking? >In this case, you are making the claim to not use this information as >part of a homework assignment, which while not being illegal, is >generally understood to be amoral, according to academic practices in >most parts of the world. > > Indeed, I don't remember myself ever cheating (in the suggested manner or otherwise) , though I did write people's philosophy papers for them (for money). >You have managed to be quite reasonable and calm through the entire >thread, but you seemed to have missed much of the sarcasm in "Mark >English's" post. > > > > Mark English was helpful as well. I enjoyed his sarcasm but chose to discard (or otherwise ignore) it in my reply. > > >Ahh the devil, if one chooses to believe in them, I am surely not. >Mailing list Don...not even close. I'm just a guy who can prove who he >is. And at least for some places on the internet, that can matter. > > > I merely meant that you appeared to be playing one, not that I (or you) believe they exist. But in order for us to talk of them (and their existence/non-existence) we must have a pre-existing notion(s) of what one is. Indeed, this is what I referring to, the *notion* of a devil. I found great humor in your reply. Indeed, your replies were helpful. What might you do illegal of which I might want to discover your true identity? If you begin cursing and saying fouls things, I would merely leave the mailing-list/newsgroup or hope that the admin would kill-file you. No need for legal action. As I haven't concocted anymore lists of questions, people can redirect their attention elsewhere. That is unless people enjoy this discourse. From ville at spammers.com Wed Oct 13 02:59:28 2004 From: ville at spammers.com (Ville Vainio) Date: 13 Oct 2004 09:59:28 +0300 Subject: Static typing in py [was Re: Some notes] References: <5c882bb5.0410121238.71ae761a@posting.google.com> Message-ID: >>>>> "Josiah" == Josiah Carlson writes: >> - The optional static typing seems a quite nice thing (for >> compilers too, they can produce faster code. It can probably >> allow faster and smaller arrays, like those of numarray). Josiah> Asking for static typing in Python is a pretty big Josiah> request. It seems from those responses to similar Josiah> questions, the answer is simply "static typing isn't Josiah> coming to CPython any time soon, probably not even for Josiah> Py3k". Guido has repeatedly expressed that Python will probably get optional type declarations in the future. I am not sure to what extent that implies static typing, but it's definitely on the map. Boo already has type declarations, and I imagine the CLR implementations of python (IronPython, Boo) will benefit most from type declarations, performancewise. The benefit to CPython might be more indirect, simplifying the work done by things like Psycho. Still, I see type declarations opening so many doors that they should be in the language - even if the performance improvement is zero at the first stage. Python is not just CPython these days. Josiah> Keep wishing, but unless you implement it, I wouldn't get Josiah> my hopes up. Implementation can be trivial - the interpreter could just assert isinstance when check_type_declarations is true. The harder part is coming up with all the semantics. -- Ville Vainio http://tinyurl.com/2prnb From yaipa at yahoo.com Fri Oct 8 00:51:48 2004 From: yaipa at yahoo.com (yaipa h.) Date: 7 Oct 2004 21:51:48 -0700 Subject: literal hex value to bin file. References: <6e07b825.0410070125.5b3e47a3@posting.google.com> Message-ID: <6e07b825.0410072051.5504e4f2@posting.google.com> Peter L Hansen wrote in message news:... > yaipa h. wrote: > > Sorry if this has been asked before, doing a search on c.l.p, I didn't > > find this particular use case. > > > > I wish to use the struct module, in windows, to pack hexdigits in such > > a way that when I pack, say 0xa into a packed object, I can then use > > it to find 0xa in a binary file. > > The question is unclear to me, but wouldn't just using "\x0a" > build a string (i.e. a 'byte sequence') with identical contents? > A "packed object" from struct is merely a string. > > > Likewise, I wish to build a hex sequence from an Assembly language > > .lst (text)file so that I can search for that sequence of hex digits > > in a binary file. > > Unclear. Please provide examples of before and after cases > of each thing mentioned above to help guide us... > > -Peter Peter, Thanks. I seemed to have worked it out. The bit of code below will write the actual hex string literal to a binary file as is. What I kept getting was the hexascii representation of the hex string, so that '9' would write to file as 0x39 and 'a' would write to the file as 0x61. What I wanted was '9' to write to the file as 0x09 and '7f' to write out as 0x7f. #----------------------------------------------- import struct a = struct.pack('B', int('ff', 16)) fh = open("a.hex", "wb") fh.write(a) fh.close() #----------------------------------------------- # results in the binary file 'a.hex' containing, 0xff # only Peter, thanks again for your attempt to understand my confusion. Cheers, --Alan From richardblackwood at cloudthunder.com Sun Oct 31 22:19:17 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 31 Oct 2004 22:19:17 -0500 Subject: OT: Ruby programmers use Python (was Re: ruby on rails ... python on ?) In-Reply-To: References: Message-ID: <4185AB35.6050103@cloudthunder.com> > > > To the OP: there are several Python "application frameworks" > which on the surface appear to be similar in goal to Rails. > I don't know much about them, and at the moment even their > names aren't coming to me, so I can't help more than that. > I think a search for "enterprise application framework Python" > would probably turn up at least one of them. > > -Peter Do you mean Zope? From spariam at hotmail.com Sat Oct 9 18:44:34 2004 From: spariam at hotmail.com (spar) Date: 9 Oct 2004 15:44:34 -0700 Subject: complex data structure - insert value Message-ID: I'm converting a Perl script to Python and have run into something I'm not sure how to do in Python. In Perl, I am running through a couple loops and inserting values directly into a complex data structure (array->hash->array). This isn't the actual code, but should demonstrate the general idea: foreach $bar_count(@bars) { foreach $el_count(@els) { $var = somefunc($bar_count,$el_count); $data[$bar_count]->{'CC'}->[$el_count] = $var; } } Basically I'd like to do the same thing in Python. I've written a convoluted test script where I can print an element: print data[0]['CC'][1] but I can't insert directly like I do in Perl (data[0]['CC'][1] = $var). In my test script I've simply initialized my lists and dictionary at the beginning of the script, not by iterating an inserting values as in the Perl example. Any advice appreciated...thanks. From peter at engcorp.com Tue Oct 26 14:56:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Oct 2004 14:56:58 -0400 Subject: Language comparison site - Python ranks #8 on the A-list In-Reply-To: References: Message-ID: Paul McGuire wrote: > I just tripped over this site (http://www.tiobe.com/tpci.htm), and google > shows that there has only been a brief mention of it on c.l.py in the Aug 12 > Dr. Dobb's Python-URL post, so I thought I'd pass it along for those looking > for some quasi-quantitative Python advocacy data. > > It's also interesting to look at the comparitive trend chart lower down on > the page. But my question is, what the heck happened in March '04? > (Several languages showed drastic swings of several percentage points up or > down - I suspect that this actually reflects some artifact of the data > sampling process, perhaps a software change at Google/Yahoo that would alter > their search outputs, which are inputs to this algorithm, which is why I > call it "quasi-quantitative.") Interesting reading from years past: http://groups.google.com/groups?q=group%3Acomp.lang.python+www.tiobe.com (Perusing those threads again to reminisce, I discovered that the site has variously claimed Python was an A++ language, and a "B status language with declining popularity".) I remain to be convinced the ranking has any more meaning than as a marketing tool to attract people to the their site so they can sell more services. (Not that this is a bad thing, for them anyway.) -Peter From pythongnome at hotmail.com Sat Oct 16 19:46:02 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Sat, 16 Oct 2004 23:46:02 GMT Subject: interactive piano Message-ID: <_oicd.7316$SZ5.2486@newsread2.news.atl.earthlink.net> Does anybody know of any projects relating to an interactive piano. And when I say that, I mean you can click on a particular note or press keys on the computer keyboard and hear the note(s) being played. TIA, Lucas From PeterAbel at gmx.net Wed Oct 13 13:22:14 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 13 Oct 2004 10:22:14 -0700 Subject: windows References: Message-ID: <21064255.0410130922.40e59cb@posting.google.com> Ajay wrote in message news:... > hi! > > i have two tkinter windows on top of each other. i would like it so that > the user has to complete the fields in the top windows before they can > interact with the window below it. that is, i dont want the user to close > the top window or minimize it or send it into the background. > > how would i do it? > > thanks > > cheers > > > > > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. There are documentations which say that Tkinter.Toplevel has a methode .transient(root) which should make the Toplevel window transient to its root window. But I never managed to make it work.(W2K Python 2.2.2). But here is a hackaround: import Tkinter #---------------------- def deiconify(widget): #---------------------- widget.deiconify() widget.grab_set() #---------------------- def withdraw(widget): #---------------------- widget.grab_release() widget.withdraw() # The root window root=Tkinter.Tk() # The Toplevel window tl=Tkinter.Toplevel(root,width=400,height=200,bg='white') # Withdraw Toplevel, when destroyed tl.protocol("WM_DELETE_WINDOW",lambda w=tl:withdraw(w)) # Make Toplevel not resizable tl.resizable(width=False,height=False) # Default state of Toplevel is withdrawn tl.withdraw() # Give Toplevel window a title tl.title('Toplevel-Window') # A Button on the root window to make Toplevel window visible Tkinter.Button(root,text='Toplevel on',command=lambda w=tl:deiconify(w)).pack() # Start mainloop root.mainloop() Regards Peter From jeff at ccvcorp.com Mon Oct 11 21:41:41 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 11 Oct 2004 18:41:41 -0700 Subject: Alternatives for pickle? In-Reply-To: References: Message-ID: <10mmddorhvnj71f@corp.supernews.com> Antoon Pardon wrote: >I also thought about writing out a string that, when read >back in and fed to eval would recreate the structure. But >that seems to be just as insecure if not more so. > > As I understand it, this is *exactly* what pickle already does. >So how do you serialize data in python, when you want >a somewhat secure mechanisme. Preferably where a user >can make a puzzle file by hand in a text editor. > > I'd agree with the earlier comment -- define your own file format, and write code to parse that format and instantiate the necessary objects. If it's hard to define something that's both effective for your purposes, and hard to hand-code in a text editor, then consider writing a puzzle-editor app that will allow GUI creation of puzzles which can be saved in your custom file format. Jeff Shannon Technician/Programmer Credit International From kkuppa at xora.com Wed Oct 6 05:38:52 2004 From: kkuppa at xora.com (Kiran Kumar) Date: Wed, 6 Oct 2004 15:08:52 +0530 Subject: Java to Python byte code Message-ID: Hello All, I am just curious to know if there is any tool which would let me cross compile java source code to python byte codes directly. I have developed a library [in Java ] for statistcs and machine learning. Some of them are computationally demanding. My line of thinking is , if I could get to compile java source to python byte code , it would be more faster than interfacing with Jython. Any comments would be helpful Thanks, Kiran Kumar --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/2004 -------------- next part -------------- An HTML attachment was scrubbed... URL: From opengeometry at yahoo.ca Thu Oct 7 17:52:34 2004 From: opengeometry at yahoo.ca (William Park) Date: 7 Oct 2004 21:52:34 GMT Subject: Job postings References: <41634A6E.D0A49DCD@yahoo.com> <7xpt3wtvci.fsf@ruckus.brouhaha.com> <41644F87.6F87F2D0@yahoo.com> Message-ID: <2sls51F1mpkjbU1@uni-berlin.de> Jive Dadson wrote: > > > Paul Rubin wrote: > > > > Jive Dadson writes: > > > Where can I post a job description for a Python programmer? He or she > > > would have to know both application programming in Python, and should be > > > able to port Python to a "friendly" operating system. > > > > I think you just posted one. What's the target OS? Where's the job? > > The company is in San Jose, CA. The OS is a OnTime RTOS-32. The first is gcc, glibc, bison, make, sh, and other things needed for compile. -- William Park Open Geometry Consulting, Toronto, Canada From mediocre_person at hotmail.com Sat Oct 16 19:14:26 2004 From: mediocre_person at hotmail.com (Mediocre Person) Date: Sat, 16 Oct 2004 18:14:26 -0500 Subject: Python control of desktop properties In-Reply-To: <416c8404$1_3@alt.athenanews.com> References: <416c8404$1_3@alt.athenanews.com> Message-ID: <4171aa7a_3@alt.athenanews.com> Mediocre Person wrote: > > One of my students is interested in using Python to control his > (Windows) desktop, and wants to write a program to change the desktop > background or wallpaper. I told him I'd look into this, but I've had to > admit defeat. > Thank to all for the replies--got the code working now. Nick. From fakeaddress at nowhere.org Thu Oct 7 23:34:22 2004 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 08 Oct 2004 03:34:22 GMT Subject: Simple Python web proxy stalls for some web sites In-Reply-To: References: <41649d0e@post.usenet.com> Message-ID: <1Vn9d.25933$QJ3.12295@newssvr21.news.prodigy.com> Richie Hindle wrote: > By default, urllib2 specifies "User-Agent: Python-urllib/x.y" Some > sites, Google included, reject this because they don't like to be > web-scraped. Google dis' Python? No way! I checked, and Google is answering in good faith. Some web sites block unknown user-agents, but only the most evil would hang the connection. Google doesn't even block wget. -- --Bryan Full disclosure: I used to work for Google. I don't now, and never did have any authority to speak for them. From aisaac at american.edu Mon Oct 25 12:15:00 2004 From: aisaac at american.edu (Alan G Isaac) Date: Mon, 25 Oct 2004 12:15:00 -0400 Subject: Pythonic function composition References: <10nq3c4j3lst8e2@corp.supernews.com> <2u4k8aF269be0U1@uni-berlin.de> Message-ID: <10nq9iaj6e74565@corp.supernews.com> "Oliver Fromme" wrote in message news:2u4k8aF269be0U1 at uni-berlin.de... > There's no need to juggle with lambda in this case. > Lambda has its uses, but this isn't one of them. I kind of like the lambda version (see Peter's post). But maybe it is more opaque. Thanks, Alan From andymac at bullseye.apana.org.au Fri Oct 8 19:49:12 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 9 Oct 2004 09:49:12 +1000 (EST) Subject: Can't get curses to work in python In-Reply-To: <200410080848.15470.scott_list@mischko.com> References: <200410080848.15470.scott_list@mischko.com> Message-ID: <20041009094729.W36393@bullseye.apana.org.au> On Fri, 8 Oct 2004, Scott Chapman wrote: > I can't figure out how to get curses (ncurses) enabled in Python. I have > ncurses and ncurses-devel rpm's installed on my system (Suse 9.1) but I can't > figure out how to get it enabled when I compile Python. Check, & if necessary change, the library and included path values for the curses module in the setup.py script in the root of the Python source tree. ------------------------------------------------------------------------- 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 usenet.0.lho at spamgourmet.com Fri Oct 29 02:27:36 2004 From: usenet.0.lho at spamgourmet.com (Joachim Bowman) Date: Fri, 29 Oct 2004 08:27:36 +0200 Subject: Open Source License Question In-Reply-To: References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <97-dnSRAYPEwPuLcRVn-rA@rogers.com> <6f402501.0410271123.5a7e68d9@posting.google.com> Message-ID: <2ue65gF28i9f7U1@uni-berlin.de> Hi, Dan Perl wrote: > "Michael Foord" wrote in message > news:6f402501.0410271123.5a7e68d9 at posting.google.com... >>A lot of people use python as part of their job and are active >>participants in teh python community. A lot of what I write are >>library modules to do a particular job. Using the GPL means someone is >>unable to use your work in a business setting. i don't expect other >>people to sell products containing my work - but neither do I want to >>prevent them from being able to use it. > > Fair enough. LGPL, X, or BSD should allow you to do that. So does the GNU GPL. Freedom/Open Source and commercial use are two orthogonal concepts. The two don't interfere in any way. You can have Free Software (under the GPL) that is used and distributed commercially, Free Software that is used and distributed in a non commercial way (Python), proprietary software that is used and distributed commercially (think about MS Word), and proprietary software that is used and distributed free of charge and without a commercial background (sometimes called freeware). J From aleaxit at yahoo.com Fri Oct 29 19:18:02 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 30 Oct 2004 01:18:02 +0200 Subject: Interface of the set classes References: <41824654$0$1779$636a15ce@news.free.fr> <1gmfcnn.1kc0foj1j6zq3hN%aleaxit@yahoo.com> <4182518e$0$5916$626a14ce@news.free.fr> <1gmfg7o.a3ycdbrc571eN%aleaxit@yahoo.com> <41826d85$0$17459$626a14ce@news.free.fr> Message-ID: <1gmfzoq.99sjae1sgqm5pN%aleaxit@yahoo.com> Pierre Barbier de Reuille wrote: ... > > So, you cannot "switch freely" -- there are constraints. > > Right ... but take hash_set and you have exactly the same kind of "set". > In my case, I already had the '<' operator ... so it wasn't a problem. > Then, you'll argue that you need to be hashable. True, but as I said (I > don't mean here I was clear about that :o) ), the choice of the > container usually depend on the data set. Sure. > > call it S. You can write V[3], but you can't write S[3], for example. > > Here, too, your assertion that "you can switch freely" is utterly > > baffling. > > Yes, that's why I needed __getitem__ only because some things cannot be > done (in Python 2.3) without. Such as...? 'tee' is only needed if you need to "move forward a bit" on one branch and then _backtrack_ to a previous snapshot, or the like. If all you're doing is suspend an iteration and then resume it, say: iter1 = iter(container1) iter2 = iter(container2) print 'here is the part of ct 1 up to the first FOO if any' for item1 in iter1: print item1 if item1 == 'FOO': break else: print 'Ah well, no FOO!-(' print 'and here is the part of ct 2 up to the first BAR if any' for item2 in iter2: print item2 if item2 == 'BAR': break else: print 'Sigh, no BAR!-(' if item1=='FOO': print 'And here is the rest of ct1' for item1 in iter1: print item1 if item2=='BAR': print 'And here is the rest of ct2' for item2 in iter2: print item2 IOW, as long as you only need forward iteration (w/o snapshot/backtrack), you're in clover. If you do need to "snapshot and backtrack", in the _general_ case you're best off snapshotting into a list anyway - tee, in general, can't do better than that (until and unless the PEP on copyable iterators lets suitable iterator objects cooperate more deeply with tee...). So "cannot be done" is a definite overbid -- you may just be spending a little more time or memory than you'd like, worst case. > > It's not: neither in Python nor in C++ can you switch freely. > > True, but in part ^_^ In C++, you can easyly design algorithm working > with whatever sequence you have. But for that you'll have to use > templates, iterators, probably tags, and on. But it's possible ... I > don't see a way to do it in Python ... and that's my whole point. Python has iterators, and doesn't need templates, since signature based polymorphism is intrinsic. Python only has forward iterators (actually only _input_ iterators, since you can never alter the underlying container directly through an iterator) so what would it do w/tags? If your complaint is that Python needs more categories of iterators, please express your complaint in these terms -- rather than in unrelated terms criticizing the design of container types, a cri de coeur that's actually quite unrelated to the complaint. I used to wish for 'snapshottable'/'restartable' iterators, but 'tee' basically gives me the equivalent (though I'd still dearly love to know that all suitable iterators _cooperate optimally_ with 'tee', that, at least for builtin ones, is just a matter of implementation -- exposing it as _design_ is ``just'' an issue of letting *user-coded* iterators cooperate with 'tee' just as fully, if and when feasible). I still do wish (somewhat) for some architecture for output iterators, and (more) for one for forward iterators. (I would imagine that, if we had forward iterators, an output iterator would just be a forward iterator that doesn't return anything useful upon .next() and doesn't raise StopIteration -- just offers something like a .set(newval) method, or whatever a forward iterator would offer for that purpose). Funny enough, not once since C++ stopped being my main programming language have I found myself wishing for any other category of iterator in any other language. Perhaps just because the kind of container that naturally can support a forward-backward iterator isn't common anyway, and a random-access iterator basically means indexing -- and then I'd rather use indexing (and slicing...). > Yes, but use insert_iterator and you can insert with both vector and set > with the same syntax ... even if, obviously, the position you gave for > set will be ignored. So : > > inserter(result, result.end()) = 3; > > will insert 3 into result, at the end if result is "ordered" (as the > list in python), or where it has to be for "sorted" or "unordered" > containers. Genericity in C++ comes from template functions most of the > time. Again, this basically seems to me to be a wish for more categories of iterator. The key reason this cannot be done directly in Python is that there is no output iterator concept. Of course, it's not rocket science to 'roll your own' in Python (in Python style, of course). The equivalent of "specializing a template" requires some kind of typetesting or featuretesting; and we don't have a "just past the end" ``bookmark'' to use, so, for example, the insert method of a list can never be used to mean 'append' (sigh). So, we probably need name distinctions between insert_at_end and insert_before_position -- I don't think anybody will ever convince GvR that the latter should accept and ignore a position argument, btw. But at least insert_at_end should be uncontroversial: def insert_at_end(container): try: return container.append except AttributeError: pass try: return container.add except AttributeError: pass try: update = container.update except AttributeError: pass else: return lambda xy: update((xy,)) raise TypeError, "can't insert-at-end in %s' % type(container) and then of course the equivalent of your snippet above is insert_at_end(result)(3) [[ You'll never manage to get 'assign to a function call' into Python, but the syntax sugar of a call is pretty reasonable here anyhoo. ]] Of course, if result is a dict this will fail (you'd need a 2-item tuple, or something that can pass for it in a dim light, as the argument), just like your C++ snippet will fail if result is a std::map (you'd need an std::pair as the RHS) -- though C++ will fail at compile time, and Python at runtime, as usual. > > Not when the semantics are too different, as in the case of S and V. > > Ok, that's something I don't agree ... for me there is a common semantic > between S and V which is "storing values in a linear container". After > that, you can put the properties you need in that container, but if I > need to write an algorithm whose only assumption is "a linear container" > I want to be able to use whatever linear container I have ... and I > don't want to reimplement it for each. So write that insert_at_end function -- it IS pretty simple, after all. Put it in your myneatutils.py module and import it everywhere. Or put it into a module that you call std.py instead, so the parallel with C++ will be even clearer -- std::inserter vs std.insert_at_end, etc. Faking that you can insert at any point for a container in which you CAN'T is extremely dubious, btw. Even the _at_end part of the name of the function I suggest may be going overboard. After all, any algorithm that depends on the common semantics between S and V had better NOT believe anything it inserts does go 'at end', so maybe a name such as 'insert_wherever_it_is_most_convenient_for_you' might be better (although a little bit verbose). > > Well, you surely didn't get operator[] on C++'s std::set<...>s, that's > > for sure... > > Well, no ... but it's not needed ^_^ And if I really need it you have > the "advance" template function that do the __getitem__ stuff in the > most efficient way, whatever your _linear_ container is. Again, that's obviously trivial to write for Python, since Python doesn't have random access iterators, so the most efficient way for any container c to get an iterator starting at its 5th item will be to start with iter(c) and step forward 5 times (with itertools.islice)...;-) (Well, with a list you could slice -- if you never needed to write into the original list, which, as I mentioned, Python has no iterator kind for doing, anyway; if you want to prefer this solution, try/except is just friend -- feature-testing, basically). Again, a reasonable complaint (if you can convince Raymond Hettinger, basically) is that itertools.islice should be able to cooperate specially with some privileged iterators (builtin ones only, or more ambitiously, user-coded ones too), like itertools.tee should, again by feature-testing. Essentially an implementation issue as long as you stick to builtins, becomes a design one if you want usercoded ones too. > So I hope I made my point clearer this time ^_^ I used Python for a bit Sure! If you had whined about the povery of kinds of iterators that Python supplies, rather than (as per subject) about the interface of the set classes, it would have been quite clear from the start. > lists, sets and dictionnary. And I don't really see any other way to do > that (but to add methods to the sets ... and I don't want to do so). No need: the Python equivalent of C++'s specializing of templates (just like that of C++'s overloading) is feature-testing (or type-testing, but generally that's _not_ warranted -- feature-testing allows user-coded types to cooperate just as well!). So, the above-exemplified function is the Python equivalent of a C++ template function with specializations. Of course Python does more at runtime that C++ does at compiletime -- but that applies in several other ways, anyhow;-). > Ok, so how do you write an algorithm on a container without specifying > which, knowing that you cannot use the iterators, neither the signature > of the class, nor the derivation ? You encapsulate the feature-testing (looking for suitable methods to either return directly, or wrap in inner functions -- not necessarily lambdas, an inner 'def' will often be preferable -- to return) into functions, once -- equivalent to a C++ template functions w/specializations. Then you write your algorithms in terms of those functions, just like, in C++, you'd write them in terms of template functions (either coded by yourself, or taken from some library coded by others, such as the excellent Boost people). > That was all the methods I imagined for Python's genericity. But none of > them work when you see the base containers. "The signature of the class" (or, rather, some specific methods thereof) is really all you need. But it's best to push that detail into a function, as above. Should you ever need to optimize away the process for some given types, it's easy, too: at_end_inserters_by_type = { list: list.append, collections.deque: collections.deque.append, set: set.add, } def insert_at_end(container): m = at_end_inserters_by_type.get(type(container)) if m is not None: return m.__get__(container) ...same as before... Note that I have kept the helper dictionary exposed so it's easy to add optimized customizations, just as in C++ it's easy to add template specializations. Not just for user-coded types, but also for existing ones which this particular utility module isn't optimizing for, e.g.: import std import array std.at_end_inserters_by_type[array.array] = array.array.append and the like (assuming std.py is the module where we have insert_at_end and its supporting optimizations-helper-dictionary). If you have several such functions needing helper dictionaries, you may make a dictionary of dictionaries, keyed first by the function, and maybe expose a helper function to register optimization-specializations for a given function, rather than let user-level code deal with directly indexing dictionaries. Then the above specialization might become: std.specialize(insert_at_end, array.array, array.array.append) As long as, after checking the specializations, the function continues with feature-testing as before, the specializations may only be needed for performance, or for existing types (maybe from some library) that supply the needed functionality but need interface adaptation, basically like in C++. Alex From cce at clarkevans.com Wed Oct 13 14:43:33 2004 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 13 Oct 2004 14:43:33 -0400 Subject: I sing the praises of lambda, my friend and savior! In-Reply-To: <10mqr0rlj9h6r69@corp.supernews.com> References: <10mli0vohrtf8b6@corp.supernews.com> <10mllq67t1qah3b@corp.supernews.com> <10mo6q66oi0kj04@corp.supernews.com> <10mqr0rlj9h6r69@corp.supernews.com> Message-ID: <20041013184333.GB47197@prometheusresearch.com> On Wed, Oct 13, 2004 at 10:58:14AM -0700, Jeff Shannon wrote: | Antoon Pardon wrote: | >I find it better to let the coder decide what makes sense in his program | >and what not. | | Which is the Perl philosophy. Many people seem quite happy with Perl | because of this TMTOWTDI attitude; personally, I prefer Python's clarity | and simplicity. On this list, that's damn near close to an ad hominem attack. There are more than one way to do many of things in Python, and just about every "feature" that gets added is yet another way to do something that is already being done. This doesn't stop features from being adopted, does it? Every list comprehension has an equivalent version using a while-loop. I could go on with examples, but your assertion is a leaky bucket, so why bother waste the space? Your arguments thus far have been "I don't use it, thus it probably isn't useful, and therefore, no one should be able to use it." It's an uninformed position and frankly, not very helpful. I use lambda because it: - puts the definition of an expression right where it is used; - doesn't require me to mint a name, or worry about other possible calls to the same expression; and - is efficient use of vertical coding space. All of these reasons provide clarity in maintaining code. If you are working with a programming style that uses CPS, deferred execution, or similar mechanism with heavy callbacks or passing functions, you will understand the importance of the above features. Kind Regards, Clark From tjreedy at udel.edu Tue Oct 12 21:24:33 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 12 Oct 2004 21:24:33 -0400 Subject: Ok, I'm quite new to Python References: Message-ID: "Michael" wrote in message news:ckhrcs$g92$1 at hercules.btinternet.com... > But i'm a good c++ programmer. > > What i want to do is parse a text file and store the information in > relevant > fields: A more useful-to-the-reader and possibly more fruitful-to-you subject line would have been something like 'Need help parsing text files'. tjr From bokr at oz.net Sun Oct 31 01:48:17 2004 From: bokr at oz.net (Bengt Richter) Date: Sun, 31 Oct 2004 05:48:17 GMT Subject: Python-list Info Page References: Message-ID: <418467cb.1220411769@news.oz.net> On Sat, 30 Oct 2004 23:43:40 -0400, Gary Robinson wrote: >I am trying to understand a couple of nuances of inheriting from the >tuple type. > >The following class definition works nicely: > It may appear to, but it's not doing what I think you think it is ;-) >class Test(tuple): > def __init__(self, tup): > self.x = 5 > self = tup The above is just rebinding the local name 'self', which _was_ bound to your instance (which gave you the access to make self.x = 5 work), but as soon as __init__ exits, that last self binding is gone. >a = Test((1,2)) >print a, a.x > >The result of that print is "(1, 2), 5". Yes, the (1,2) that you passed to Test, got passed on to tuple.__new__, because there was no Test.__new__, and so the normal tuple creation took place. Then __init__ got called. > >But the following version: > >class Test(tuple): > def __init__(self, tup): > self = tup > self.x = 5 >a = Test((1,2)) > That's because you changed the self binding to whatever was passed in as tup (a real python tuple (1,2), not an instance of your subclass) and you effectively tried to hang an attibute x onto a native tuple, like: >>> self = (1, 2) >>> self.x = 5 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'tuple' object has no attribute 'x' >blows up in Python 2.3, complaining that attribute x doesn't exist. > >I'm not clear on why one works and not the other, or whether there's a Neither one worked ;-) >better syntax for assigning an attribute to a tuple subclass in the >__init__() method. > >Anyone have any thoughts?? If you want to modify tuple creation from the constructor argument, you will have to define a __new__, e.g., >>> class Test(tuple): ... def __new__(cls, tup): ... inst = tuple.__new__(cls, tup+('mod from __new__',)) ... inst.x = 5 ... return inst ... >>> a = Test((1,2)) >>> a (1, 2, 'mod from __new__') >>> type(a) >>> a.x 5 You notice I did the __init__ job of self.x = 5 right in __new__, but we could have left it for init: >>> class Test(tuple): ... def __new__(cls, tup): ... inst = tuple.__new__(cls, tup+('mod from __new__',)) ... return inst ... def __init__(self, *ignore): ... self.x = 5 ... >>> a = Test((1,2)) >>> a.x 5 >>> a (1, 2, 'mod from __new__') __init__ gets called with the same arg as __new__, so you have to allow for it. The *args format is handy, since you can ignore zero or more args without knowing how many are being passed. Otherwise ignore=None would accept and ignore zero or one args. You could call init yourself from __new__ by doing inst.__init__(), but that doesn't eliminate the automatic call after you leave __new__ returning inst, so you'd get two calls, one with no arg and one with the tup arg. (Note that just specifying tup as an arg means exactly one arg must be supplied. E.g., tup=() would give you a default empty tuple. Also, if you wanted more args for __init__, you'd have to allow for them in both arg lists, e.g., >>> class Test(tuple): ... def __new__(cls, tup, *ignore, **ignorekw): ... inst = tuple.__new__(cls, tup+('mod from __new__',)) ... return inst ... def __init__(self, ignoretup, ones=111, two='two', **kw): ... self.x = 5 ... self.ones = ones ... self.two = two ... self.kwargs = kw ... >>> a = Test((3,4),'string ones', 2, keyword='arg', another=123) >>> a (3, 4, 'mod from __new__') >>> a.x 5 >>> a.ones 'string ones' >>> a.two 2 >>> a.kwargs {'another': 123, 'keyword': 'arg'} Of course, you could have used the extra parameters to do something in place of the ('mod from __new__',) nonsense ;-) Hm, ... I'm not sure I like not having control of the call to __init__ even when I've defined __new__. What is the right way to do that? Regards, Bengt Richter From danperl at rogers.com Wed Oct 27 15:23:35 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 27 Oct 2004 15:23:35 -0400 Subject: Open Source License Question References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <97-dnSRAYPEwPuLcRVn-rA@rogers.com> Message-ID: Following a link in the article that I was pointing to, I found yet another interesting article. See especially the "Choosing a License" section in http://www.oreilly.com/catalog/opensources/book/perens.html. I didn't know about the X license before, but it sounds intriguing. Michael, you may be interested in that or in LGPL. Dan "Dan Perl" wrote in message news:97-dnSRAYPEwPuLcRVn-rA at rogers.com... > Michael, I have one comment in-line (see below), but other than that I can > only say that I chose GPL for my own project. It may discourage use of my > code for commercial purposes but it might even be pretentious to expect > that something like that would ever happen. On the other hand, I was more > interested in the advantages of open-source and I wanted to enforce that > as much as possible. I did some research of my own at the time (recently, > actually) but I didn't go much into details and I didn't study other > licenses in detail either, but I chose GPL in large part because it is the > most widely used. > > I tried to find some of the web pages that I read when I was doing my > research but I couldn't. However, I stumbled upon an article that I > didn't see before and that is very much in line with my thoughts. Here's > a link: http://www.dwheeler.com/essays/gpl-compatible.html. > > Hope this helps, > > Dan > > "Michael Foord" wrote in message > news:6f402501.0410270331.6f0d5fd6 at posting.google.com... >> I'd like to formalise slightly the license I release my projects >> under. At the moment it's 'free to use, modify, distribute and >> relicense'. This is basically fine as I don't want t oprevent people >> using my work in commercial settings - but I would like to retain the >> right to be identified as the author. I'd also like to prevent people >> selling derivative works where my stuff forms the substantial part of >> the poduct. > > Michael, I think it's going to be hard to get what you want. I don't see > how you can give a lot of freedom ("I don't want to prevent people using > my work in commercial settings") and, at the same time, achieve something > like "to prevent people selling derivative works where my stuff forms the > substantial part of the poduct". I'm no lawyer, but I don't think you can > define in a license what is a "substantial part of the product". > >> I'd prefer to use an OSI approved license - but it's not essential. >> I've been browsing through them and I can't quite see any that >> *exactly* fits the bill. Before I draft my own I wondered if anyone >> had a reccomendation. >> >> I don't need to require people to make a list of amendments if they >> change things. This puts the Python license out. I also don't mind >> people relicensing derivative works - a simple thanks in the >> documentation and a link to the homepage is my basic requirement. >> >> >> Regards, >> >> Fuzzy >> http://www.voidspace.org.uk/atlantibots/pythonutils.html > > From brian at sweetapp.com Wed Oct 13 09:32:45 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 13 Oct 2004 15:32:45 +0200 Subject: [ANN] Boo 0.4.3 - python-like language for .NET/Mono In-Reply-To: <8-ydnZX55r3oYffcRVn-vw@giganews.com> References: <8PGdnS7wN_uwg_rcRVn-qw@comcast.com> <8-ydnZX55r3oYffcRVn-vw@giganews.com> Message-ID: <416D2E7D.5060808@sweetapp.com> Istvan Albert wrote: > [benchmark snipped] > This does not appear to indicate that boo is any faster > than python... Correct. Indeed, your benchmark, which is the most sloppily constructed that I've ever soon, doesn't indicate much at all. Cheers, Brian From khatwin at ratbaggames.com Thu Oct 28 21:47:05 2004 From: khatwin at ratbaggames.com (Kim Hawtin) Date: Fri, 29 Oct 2004 11:17:05 +0930 Subject: P2P framework In-Reply-To: <4180f21f$0$43632$ed2e19e4@ptn-nntp-reader04.plus.net> References: <4180f21f$0$43632$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <4181A119.9050009@ratbaggames.com> Boria Feigin wrote: > Hi All, > > I am looking for a networking (p2p, if you like) framework with Python > bindings. Requirements are very basic - a node should be able to: > o join/leave the network (perhaps with some auth. mechanism, but not > essential at this stage) > o broadcast a message to other nodes > o communicate with another node on the network > > Basically, something like Sun's JXTA (www.jxta.org) would be more than > sufficient. They do have a Python bindings project (jxtapy.jxta.org) but > that seems dead and I'd rather avoid using Jython for the time being. > > All and any advice appreciated. hi, have a look at circle. might be appropriate. cheers, kim From jeff at ccvcorp.com Fri Oct 15 16:07:12 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 15 Oct 2004 13:07:12 -0700 Subject: how to re-import changed code? In-Reply-To: References: Message-ID: <10n0banri5f2bda@corp.supernews.com> Wolfgang.Stoecher at profactor.at wrote: >Hi, > >another beginner's question: >when I import a module, change the corresponding textfile and try to >import the same module again, it looks like the internal code does not >change (the source-line in an error-message is up to date, however!). Also >del module before import and deleting the .pyc file do not help! How to >realize a fast edit-try-cycle? (btw: I am using python 2.2 under windows) > > What you're looking for is the reload() function. Normally, an imported module is cached by the interpreter, and subsequent imports go straight to the cache without checking whether the file has changed or not. If you reload(), that specifically clears the cache and imports from the (current) disk file again. Jeff Shannon Technician/Programmer Credit International From liquid at kuht.it Mon Oct 18 14:22:43 2004 From: liquid at kuht.it (GMTaglia) Date: Mon, 18 Oct 2004 18:22:43 GMT Subject: optparse examples References: <_Uxcd.50307$b5.2548305@news3.tin.it> Message-ID: Hameed U. Khan wrote: > Hi, > below is the link to programme i made 6 months ago when i started > using linux and found no visual type of display of memory in text > mode. this programme displays number and a bar showing the memory > usage. i have used optparse in it may be it will help you. > the file is zipped becuase geocities dont allow .py files ;). and i > have no webspace some where else. > http://geocities.com/hameedkhaan/meminfo.zip Thanks for this recipe Hameed, I will use it to learn more :) cheers GMTaglia From virge at jakarta.wasantara.net.id Fri Oct 8 10:30:46 2004 From: virge at jakarta.wasantara.net.id (Virge) Date: 8 Oct 2004 14:30:46 -0000 Subject: [VIRGE] VIRUS NOTIFICATION Message-ID: <20041008143046.24967.qmail@jakarta.wasantara.net.id> ################# VIRUS NOTIFICATION ################# A message you sent to helmets at jakarta.wasantara.net.id contains a virus or a worm, and was not delivered. -- DATE : Fri, 8 Oct 2004 11:33:58 +0900 SUBJECT : Re: Message VIRUS : WORM_NETSKY.P -- It is possible your computer is infected without your knowledge. Please download a current virus scanner and check your computer. Thank you. ###################################################### . From aleaxit at yahoo.com Wed Oct 13 07:52:53 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 13 Oct 2004 13:52:53 +0200 Subject: Overloading operators on the rigth. References: <416BD8E7.9885FEBD@pasdepourriels.edf.fr> <1gljwcn.hu8qmfo9di8hN%aleaxit@yahoo.com> <416c7e11.110043444@news.oz.net> <1gllabm.igadlt1xcmxgqN%aleaxit@yahoo.com> <416cfd61.142635999@news.oz.net> Message-ID: <1gllixl.soifpo1xg2cdvN%aleaxit@yahoo.com> Bengt Richter wrote: > On Wed, 13 Oct 2004 10:18:28 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: > > >Bengt Richter wrote: > > ... > >> >>>> class foo: > >> >... def __getattr__(self, name): > > ... > >> On my system, (NT4, python 2.3.2) what really happens for newstyle classes > >> isn't apparent from that experiment: > > > >Heh, of course not -- the main difference between old-style and > >new-style classes is that, for the latter, implicit lookup of special > >methods when needed for operations starts with the *class*, not with the > Well, it always starts with the class if there's no attribute on the instance, I find this a strange meaning for the word "start". To ensure the instance doesn't have the attribute, that's where (conceptually) one could say the lookup "starts", I think. > but the key is whether the "implicit lookup" for methods needed for > operations uses an overridable __getattribute__ somewhere, or just chases > down the bases chain looking for the actual __gt__ or whatever, not > allowing a hook to synthesize a result. Actually, it reaches right into the appropriate slot of the type structure. The slots are generated or changed when the type (i.e., the class object) is generated or changed. So, it may be improper on my part to call this procedure a 'lookup'. > >I just used an old-style class because, that way, I could show the > >lookups happening without having to code a custom metaclass. The > Could you show such a metaclass? I have tried a few things and not > succeeded. It almost makes me think there is no place to hook the internal > __getattribute__ that looks for the methods for code generated from 12 and the like. I'd be interested in seeing it. I think I'd basically have to repeat what types.ClassType is doing -- essentially, prefill all slots with functions that _do_ perform the lookups. To be honest, I haven't tried to see if that strategy hits any snags, I just don't think it would. > >special names being looked for are just the same, whether for classic or > ^^^^^^^^^^^^^^ > but maybe not the same order, see below > >newstyle classes, anyway -- all that changes is _where_ they're looked > >up (starting on the instance, vs starting on the class). You're right -- coercion is "fading" so it's now attempted _after_ 3-way comparison rather than before; so the 'where' isn't quite _all_ that's changed (I had never coded nor seen a classic class which depended on coercion for its comparisons, which may explain though not excuse my imprecision). > NBD, but perhaps the order change is a version difference? Yep, it's part of coercion slowly going away. > Not that the OP was asking any of this ;-) No, but they may still be meaningful in some cases, of course. Alex From alanmk at hotmail.com Mon Oct 11 11:34:57 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 11 Oct 2004 16:34:57 +0100 Subject: Python to Python communication In-Reply-To: References: Message-ID: [Harald Massa] >>I have a group of Python programms which I want to teach to "talk to each >>other". [Thomas Guettler] > Peer to peer: There is no central server. All can talk to each other. > The problem is: How to find the other? If there are on one computer > this is easy: Just write files to a directory all processes know. > But if you want to talk to other computers, you need to know their > IP addresses. Or use a peer-to-peer library that has solved all of those problems already http://www.python.org/other/spread/ regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From adalke at mindspring.com Wed Oct 20 23:02:54 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 21 Oct 2004 03:02:54 GMT Subject: Is there a "Large Scale Python Software Design" ? In-Reply-To: <2tomkhF22ksv0U2@uni-berlin.de> References: <7n78n09cv11bedrvsnjfb6aa0jk981s4dq@4ax.com> <1098143368.985682.72000@z14g2000cwz.googlegroups.com> <1098194866.552318.234710@f14g2000cwb.googlegroups.com> <1glxbjm.3z1g3hhxomoxN%aleaxit@yahoo.com> <0lndd.1925$KJ6.830@newsread1.news.pas.earthlink.net> <2tomkhF22ksv0U2@uni-berlin.de> Message-ID: Greg Ewing wrote: > Indeed. It would be nice to have access to a time machine > so one could go back and ask oneself about things like > this... As in James P. Hogan's book "Thrice Upon a Time". Also notable for having no antagonist and for being the only story I know of that uses quantum time as the way to resolve time travel paradoxes. Andrew dalke at dalkescientific.com From steve at holdenweb.com Mon Oct 25 18:38:39 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Oct 2004 18:38:39 -0400 Subject: Paid Research Project on Stackless 3.1 In-Reply-To: <468v42-c23.ln1@nb2.stroeder.com> References: <468v42-c23.ln1@nb2.stroeder.com> Message-ID: Michael Str?der wrote: > Christian Tismer wrote: [Offer of paid work] > > I'm not sure about the exact daily rates for programmers in Berlin but I > would not expect many responses from really skilled people for taking > over a commercial project for such a low payment and additionally taking > the risk that there's no payment at all. > Others have responded adequately to your other points, but I'd like to mention that I think Christian's standing in the Python community is such that he's be extremely unlikely to jeopardise it for what is a fairly trifling amopunt of money. I hope we'll have the honor of seeing Chris at the next PyCon, my last as chairman. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From pcslen at comcast.net Thu Oct 7 01:19:47 2004 From: pcslen at comcast.net (Len Sumnler) Date: Thu, 07 Oct 2004 05:19:47 GMT Subject: 2 Newbie questions. Message-ID: Hi All I am running SuSe Linux ver. 9.0. I have written the famous "Hello World" program and want to run it as an executable. I have searched the net and performed chmod +x mypython.py and added as the first line of my program #!/usr/bin/env python. When I try to run the program as follows $ mypython.py I get the error message of, "bash: mypython.py: command not found". What am i doing wrong. Second, I am looking for a good online tutorial for some one who knows other programming languages assembler, cobol, etc any suggestions. Thanks Len Sumnler, Jr From alanmk at hotmail.com Sat Oct 9 11:19:48 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 09 Oct 2004 16:19:48 +0100 Subject: module name not recognized In-Reply-To: References: Message-ID: [Darren Dale] >>>I have built two basic modules using distutils. One of them >>> installs fine, but the other, I can't import modules from it. >>> I've been pouring over the code and I cant find the problem. [Larry Bates] >>Two things to check: >> >>Does the package have the required __init__.py file? >>Is the directory where it is installed on the PYTHONPATH? [Darren Dale] > I checked both before writing the original post, this isnt the > problem. One more thing to check: have you named your module with an identical name to an existing module that is before your module the path, e.g. calling your module "xml" or "email", which clash with standard library modules. This is a frequent cause of hair-pulling inexplicable behaviour. If that isn't the problem either, then you're probably best off posting more details, i.e. what are your modules called, where are they located, what doesn't work/what exceptions are raised, etc. regards, alan. From jbellis at gmail.com Tue Oct 19 10:07:46 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 19 Oct 2004 07:07:46 -0700 Subject: Is there a "Large Scale Python Software Design" ? In-Reply-To: References: <7n78n09cv11bedrvsnjfb6aa0jk981s4dq@4ax.com> <1098143368.985682.72000@z14g2000cwz.googlegroups.com> Message-ID: <1098194866.552318.234710@f14g2000cwb.googlegroups.com> Josiah Carlson wrote: > Jonathan Ellis wrote: > > Wouldn't it have been better to ask these questions BEFORE proposing > > python as (presumably) a Great Solution? IMO, as great as python is, > > it isn't appropriate for projects that are large and include many > > developers. > > Having recently released a piece of software with 10k lines of Python > running in its backend as a core technology, and being paid for it, I > will say that Python was and is the best tool for the job. A C version > would have been at least 4-10 times as many lines, and we wouldn't be > releasing ~3 months after starting with nearly the confidence we are now. Heh. "Large" depends on a lot of things, particularly connectedness, but I really can't picture 10k being large under any circumstances. -Jonathan From rkern at ucsd.edu Thu Oct 28 18:09:49 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 28 Oct 2004 15:09:49 -0700 Subject: Constructor problem In-Reply-To: <418169ec$1_1@alt.athenanews.com> References: <418169ec$1_1@alt.athenanews.com> Message-ID: Nick wrote: > class Deck2: > def __init__(self): > self.deck = 52 * [Card()] Here you are creating a single Card instance and putting the same object into a list 52 times. Each slot in the list points to the same object. Another lesson to take away from this: Don't optimize prematurely. The simplest implementation should be fine unless proven otherwise via profiling. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From indigo at bitglue.com Wed Oct 6 08:20:23 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 6 Oct 2004 08:20:23 -0400 Subject: Java to Python byte code In-Reply-To: References: Message-ID: <20041006122023.GC5130@unununium.org> I know of no such tool. Furthermore, I doubt it would be faster. The Java VM is many times faster than Python for most things. Perhaps a better solution would be to compile your Java with gcj and then interface to that with Pyrex. On Wed, Oct 06, 2004 at 03:08:52PM +0530, Kiran Kumar wrote: > Hello All, > > I am just curious to know if there is any tool which would let me > cross compile java source code to python byte codes directly. > > I have developed a library [in Java ] for statistcs and machine > learning. Some of them are computationally demanding. My > line of thinking is , if I could get to compile java source to > python byte code , it would be more faster than interfacing > with Jython. > > Any comments would be helpful > > Thanks, > > Kiran Kumar From aleaxit at yahoo.com Tue Oct 5 05:08:36 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 5 Oct 2004 11:08:36 +0200 Subject: shelve: choice of database package References: Message-ID: <1gl6k92.1k9bkqw1a1khhoN%aleaxit@yahoo.com> Ajay wrote: > hi! > > i am using shelve in a piece of code i have. The code originally used > 'bsddb' but the Berkeley DB library isn't present on my platform (WinCE). > It says in the library reference that "The choice of which database package > will be used (such as dbm, gdbm or bsddb) depends on which interface is > available". > now i can say its not using bsddb (since its not present). Is there a way > of telling which package it is using? See the whichdbm module in the standard library. Alex From jcarlson at uci.edu Wed Oct 13 22:40:20 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 13 Oct 2004 19:40:20 -0700 Subject: what exception is it? In-Reply-To: <416de2f8$1@news.unimelb.edu.au> References: <416de2f8$1@news.unimelb.edu.au> Message-ID: <20041013193918.094A.JCARLSON@uci.edu> > try: > [do something] > except IOError: [IO error handling] > except TypeError: [Type error handling] > except: [other error handling] > > in [other error handling], one of the things I need to do is to display > to the use the kind of exception raised and the message, if any. > > How can I do this without a big if statement to go through the list of > exceptions? import traceback try: #stuff #other except statements except: traceback.print_exc() - Josiah From python-url at phaseit.net Mon Oct 11 13:45:07 2004 From: python-url at phaseit.net (Ville Vainio) Date: Mon, 11 Oct 2004 17:45:07 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Oct 11) Message-ID: QOTW: "As revealed by PSU Research Paper 'UU788', the real reason is a side effect of the nanovirus encroaching into non-whitespace, as first proposed by 'UU355' and then earlier proven (twice, as it turned out) by 'UU6 9'. The only defence is t*^$Z:%Z* NO CARRIER" - Richie Hindle. He appears to have survived the... unfortunate incident. "What do I have to say to get into the QOTW?" - Dan Python, who finally realized that Dan Perl is not going to cut it as a name. Johannes Eble is looking for software te help replace Matlab with Python. Respondents recommend the combination of SciPy and IPython. http://groups.google.com/groups?threadm=uhu1m0t4euvekl61ilengepdhuettvmutr%404ax.com Irmen de Jong is looking for a way to make an object temporarily read-only. Alex Martelli comes up with a clever, obvious-when-you-have-seen-it approach of changing the class of the live object. http://groups.google.com/groups?selm=1gl6bdp.rudxqrkoby1zN%25aleaxit%40yahoo.com Global interpreter lock of CPython and multi-CPU scalability are a recurrent theme in comp.lang.python. The current concern involves the upcoming availability and popularity of multicore CPUs. http://groups.google.com/groups?threadm=6db3f637.0410042045.2171ad5f40posting.google.com PySQLite, the python interface to the SQLite embedded relational database, hits 1.0. http://groups.google.com/groups?selm=mailman.4368.1097005231.5135.python-list%40python.org Carlos Ribeiro provides Erik Johnson a simple explanation of the mechanics behind class and function definitions - a simple matter that confuses many, especially people who think Python has such things as 'declarations'. http://groups.google.com/groups?selm=mailman.4460.1097104255.5135.python-list%40python.org Alex Martelli shows how we should use the plain objects returned by object() as sentinels. http://groups.google.com/groups?threadm=1glatop.p9hsopf3b9m4N%25aleaxit%40yahoo.com Robin Becker needs to determine whether an object is a sequence. http://groups.google.com/groups?threadm=41650CAE.704%40chamonix.reportlab.co.uk Boo 0.4.3, the Python-like language for .NET/Mono CLR, is out. http://groups.google.com/groups?selm=8PGdnS7wN_uwg_rcRVn-qw%40comcast.com ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From justinstraube at charter.net Wed Oct 13 23:17:12 2004 From: justinstraube at charter.net (justin) Date: Wed, 13 Oct 2004 20:17:12 -0700 Subject: Tkinter Dialog boxes References: Message-ID: On Wed, 13 Oct 2004 20:06:31 -0700, justin wrote: >I am looking for one that will allow me to select a directory rather >than a file. Any suggestions what I can try? Ok, I just found what I was looking for, tkFileDialog.askdirectory(). justin From newsgroups at jhrothjr.com Thu Oct 21 21:01:11 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 21 Oct 2004 20:01:11 -0500 Subject: Method Underscores? References: <9dIdd.3712$EL5.3057@trndny09> Message-ID: <10ngmuq11n9qn97@news.supernews.com> "Chris S." wrote in message news:9dIdd.3712$EL5.3057 at trndny09... > Is there a purpose for using trailing and leading double underscores for > built-in method names? My impression was that underscores are supposed to > imply some sort of pseudo-privatization, but would using myclass.len() > instead of myclass.__len__() really cause Python considerable harm? As > much as I adore Python, I have to admit, I find this to be one of the > language's most "unPythonic" features and a key arguing point against > Python. I've searched for a discussion on this topic in the groups > archives, but found little. What are everyone's thoughts on this subject? Languages that make everything methods tend to have two characteristics in common: a single base class, and no facility for procedural programming. Python does not have a single base class, and one of its strong points is that it's a multi-paradigm language. You can use it for procedural programming without having to put everything in the object paradigm. People quite frequently do this for scripts. In single base class languages, the top object in the hierarchy is a hod-podge of methods that have no relationship other than the language designer's decision that the function is fundamental enough that it needs to be available to every object, whether it needs it or not. It would be technically possible (and relatively easy for anyone with a bit of experience with working on Python's internals) to add, for example, .len() to the object class. Would this break anything? Unlikely in most cases (there is one edge case I know of where it would). Alex Martelli's comment elsewhere in this thread assumes one would also remove it from the builtins, which would of course break everything in sight. Removing it from the builtins is equivalent to eliminating the multi-paradigm nature of Python: you could no longer do effective procedural programming without the builtins! This is simply not going to happen: it would be a completely different language. Discussing it is futile. Also, the new .len() method would only be available to new style classes written in Python, and then only if the author of some subclass had not decided to implement their own len() method with different semantics. The first of these two objections goes away in Python 3.0, where old style classes are eliminated. The second, however, is a difficulty that all "pure" OO languages need to deal with, and there is no real good way of handling it (meaning obvious, works all the time everywhere, and upward compatible without breaking anything.). Having a parallel structure where a large number of builtins are also implemented as methods on object violates Python's basic philosophy in at least two ways: there should only be one (obvious) way to do something, and things should work the same way everywhere. All that said, I'd like to see some of the builtins as methods on object, but since it's not going to happen, it's not worth worrying about. John Roth From francisl at aei.ca Mon Oct 4 19:10:57 2004 From: francisl at aei.ca (Francis Lavoie) Date: Mon, 04 Oct 2004 19:10:57 -0400 Subject: mp3/ogg player Message-ID: <4161D881.5080606@aei.ca> Hi I looking to build a second program in python. I would like to code a music player, which can play mp3 an ogg files. But every solution that I find, seem over complicated or not multiplaform. Is there a simple package of libraries that we only have to install once, or plug it into the program that give mp3 and ogg playability like a .jar file in java? My main developpement OS is windows for now. Thank you From adalke at mindspring.com Sat Oct 9 23:56:13 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 10 Oct 2004 03:56:13 GMT Subject: Init a table of functions In-Reply-To: References: <1097371939.905273@mystique.esoterica.pt> <942ad.836$Bw1.213@newsread3.news.pas.earthlink.net> Message-ID: Richard Blackwood wrote: > Yo Andrew. That doesn't work. Check my previous post w/ errors. What do you mean? Ahh, I see I solved the first problem (can't find 'foo') without solving what the OP wanted. Try this reordering. class foo: def f1(): print "f1" def f2(): print "f2" K={"f1" : f1, "f2" : f2, } f1 = staticmethod(f1) f2 = staticmethod(f2) def main(): foo.K["f1"]() foo.K["f2"]() if __name__ == "__main__": main() The 'staticmethod' is a descriptor and only works in the context of a class. Functions get turned into methods only in the context of a class. So to use a function as a function, get it before it turns into a method or staticmethod. Andrew dalke at dalkescientific.com From jbperez808 at wahoo.com Mon Oct 25 21:59:34 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Tue, 26 Oct 2004 09:59:34 +0800 Subject: Tkinter 3000 / WCK (Re: Integrate Tile into Tkinter) In-Reply-To: <3Gkdd.2134$Ag.1192@fe37.usenetserver.com> References: <3Gkdd.2134$Ag.1192@fe37.usenetserver.com> Message-ID: <2u5oqmF27qhb2U1@uni-berlin.de> Speaking of Tkinter, I noticed that there has been progress with Fredrik Lundh's Tkinter 3000/ Widget Construction Kit project. Specifically, you can now make your own Tkinter widgets from scratch using pure Python. Performance actually seems to be quite good. http://www.effbot.org/zone/wck.htm --- quote from WCK page ---- The Widget Construction Kit (WCK) is an extension API that allows you to implement all sorts of custom widgets, in pure Python. Creating a new widget can be as simple as: from WCK import Widget class HelloWidget(Widget): def ui_handle_repair(self, draw, x0, y0, x1, y1): font = self.ui_font("black", "times") draw.text((0, 0), "hello, world!", font) ----------------------------- Kevin Walzer wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Are there any plans to integrate the Tile extension from Tk into > Tkinter? This theming extension allows native look and feel under > Windows XP and OS X, in particular, and adds a lot of theming > flexibility to Tk apps. In fact, it would bring Tkinter pretty much in > line with wxPython in terms of a native "look" on various platforms, > though wx still has a larger set of core widgets. I've seen only a > little discusison about Tile in Python circles, but it's one of the most > important advances going on with Tcl/Tk these days. Anyway, I'm just > curious, as I have some experience with Tcl/Tk and am learning Python. > > - -- > Kevin Walzer, PhD > WordTech Software--Open Source Applications and Packages for OS X > http://www.wordtech-software.com > http://www.smallbizmac.com > http://www.kevin-walzer.com > mailto:sw at wordtech-software.com > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (Darwin) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFBddb9JmdQs+6YVcoRAgdKAJ4v99f7qGXHEaoFTS249cvFNIXArwCdFki+ > f2Io7rRlF6IHbPsVTHAQAzY= > =s+ao > -----END PGP SIGNATURE----- > From tweedgeezer at hotmail.com Sat Oct 30 03:56:09 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 30 Oct 2004 00:56:09 -0700 Subject: int/long unification hides bugs References: <940ee3e8.0410250456.65445bbd@posting.google.com> <698f09f8.0410280709.760948ea@posting.google.com> Message-ID: <698f09f8.0410292356.df11f6a@posting.google.com> Josiah Carlson wrote in message news:... > And as others have said more than once, it is not so common that the > boundedness of one's integers falls on the 32 bit signed integer > boundary. Ages and money were given as examples. I'm not quite sure how this is relevant. My issue is with the unboundedness of computations, not the unboundedness of the numbers themselves. > And what is so wrong with implementing all of integer arithmetic in > Python? It's a whole lot of extra effort when a perfectly viable such "battery" existed in previous versions of Python. Jeremy From grante at visi.com Tue Oct 5 11:08:39 2004 From: grante at visi.com (Grant Edwards) Date: 05 Oct 2004 15:08:39 GMT Subject: New to Python: Features References: <416210AF.5060908@cloudthunder.com> <1gl6dqy.17aec2n1uecu0nN%aleaxit@yahoo.com> Message-ID: <4162b8f7$0$59523$a1866201@newsreader.visi.com> On 2004-10-05, Richard Blackwood wrote: > No, the tutorial does not and no, this is not a *school* assignment. > Grief, like I said, I haven't been in school since 1976. Plus, how many > schools (I assume you mean like a university or something) teach Python? Actually, several that I've heard of. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Fri Oct 29 07:35:50 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Fri, 29 Oct 2004 13:35:50 +0200 Subject: Tkinter and utf-8 References: <4181cc21$0$3620$8fcfb975@news.wanadoo.fr> Message-ID: <41822b37$0$31198$8fcfb975@news.wanadoo.fr> Hi ! >>> Mandrake newbie What is Mandrake ? The magician ? A comic personn ? I am not in love with Linux... ;o) Michel Claveau From zathras at thwackety.com Thu Oct 7 18:23:58 2004 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 07 Oct 2004 23:23:58 +0100 Subject: Tracking Users By IP Address References: Message-ID: <4165ad9a$0$44853$ed2619ec@ptn-nntp-reader02.plus.net> Fuzzyman wrote: ... > Assuming that each visitor will have a unique IP address is probably > not 100% accurate but will have a reasonably low margin of error !! Is > there any reason not to use this approach ? For this task things are worse than it sounds: * Many users are behind either firewalls and/or proxies * In the case of a simple NATting firewall all your accesses from offices will be from a single IP (or small set of IPs). * In the case of proxies that set either Client-IP or X-Forwarded-For headers you can't guarantee that the IPs are passed through intact (depending on the paranoia/privacy settings of the proxy) * Even if you *can* see the IP, many people connect from systems where their IP changes regularly - meaning you break your request streams so you don't get the full behaviour over time and means that people overlap. * Many ISPs that generate large amounts of traffic proxy all their traffic. Meaning you have millions of users from tens or hundreds of IPs. * The "My TiVO thinks I'm Gay" effect. PVRs often have settings to say "I like", "I hate", which allows the PVR to determine the tastes of the owner. In theory this sounds great, but because it assumes everyone in the same household likes the same thing it jumps to the wrong conclusions. If you consider homes with several people, you can't even rely on accesses from the same _machine_ to come from the same user. (If they share the same login there's nothing you can do obviously) etc... When you put all these togethrer using IPs _looks_ very bad. What's an alternative? First a few points: * Well, you want to track users. This means by EU regs (based on your email this might apply) you have to let users of your site know you're doing this. * Cookies can get by alot of the issues listed above * You're only really interested in people who can reliably send you the same cookie twice. (If they refuse cookies, you can't track them using cookies obviously, and the above implies IP won't work brilliantly for you) * Relying on cookies also means you can allow your users to opt out from being tracked. One alternative: (pseudocode) Recieve request If no-cookie-received: Set Cookie: "NEWUSER" else: if cookie-recieved == "NEWUSER": # We know they can send us cookies back id = gen-id() Set Cookie: id Then just log requests with the recieved cookie, trackable users will have a unique id, whether their IP changes, share a system, behind nat'ing firewalls etc. This allows you to track unique users that are trackable using cookies. If you have a particularly large number of users accessing your site you can tie in sampling (perhaps something like density biased sampling) in there as well something like this: new-cookie = None If no-cookie-received: new-cookie = "NEWUSER" else: if cookie-recieved == "NEWUSER": # We know they can send us cookies back id = gen-id() new-cookie = id if add-to-sample-set(request): tag = "SAMPLE" new-cookie = current-cookie or new-cookie else: tag = "NOSAMPLE" if new-cookie: Set Cookie: tag new-cookie (Or something like that IYSWIM - ie get the user population to indicate if they're being sampled - again, this allows your users to easily opt out, and also means the memory/etc required to determine whether to track the user or not isn't dependent on the number of requests your site gets - meaning that you can keep analysis costs for your site under control. If you've only got a small site this probably doesn't matter to you, but worth bearing in mind). The interesting thing about this from my perspective is that if you do take a cookie approach like this, it actually allows you to figure out how much error there actually is between IP and cookie - rather than just guess. The other nicety is it allows your users to opt-out very easily - since they can either switch off cookies, or you can send them a "NOSAMPLE" cookie. Also, at present comments in this thread revolve around "this isn't reliable because of x,y and z". If you take this sort of approach you can find out the margin of error and then decide whether you're happy with it or not. Also as you can see from above this doesn't really have to be a very complex operation (unless you're in a high volume scenario with lots of distinct users and need to add in the sampling aspect). Best Regards, Michael From steven.bethard at gmail.com Tue Oct 12 19:44:51 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Oct 2004 23:44:51 +0000 (UTC) Subject: list comprehension for splitting strings into pairs References: <2t344cF1qetlbU1@uni-berlin.de> Message-ID: Russell Blau hotmail.com> writes: > >>> lst = ['1', '1:2', '3', '-1:4'] > >>> splits = [':' in item and item.split(':', 1) or [item, None] > for item in lst] > >>> splits > [['1', None], ['1', '2'], ['3', None], ['-1', '4']] Oooh. Pretty. =) What if I want to convert my splits list to: [[1, None], [1, 2], [3, None], [-1, 4]] where I actually call int on each of the non-None items? Obviously I could extend your example to: >>> lst = ['1', '1:2', '3', '-1:4'] >>> splits = [':' in item and [int(x) for x in item.split(':', 1)] ... or [int(item), None] ... for item in lst] >>> splits [[1, None], [1, 2], [3, None], [-1, 4]] But that's getting to be a bit more work than looks good to me in a list comprehension. I thought about doing it in two steps: >>> splits = [':' in item and item.split(':', 1) or [item, None] ... for item in lst] >>> splits = [[int(i), p is not None and int(p) or p] ... for i, p in splits] >>> splits [[1, None], [1, 2], [3, None], [-1, 4]] This looks decent to me, but if you see a better way, I'd love to hear about it. =) Thanks again! Steve From fredrik at pythonware.com Wed Oct 13 16:37:41 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Oct 2004 22:37:41 +0200 Subject: [ANN] Boo 0.4.3 - python-like language for .NET/Mono References: <20041010175617.0897.JCARLSON@uci.edu> Message-ID: Josiah Carlson wrote: > There was also a similar thing with Prothon (Python with prototypes) by > Mark Hahn a while back, that actually used this newsgroup/mailing list > as their discussion forum. so we can expect Boo to turn into BoC to turn into Sproo, "better than everything else, more dynamic than everything else, faster than everything else, more syntaxes than everything, now will someone implement this for me, please" within a couple of months? cool. From mcherm at mcherm.com Sun Oct 17 18:13:01 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Sun, 17 Oct 2004 15:13:01 -0700 Subject: ConfigParser shootout, preliminary entry Message-ID: <1098051181.4172ee6dea6f5@mcherm.com> A few weeks ago, the suggestion was made on Python-Dev that it might be time to consider replacing the ConfigParser module and that we should hold a "shootout" (ie ask for implementations and see what we get). Since then I've been playing around with this... not the parsing part (which so far I have completely ignored) but the programmer interface. There needs to be a well-thought-out data model for the information stored, and the user interface needs to be very easy to use, yet not so "magical" that it becomes difficult to understand. I have put together what I think is probably my best proposal. It is based on a superset of ini config files and java .property files. There is a convenient access mechanism ("config.my_app.some_value") as well as more general approaches ("config.values['my_app.serviceByPort.80']"). I have tried to consider issues like unicode (I permit fairly lenient mixing of unicode and str), and unit testing ("... call config.clear_all() in the tearDown() method of any unittests that use the config module..."). I have even considered carefully what to leave OUT (converting to non-string data types, interpolating values, things like that). I think that I am now at the point where I could really use some input from others. So I'd like to invite people to review my design and send me your suggestions. I'm not expecting this as a *useful* module yet (it doesn't yet parse files!), but it seemed like a good stage at which to ask for feedback. I'm attaching two files, config.py and configTest.py, and they are also available from these urls: http://www.mcherm.com/publish/2004-10-17/config.py http://www.mcherm.com/publish/2004-10-17/configTest.py Thanks in advance for reviewing this. -- Michael Chermside From jepler at unpythonic.net Sat Oct 16 18:54:42 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 16 Oct 2004 17:54:42 -0500 Subject: viewing pydoc output in FireFox In-Reply-To: References: Message-ID: <20041016225440.GA2588@unpythonic.net> Please see https://bugzilla.mozilla.org/show_bug.cgi?id=153448 https://bugzilla.mozilla.org/show_bug.cgi?id=84128 Apparently you can use about:config to change security.checkloaduri to false to "fix" the behavior. Perhaps pydoc should serve up source files as well as documentation, since this behavior by design in firefox makes those links break. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From danperl at rogers.com Wed Oct 27 09:33:19 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 27 Oct 2004 09:33:19 -0400 Subject: Open Source License Question References: <6f402501.0410270331.6f0d5fd6@posting.google.com> Message-ID: <97-dnSRAYPEwPuLcRVn-rA@rogers.com> Michael, I have one comment in-line (see below), but other than that I can only say that I chose GPL for my own project. It may discourage use of my code for commercial purposes but it might even be pretentious to expect that something like that would ever happen. On the other hand, I was more interested in the advantages of open-source and I wanted to enforce that as much as possible. I did some research of my own at the time (recently, actually) but I didn't go much into details and I didn't study other licenses in detail either, but I chose GPL in large part because it is the most widely used. I tried to find some of the web pages that I read when I was doing my research but I couldn't. However, I stumbled upon an article that I didn't see before and that is very much in line with my thoughts. Here's a link: http://www.dwheeler.com/essays/gpl-compatible.html. Hope this helps, Dan "Michael Foord" wrote in message news:6f402501.0410270331.6f0d5fd6 at posting.google.com... > I'd like to formalise slightly the license I release my projects > under. At the moment it's 'free to use, modify, distribute and > relicense'. This is basically fine as I don't want t oprevent people > using my work in commercial settings - but I would like to retain the > right to be identified as the author. I'd also like to prevent people > selling derivative works where my stuff forms the substantial part of > the poduct. Michael, I think it's going to be hard to get what you want. I don't see how you can give a lot of freedom ("I don't want to prevent people using my work in commercial settings") and, at the same time, achieve something like "to prevent people selling derivative works where my stuff forms the substantial part of the poduct". I'm no lawyer, but I don't think you can define in a license what is a "substantial part of the product". > I'd prefer to use an OSI approved license - but it's not essential. > I've been browsing through them and I can't quite see any that > *exactly* fits the bill. Before I draft my own I wondered if anyone > had a reccomendation. > > I don't need to require people to make a list of amendments if they > change things. This puts the Python license out. I also don't mind > people relicensing derivative works - a simple thanks in the > documentation and a link to the homepage is my basic requirement. > > > Regards, > > Fuzzy > http://www.voidspace.org.uk/atlantibots/pythonutils.html From david.bear at asu.edu Thu Oct 21 19:08:41 2004 From: david.bear at asu.edu (David Bear) Date: Thu, 21 Oct 2004 16:08:41 -0700 Subject: confused about stdin Message-ID: This may be a dumb question but I'm confused. using command line syntax pipe like this: cat somefile | pyscript In my pyscript I can simply do buffer = sys.stdin.read() to get all of whatever cat sends. However, using syntax like this: pyscript < somefile I'm not sure. Does this send to stdin as well? And.. will it work on both unix and windows? -- David Bear phone: 480-965-8257 fax: 480-965-9189 College of Public Programs/ASU Wilson Hall 232 Tempe, AZ 85287-0803 "Beware the IP portfolio, everyone will be suspect of trespassing" From aleaxit at yahoo.com Tue Oct 12 05:23:19 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 12 Oct 2004 11:23:19 +0200 Subject: Parallelization on muli-CPU hardware? References: <6db3f637.0410042045.2171ad5f@posting.google.com> <6db3f637.0410052100.31bbe86f@posting.google.com> <1glatga.8upk9brifr2qN%aleaxit@yahoo.com> <1glawed.1e83ntp1ck15pvN%aleaxit@yahoo.com> <1glb1jy.1at6as41fab2t9N%aleaxit@yahoo.com> <1glbyrn.4jt08j144wg1dN%aleaxit@yahoo.com> Message-ID: <1gljja1.1nxj82c1a25c1bN%aleaxit@yahoo.com> Nicolas Lehuen wrote: > problem was the same ; people expected mod_python to run in a > multi-process context, not a multi-threaded context (I guess this is > due to a Linux-centered mindset, forgetting about BSD, MacosX or Win32 > OSes). When I asked questions and pointed problem, the answer was 'Duh > - use Linux with the forking MPM, not Windows with the threading MPM'. Sorry, I don't get your point. Sure, Windows makes process creation hideously expensive and has no forking. But all kinds of BSD, including MacOSX, are just great at forking. Why is a preference for multiple processes over threads "forgetting about BSD, MacOSX", or any other flavour of Unix for that matter? > Well, this is not going to take us anywhere, especially with all the > multicore CPUs coming. Again, I don't get it. Why would multicore CPUs be any worse than current multi-CPU machines at multiple processes, and forking? Alex From apardon at forel.vub.ac.be Fri Oct 29 07:22:57 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Oct 2004 11:22:57 GMT Subject: int/long unification hides bugs References: <940ee3e8.0410250456.65445bbd@posting.google.com> <698f09f8.0410280709.760948ea@posting.google.com> Message-ID: Op 2004-10-28, Andrew Dalke schreef : > Jeremy Fincher wrote: >> The problem with int/long unification is that there is no simple >> pure-Python alternative for those of us who need a bounded integer >> type. If our code depended on that raised OverflowError in order to >> ensure that our computations were bounded, we're left high and dry >> with ints and longs unified. We must either drop down to C and write >> a bounded integer type, or we're stuck with code that no longer works. > > What's wrong with the example Number wrapper I posted a couple days > ago to this thread? Here are the essential parts > What I think is wrong with it, is that it distributes its constraineds too far. The fact that you want constraints on a number doesn't imply that all operations done on this number are bound by the same constraints The way I see myself using constrains, would mean I need them on a name, not on an object. -- Antoon Pardon From adalke at mindspring.com Sun Oct 17 06:35:55 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 17 Oct 2004 10:35:55 GMT Subject: beginning index for generators In-Reply-To: References: Message-ID: Peter Otten > No. That's what I would like xrange() to be. Ahh, I had forgotten about that restriction. BTW, this is kinda cute with your code >>> list(irange("A", "AAAAAAAAA", "A")) ['A', 'AA', 'AAA', 'AAAA', 'AAAAA', 'AAAAAA', 'AAAAAAA', 'AAAAAAAA'] >>> >>And that's itertools.islice? > > > No, but it _calls_ itertool.islice() as you may have noted :-) > Its raison d'?tre is that it allows to pass the start, stop, and step > attributes of a slice object without looking into the special cases. Acutally I didn't notice. I was on my way out the door and didn't look that closely. My apologies. Given the worry you had above about the sys.maxint limit, aren't you also concerned about the same limits with itertools.islice? > Yes, unfortunately. Discriminating between dictionaries and lists has been > deliberately left out. Is there a recommended way to do it? Looking for a > 'keys' attribute maybe? No, because there are some data structure which act like both a list and a dictionary. Eg, one where the dictionary keys are strings and the items are stored and accesible via integers into the sort order. Andrew dalke at dalkescientific.com From eric_brunel at despammed.com Thu Oct 28 03:54:12 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 28 Oct 2004 09:54:12 +0200 Subject: how come .insert() don't work In-Reply-To: <4180a179$0$76514$b83b6cc0@news.wanadoo.nl> References: <41801753$0$62043$ee9da40f@news.wanadoo.nl> <41801852$0$189$9b622d9e@news.freenet.de> <41803447$0$41713$1b2cd167@news.wanadoo.nl> <4180a179$0$76514$b83b6cc0@news.wanadoo.nl> Message-ID: <4180a3e5$0$3624$8fcfb975@news.wanadoo.fr> Bennie wrote: > > Hi, > > This is a chunck out of my program: > -------------------------------------------------- > from Tkinter import * > > class App: > def __init__(self, master): > frame = Frame(master) > frame.pack() > > self.menubar = Menu(root) > self.html = Menu(self.menubar, tearoff=0) > self.html.add_command(label="p", command=self.tekst_in('p')) You're using your tekst_in method before setting the attribute self.tekst, so when the method code is executed, there is actully no attribute named tekst; hence the Attribute error. Move the previous line after the self.tekst.pack(...) line and everything should be fine. > # self.html.add_command(label="p", command=self.tekst_a) > self.menubar.add_cascade(label="html", menu=self.html) > > root.config(menu=self.menubar) > > self.tekst = Text() > self.tekst.pack(fill=BOTH, expand=YES) > > def tekst_in(self, tag): > tekst_tag={'p': '\t\t

\n\n\t\t

\n', 'br': '
'} > self.tekst.insert(INSERT, tekst_tag[tag]) > > # This works > #def tekst_a(self): > # self.tekst.insert(INSERT, "

") > > > if __name__ == '__main__': > root = Tk() > app = App(root) > root.mainloop() > > > -------------------------------------------------- > > > The error is: > ------------------------------- > Traceback (most recent call last): > File "test.py", line 30, in ? > app = App(root) > File "test.py", line 10, in __init__ > self.html.add_command(label="p", command=self.tekst_in('p')) > File "test.py", line 21, in tekst_in > self.tekst.insert(INSERT, tekst_tag[tag]) > AttributeError: App instance has no attribute 'tekst' > ------------------------------------------------------ > hope this is enough info. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From carribeiro at gmail.com Mon Oct 18 07:43:05 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 18 Oct 2004 09:43:05 -0200 Subject: Style question on recursive generators Message-ID: <864d370904101804436abfc3cd@mail.gmail.com> Hello all, Here I am using some deeply nested, tree-like data structures. In some situations I need to traverse the tree; the old-style way to do it is to write a recursive method on the node class, as in: def walk(self): """old-style recursive tree traversal""" child.do_something for child in childs: child.walk() Of course, "do_something" can be a configurable method or action on the node, whose actual implementation doesn't matter for this discussion. The recursive solution is clean and readable, and that's why its frequently preferred over the iterative solution, which (a) requires manual housekeeping (using a stack) to work; and (b) is not truly 'object oriented', in the sense that it does not delegate node traversal behavior to the node being traversed. In my last projects I've been tending towards a greater use of generators. However, when a generator is used in the situation described above, the end result does not 'read' as naturally: def walk(self): """generator-based recursive tree traversal""" yield child for child in childs: for node in child.walk() yield node The problem is that I need to 'chain' the yields from the subtrees to yield back the result to the caller. It does not seem to be as elegant as the simple recursive version; it's confusing to read, because one has to figure out what is being yielded in the inner loop, and it's also error-prone -- it's easy to forget to include the 'yield' in the inner loop. I'm now wondering which is better: to keep using old-style recursive tree traversal code, or to chained-yield generator solution. It's more of a stylistic decision -- I'm not concerned about raw performance at this point, but clarity and elegancy of design are more important. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From export at hope.cz Sat Oct 16 06:59:05 2004 From: export at hope.cz (Lad) Date: 16 Oct 2004 03:59:05 -0700 Subject: Poll script in Python Message-ID: <81a41dd.0410160259.4767918f@posting.google.com> Is there a poll script available in Python? From bradtilley at gmail.com Tue Oct 26 13:08:36 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Tue, 26 Oct 2004 13:08:36 -0400 Subject: python, mbox files and forwarding messages Message-ID: Can Python parse a mbox file and forward each individual message within that file to someone else? For example, let's say I have a 10MB mbox file that has 678 messages. I'd like to send each of the messages to santa.claus at northpole.com... how might I do that? Also, how might I handle messages that have an attachment associated with them during the forward process? Thanks, Brad From carribeiro at gmail.com Wed Oct 13 08:15:32 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 13 Oct 2004 09:15:32 -0300 Subject: Order in metaclass In-Reply-To: References: Message-ID: <864d3709041013051545841e8b@mail.gmail.com> On Tue, 12 Oct 2004 15:37:22 -0400, Nicolas Fleury wrote: > In the following example: > > class MyMetaclass(type): pass > class MyBaseType(object): __metaclass__ = MyMetaclass > class MyType(MyBaseType): > x = 4 > y = 5 > z = 6 > > Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere? Well, some people have already pointed to you about a recent discussion on this topic. I was the one who started it all :-) What I have learned is: -- Due to the way the class statement is handled, it's not possible (without really black magic) to guarantee ordering in a transparent way. If you need to put attributes in order, you have either to provide a list with all attributes in order, or use derive your attributes from a base class that provide some ordering mechanism of its own. -- You have to include an extra member into your class to record the order. I have chosen to include a list, named "_fields", with all attribute _names_. Storing the attribute name is guaranteed way to keep the ordering even when a descendant override an attribute, or when the user modify its value. I have written a small package called GenericTemplates, that works all the magic needed. It's the basis for a much more ambitious package for 'declarative-style' data structures using class statements. It handles nested classes also, and keeps the ordering of all attributes that inherit from a AbstractAttribute class (it includes nested classes that inherit from GenericTemplate, and also OrderedAttributes and TypedAttributes). I have a page for it in portuguese only at: http://www.pythonbrasil.com.br/moin.cgi/TemplatesGen%E9ricos The code is as follows -- still with debug code included, and lots of comments: """ metatemplate.py Template class that can be used to write complex data structures using nested classes. Template classes can store other template classes (nested) or user-defined attributes (typed or untyped). The original definition order information is preserved, allowing for true templating use for applications such as html templates, data entry forms, and configuration files. (c) 2004 Carlos Ribeiro carribeiro at gmail.com http:///pythonnotes.blogspot.com """ import sys from inspect import isclass, isdatadescriptor from types import StringType, IntType, FloatType, ListType import itertools #---------------------------------------------------------------------- # Debug constants. I don't intend to remove them, even from production # code, but I intend to use the logging module to print the messages debug_generic_attribute = 0 debug_typed_attribute = 0 debug_auto_instantiation = 0 #---------------------------------------------------------------------- # AbstractAttribute is the ancestor of all classes that can be used # in the metacontainer framework. class AbstractAttribute(object): pass #---------------------------------------------------------------------- # GenericAttribute is the ancestor of all simple elements that are # used as attributes of user defined Container subclasses # # GenericAttributes are simpler than full containers. They're both # derived from the same AbstractAttribute class, but GenericAttributes # have only a single value associated with them. # # When referred from a instance, the __get__ method returns the value # associated with the attribute. If called from the class, the __get__ # method returns the property itself. class GenericAttribute(AbstractAttribute): """ Generic attributes for generic containers """ def __init__(self, default = None): self._seqno = next_attribute_id() self.value = default def __repr__(self): return "" % (self.__class__.__name__) def __get__(self, instance, owner): if debug_generic_attribute: print "GET self:[%s], instance:[%s], owner:[%s]" % \ (self, instance, owner) if instance: attrdict = instance.__dict__.setdefault('__attr__', {}) return attrdict.get(self.name, self.value) else: return owner def __set__(self, instance, value): if debug_generic_attribute: print "SET self:[%s], instance:[%s], value:[%s]" % \ (self, instance, value) attrdict = instance.__dict__.setdefault('__attr__', {}) attrdict[self.name] = value class TypedAttribute(GenericAttribute): """ Typed attributes for generic containers """ def __init__(self, default = None, mytype = None): self._seqno = next_attribute_id() self.value = default if mytype: if isclass(mytype): self.mytype = mytype else: raise TypeError("Argument expects None " "or a valid type/class") else: self.mytype = type(default) def __repr__(self): return "" % \ (self.__class__.__name__, self.mytype.__name__) def __get__(self, instance, owner): if debug_typed_attribute: print "GET self:[%s], instance:[%s], owner:[%s]" % \ (self, instance, owner) if instance: attrdict = instance.__dict__.setdefault('__attr__', {}) return attrdict.get(self.name, self.value) else: return self.value def __set__(self, instance, value): if debug_typed_attribute: print "SET self:[%s], instance:[%s], value:[%s]" % \ (self, instance, value) if not isinstance(value, self.mytype): # if it's a string, tries to convert to the correct # target type (this is needed because most things read # from files will be strings anyway) if isinstance(value, StringType): value = self.mytype(value) else: raise TypeError, "Expected %s attribute" % \ self.mytype.__name__ attrdict = instance.__dict__.setdefault('__attr__', {}) attrdict[self.name] = value #---------------------------------------------------------------------- # auxiliary functions next_attribute_id = itertools.count().next def getfields(dct): """ takes a dictionary of class attributes and returns a decorated list containing all valid field instances and their relative position. """ for fname, fobj in dct.items(): if isinstance(fobj,GenericAttribute): yield (fobj._seqno, (fname, fobj)) elif isclass(fobj) and issubclass(fobj,AbstractAttribute): yield (fobj._seqno, (fname, fobj)) elif (fname[0] != '_'): # conventional attributes from basic types are just stored # as GenericAttributes, and put at the end of the list, # in alphabetical order if (isinstance(fobj,StringType) or isinstance(fobj,IntType) or isinstance(fobj,FloatType) or isinstance(fobj,ListType)): yield (sys.maxint, (fname, GenericAttribute(fobj))) else: yield (0, (fname, fobj)) else: yield (0, (fname, fobj)) def makefieldsdict(dct, bases): # build the field list and sort it fields = list(getfields(dct)) fields.sort() # undecorate the list and build a dict that will be returned later sorted_field_list = [field[1] for field in fields] field_dict = dict(sorted_field_list) # finds all attributes and nested classes that are containers attribute_list = [field for field in sorted_field_list if (isinstance(field[1],AbstractAttribute) or (isclass(field[1]) and issubclass(field[1],AbstractAttribute) ))] # check baseclasses for attributes inherited but not overriden # !!WARNING: this code does not checks correctly for multiple # base classes if there are name clashes between overriden # members. This is not recommended anyway. inherited = [] for baseclass in bases: base_field_list = getattr(baseclass, '_fields', None) # looks for a valid _fields attribute in an ancestor if isinstance(base_field_list, ListType): fnames = [f[0] for f in attribute_list] for fname, fobj in base_field_list: # checks for overriden attributes if (fname in fnames): # overriden - inherited list contains the new value newobj = field_dict[fname] inherited.append((fname, newobj)) # remove attribute and quick check field names list attribute_list.remove((fname, field_dict[fname])) fnames.remove(fname) else: # copy the original entry into the inherited list inherited.append((fname, fobj)) field_dict['_fields'] = inherited + attribute_list return field_dict #---------------------------------------------------------------------- # MetaTemplate metaclass # # Most of the hard work is done outside the class by the auxiliary # functions makefieldsdict() and getfields() class MetaTemplate(type): def __new__(cls, name, bases, dct): # creates the class using only the processed field list newdct = makefieldsdict(dct, bases) newclass = type.__new__(cls, name, bases, newdct) newclass._seqno = next_attribute_id() newclass.name = name return newclass #---------------------------------------------------------------------- # GenericTemplate superclass class GenericTemplate(AbstractAttribute): __metaclass__ = MetaTemplate def __init__(self): """ instantiates all nested classes upon creation """ # builds a copy of the field list. this is needed to allow # customizations of the instance not to be reflected in the # original class field list. self._fields = list(self.__class__._fields) # auto instantiates nested classes and attributes if debug_auto_instantiation: print "AutoInstantiation <%s>: fieldlist = %s" % \ (self.name, self._fields) for fname, fobj in self._fields: if isclass(fobj) and issubclass(fobj,Container): # found a nested class if debug_auto_instantiation: print "AutoInstantiation <%s>: field[%s] is a " "Container Subclass" % (self.name, fname) fobj = fobj() setattr(self, fname, fobj) elif isinstance(fobj, AbstractAttribute): # found an attribute instance if debug_auto_instantiation: print "AutoInstantiation <%s>: field[%s] is an " "Attribute Instance" % (self.name, fname) # removed: parent links are still being thought out, # and I'm not even sure if they're a good idea # setattr(fobj, 'parent', self) setattr(fobj, 'name', fname) else: if debug_auto_instantiation: print "AutoInstantiation <%s>: field[%s] is " "unknown" % (self.name, fname) def iterfields(self): for fname, fobj in self._fields: yield getattr(self, fname) def __repr__(self): return "<%s '%s'>" % (self.__class__.__name__, self.name,) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fumanchu at amor.org Mon Oct 18 20:05:51 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 18 Oct 2004 17:05:51 -0700 Subject: itertools candidate: warehouse() Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3244FD8@exchange.hqamor.amorhq.net> Michael Hoffman wrote: > Robert Brewer wrote: > > > > What do you all think? I've been using a class-based > variant of this in > > production code (business app) for six months now, and have found it > > extremely helpful. I saw a pointer to itertools today and figured a > > function-based version might be nice to include in that > module someday. > > Could you give a real-world example of its use? Sure. Here's a bit of presentation-layer logic from a webapp of mine. The user checks a bunch of checkboxes on an HTML page to show which staff members are working on a project on each day in the given range. An example form: Name 10/12 10/13 10/14 10/15 10/16 Bob [ ] [X] [ ] [X] [ ] Doug [X] [ ] [X] [X] [ ] Wendy [ ] [ ] [ ] [X] [X] In this case, there is already a set of persistent WorkDate objects; when the user edits the form (even just one checkbox), you can: a) destroy all the relevant previous WorkDate objects and make a new set, b) make horribly long control names using each object's ID (including the blank ones!), c) reuse the existing objects and rewrite the date and worker for each one Reuse is nice, but means you probably have to create new WorkDate objects when you run out, and go through a formal destroy procedure if you don't reuse them all. The warehouse function helps that out by keeping track of the iteration (and on-the-fly object creation) for you: parms = UI.requestParams for worker in job.Worker(): avail, rem = dejavu.warehouse(worker.dates(), WorkDate) for day in days: control_name = u'%s:%s' % (worker.ID, day.strftime('%m/%d/%Y')) if parms.has_key(control_name): # The appropriate checkbox was turned ON. # Reuse an existing WorkDate (or make a new one). wd = avail.next() wd.WorkerID = worker.ID wd.Date = day if not wd.sandbox: # The object is new. Make it persist in storage. UI.sandbox.memorize(wd) # Forget (destroy) any remaining workdate objects. for wd in rem: wd.forget() Robert Brewer MIS Amor Ministries fumanchu at amor.org From sstaats at questia.com Mon Oct 11 11:43:10 2004 From: sstaats at questia.com (S. Staats) Date: 11 Oct 2004 08:43:10 -0700 Subject: How does one keep python from printing newline at program exit? Message-ID: <64cf9d00.0410110743.ec1920f@posting.google.com> Good day, everbody. Here is a simple program called test.py: #!/usr/bin/python print "No newline, please.", # End of program Here is what program does: prompt> ./test.py No newline, please. Here is what I want the program to do: prompt> ./test.py No newline, please.prompt> How can I get the python interpreter to not print a newline when it exits? Thanks for your help! From peter at engcorp.com Fri Oct 1 11:05:16 2004 From: peter at engcorp.com (Peter L Hansen) Date: Fri, 01 Oct 2004 11:05:16 -0400 Subject: __author__ In-Reply-To: <6e04113a.0410010627.559842f6@posting.google.com> References: <6e04113a.0410010627.559842f6@posting.google.com> Message-ID: David Keeney wrote: > I see this set (or similar) of variables in various modules I read. > They are found near the top of each module file, outside of any class > or function definitions. > > " > __author__ = "Software Authors Name" > __copyright__ = "Copyright (C) 2004 Author Name" > __license__ = "Public Domain" > __version__ = "1.0" > " > > What is the function of this set of variables? I assume there are > software products that use these, (Python itself, perhaps), that > expect to find certain variables explained. > > What are the expected variables, other than the ones listed above, and > what software would I expect to use them? IME, other than __version__, none of these are *widely* used, nor are they necessary. In any case, they are all just conventions, and there are NO "expected variables" along the lines of what you're thinking, and while there is probably some software that uses some particular set of them, looking for such a thing just so that you can throw a bunch of things like that at the top of your modules, where they will never actually be used (except for __version__), is a waste of time, IMHO. *If* you want to write them that way, then use them in, say, an About Dialog or when a "-h" option is specified, then go ahead. I personally use things like APP_AUTHOR and APP_COPYRIGHT rather than the double-underscore convention, which in my view makes them look like they are somehow "special" to Python, causing just the sort of confusion that you have faced here. :-( -Peter From Anna at nospam.invalid Sun Oct 3 00:52:45 2004 From: Anna at nospam.invalid (Ann) Date: Sun, 03 Oct 2004 04:52:45 GMT Subject: newbie permission problem Message-ID: I am new to python. I have a small program that deletes small jpeg files, but I am getting a permission error, even though I am the owner of the file and the directory has 777 permission. I have WIN XP Pro. I have mks toolkit "ls" command. Login name is "Philip" ------------- 36 45 border_l_r2_c3.gif is tiny <- printed by program Traceback (most recent call last): File "C:\test2.py", line 28, in ? os.remove(d) # delete the tiny files OSError: [Errno 13] Permission denied: 'border_l_r2_c3.gif' C:\>ls -ld . border_l_r2_c3.gif drwxrwsrwx 1 Philip None 0 Oct 2 23:40 . -rwxrwxrwa 1 Philip None 398 Oct 2 22:42 border_l_r2_c3.gif From garabik at kassiopeia.juls.savba.sk Wed Oct 20 03:09:19 2004 From: garabik at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 20 Oct 2004 07:09:19 GMT Subject: module to ping a remote computer References: <1098167660.152175@news-1.nethere.net> Message-ID: <2tmh8vF20qqlaU1@uni-berlin.de> anonymous wrote: > Has anyone here created a module for pinging a remote computer via the ping > command and displaying a green/red led light button on the local computer > depending upon the response back? This would be a very simple automatic > monitor. > Jeremy Hylton, jeremy @ cnri.reston.va.us did develop a ping class. I have a copy of it because I wanted to use it in some other project, but never got enough time to finish it. I can send you a copy if you want. -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From mwilson at the-wire.com Fri Oct 8 12:04:24 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 08 Oct 2004 12:04:24 -0400 Subject: Graceful handling of first line References: <654bb44cb5ff9def08dab7c56459c4c0@localhost.talkaboutprogramming.com> <4165C9FD.5060000@bellsouth.net> Message-ID: In article , Egbert Bouwman wrote: >A file is too large to fit into memory. >The first line must receive a special treatment, because >it contains information about how to handle the rest of the file. > >Of course it is not difficult to test if you are reading the first line >or another one, but it hurts my feelings to do a test which by definition >succeeds at the first record, and never afterwards. >Any suggestions ? f = file("lines.txt", "rt") first_line_processing (f.readline()) for line in f: line_processing (line) ought to work. Regards. Mel. From nico-NoSp at m-tekNico.net Wed Oct 6 16:57:56 2004 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Wed, 06 Oct 2004 22:57:56 +0200 Subject: New to Python: Features References: <4162B500.6080209@sympatico.ca> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > ...it sounds like Python has most of what I want (though not all). That which it doesn't have, you'll learn to "unwant" it soon. ;-) - -- Nicola Larosa - nico-NoSp at m-tekNico.net Python gives you enough rope to hang yourself, but you have to know where to look. Its land has a dearth of trees, branches or posts to use the rope to actually hang yourself. And the landscape is so beautiful we don't even notice most of the time. :) -- Chris on comp.lang.python, July 2004 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFBZFxYXv0hgDImBm4RAjxKAJ4xY+H7AOkHmucJ1dZWyofndAt3TwCeOjGe s8WXvvy9aiRqyUWrYIwWIMU= =1P1R -----END PGP SIGNATURE----- From dw at botanicus.net Sat Oct 23 10:36:02 2004 From: dw at botanicus.net (David Wilson) Date: Sat, 23 Oct 2004 15:36:02 +0100 Subject: ConfigParser shootout, preliminary entry In-Reply-To: References: <1098051181.4172ee6dea6f5@mcherm.com> <16761.55998.900388.409796@montanaro.dyndns.org> Message-ID: <417A6C52.2020709@botanicus.net> Peter Hansen wrote: >> In the context of the subject, we are discussing here a replacement >> ConfigParser. Any implementation of attribute access would amount to a >> possibly regression in functionality and more incompatibility with how >> Microsoft did it, as keys may be duplicate in .INI land. > So to recap, even though I might believe it's a good idea > *for me*, in a particular application which I have in mind > and which you know nothing about, you believe that I should > not use such an approach, in my own code, on my own application. > Or at least you would say that I'm committing some sort of > really bad programming mistake by doing so. Have I got that > right? No. I'm not sure how you took what I said to mean the above, as I have never referred to your style of code or anything else to do with you. To reiterate infinitely, I am referring to a configuration file parser. In particular, the one present in the standard library which presents an interface to Microsoft-style .INI files. In that parser, __getattr__ cannot be applied cleanly without adding nonstandard semantics to the returned attribute - either discard data, or return multiple items of a surprising type - a list at best. > Or was it just that *you* don't like this pattern of access > (in which case I'd suggest that you don't have to use it, > since the dictionary approach is provided as well). I am interested only in providing a correct and clean interface to a very simple piece of functionality. I am happy to say that anyone that uses __getattr__ for .INI files should be shot. If that includes you, it would be a sad loss.. > For me, replace "confobj" with "config", representing the > "configuration information" of the program, and in that case > "category" bears a clear relation to it. NAME ConfigParser - Configuration file parser. The 'config' object you refer to does not appear to be implemented by the ConfigParser module. Furthermore, I have > *no duplicate keys*, so I really would like to use the much > simpler form of access "config.logging.maxfilesize" or some > such. > > If I had only a "confobj" of your variety, which provided *only* > the dictionary interface, I would be sorely tempted just to read > in all the keys and store them in my own "config" object, which > would then be used as I mentioned above. I'd really rather not > go to that extra effort. Then join the effort to create a new configuration system, *do not* pollute ConfigParser. Again I point at the subject line and the footer of my previous post. > I think this is a case of you imagining only one style of > access and application, while there are other scenarios where > other forms of access are equally appropriate *or better*. > Nobody is forcing you to use the other method though. No, I am trying to defend the cleanliness of a very simple class for reading a configuration file, not representing configuration data, or acting as a mapping or transparent proxy for the items present in a configuration. David. From spamtrap at library.lspace.org.invalid Tue Oct 12 09:45:45 2004 From: spamtrap at library.lspace.org.invalid (Shmuel (Seymour J.) Metz) Date: Tue, 12 Oct 2004 10:45:45 -0300 Subject: EVIL AMERICAN GOVT (aka FBI) is full of SADISTS and PERVERTS References: <11a9e0b9.0410100611.1d8028b0@posting.google.com> Message-ID: <416bee19$3$fuzhry+tra$mr2ice@news.patriot.net> In <11a9e0b9.0410100611.1d8028b0 at posting.google.com>, on 10/10/2004 at 07:11 AM, vickyp679 at yahoo.com (vicky) said: >Newsgroups: >comp.lang.pl1,comp.lang.postscript,comp.lang.prolog,comp.lang.python,comp.lang.rexx >Subject: EVIL AMERICAN GOVT (aka FBI) is full of SADISTS and >PERVERTS What does this garbage have to do with any of those news groups? >I am not a muslim, I don't have even a single muslim friend, I am >not a member of any religious organization, Nu, so by you it would be OK to persecute someone for his religion? >FBI has been MENTALLY TORTURING me with 24X7 surveillance for the >last three years inside and outside my apartment with video >surveillance devices and motion sensors around my apartment, my >phone has been tapped, my web surfing is being monitored all the >time for the last three years, my emails are being monitored, gps >vehicle tracking devices and voice amplification devices have been >placed in my car and undercover FBI agents have followed me to >restaurants, grocery stores, malls, movie theatres, banks and even >barber shops etc They have my sympathy. Three years on the kook squad is too much for any man. I can get you a good price on purple cloths. -- Shmuel (Seymour J.) Metz, SysProg and JOAT Unsolicited bulk E-mail subject to legal action. I reserve the right to publicly post or ridicule any abusive E-mail. Reply to domain Patriot dot net user shmuel+news to contact me. Do not reply to spamtrap at library.lspace.org From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Tue Oct 12 18:19:59 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Tue, 12 Oct 2004 23:19:59 +0100 Subject: proposition for syntax for initialisation of multidimensional lists In-Reply-To: <416c465f$1@news.broadpark.no> References: <416c465f$1@news.broadpark.no> Message-ID: Nils Grimsmo wrote: > i always have trouble explaining why creation of multidimensional lists > is not as straight forward as it could be in python. Maybe because that is not really a sensible thing to do with the list data structure, which can change in length after instantiation? > >>> [0] * (2,3,4) > [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, > 0], [0, 0, 0, 0]]] > > [SNIP] > > what do you think? I think I will continue doing this: >>> import numarray >>> numarray.zeros((2,3,4)) array([[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]) -- Michael Hoffman From andrea.valle at unito.it Sat Oct 30 02:51:23 2004 From: andrea.valle at unito.it (andrea valle) Date: Sat, 30 Oct 2004 08:51:23 +0200 Subject: names of parameters as string In-Reply-To: <291020042102228624%JBrouwersAtProphICyDotCom@no.spam.net> References: <3cccb1d8.0410280723.50ff8679@posting.google.com> <41811f1f$0$33063$a1866201@newsreader.visi.com> <3cccb1d8.0410290102.7f001ada@posting.google.com> <291020042102228624%JBrouwersAtProphICyDotCom@no.spam.net> Message-ID: <1CC54D90-2A40-11D9-A5B8-0003939C968C@unito.it> Thanks to all for the replies. Now, sorry, something related. Suppose I have a string and I'd like to create a variable with its name. How can I do that? I tried to create the variable text assigning to it the value "text" with this: >>> eval("text = \"text\"") But it raises an error. Thanks as usual Best -a- On 30 Oct 2004, at 05:59, Jean Brouwers wrote: > > > Take a look at the getargspec() function in the inspect module. It > returns a 4-tuple and the first item of that tuple is a list of the > parameter names of a function or method. > >
>   import inspect
>   def foo(p1, p2):
>     pass
>   print inspect.getargspec(foo)
>
> results in:
>
>   (['p1', 'p2'], None, None, None)
>
> 
> > The second item is the name of the *args argument, the third is the > name of the **kwds argument and the last item is a tuple of the values > of the kwds args. > > More details in > > > > and on page 381 of the (outstanding, IMO) book "Python in a Nutshell", > 1st edition. > > > /Jean Brouwers > ProphICy Semiconductor, Inc. > > >>>>> def foo( foo_param1, foo_param2): > > > In article , > andrea valle wrote: > >> Hi to all, >> I'd like to access the parameter list of a function (or better of a >> method) in order to generate GUI elements. >> That is. >> If I have this: >> >>>>> def foo( foo_param1, foo_param2): >> print foo_param >> >> I'd like to have something like: >> >>>>> print foo.param_list >>>>> 'foo_param1', 'foo_param2' >> >> My idea is to use the foo_params strings in Tkinter as text for Label >> and as variables for Entries. >> >> What have I to do? >> >> Thanks a lot as usual >> >> Best >> >> -a- >> >> >> _____________________________________________________________________ >> For your security, this mail has been scanned and protected by Inflex > -- > http://mail.python.org/mailman/listinfo/python-list > Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From dgargan at sbcglobal.net Wed Oct 20 21:57:23 2004 From: dgargan at sbcglobal.net (digidalmation) Date: Thu, 21 Oct 2004 01:57:23 GMT Subject: mod_python apache configuration issues In-Reply-To: References: Message-ID: <7IEdd.20327$Qv5.18051@newssvr33.news.prodigy.com> David Fraser wrote: > digidalmation wrote: > >> Hello all. I've been trying to get my linux server to run mod_python. >> It's a Mandrake 10 linux box, and apache/mod_python are installed from >> rpms. >> apache2-mod_python-2.0.48_3.1.3-1mdk >> apache2-2.0.48-6mdk >> >> >> The rpm installed the python module as: >> /usr/lib/apache2-extramodules/mod_python.so >> >> And added a config file for apache: >> /etc/httpd/conf.d/16_mod_python.conf >> >> The apache config files contained the following before my modifications: >> >> >> LoadModule python_module extramodules/mod_python.so >> >> >> >> >> >> Now after reading the docs installed into /usr/share/doc for mod_python >> and going through the directions at python.org, I've also changed the >> config file to add a few lines to one of the directives: >> >> >> Options -Indexes FollowSymLinks MultiViews >> AllowOverride All >> AddHandler mod_python .py >> PythonHandler mptest >> PythonDebug On >> >> >> Now when I put the url into a browser: >> http://myserver.mydomain.com/mptest.py >> >> I get a popup from the browser because it doesn't know how to handle >> mptest.py, and it asks what you want to do with the file (open it with >> an application, save it to disk, etc). I can choose to open the file >> with a text editor, and all it shows is the text "hello world". >> >> That's the output of the mptest.py script.... apache isn't feeding the >> browser the code from the mptest.py, only the output. (Otherwise when I >> open it in a text editor I'd see the entire mptest.py script. >> >> Contents of the mptest.py script: >> from mod_python import apache >> >> def handler(req): >> req.write("Hello World!") >> return apache.OK >> >> I'm not a python developer, but have been working with Linux and Apache >> for a number of years. I'm not sure where to go from here. It appears >> that the script gets compiled - there is a mptest.pyc file in the >> directory now. Why is it sending my browser the mptest.py file with the >> stdout of the script? >> >> Thanks in advance. Any help on this is appreciated. >> >> Dave >> >> > > This is working properly, all you want to do is set the content type so > that your browser can understand it: > req.content_type = "text/plain" > or something like that should do it. > > David David, you steered me in the right direction! I just added this to my apache config file, and voila... it works. AddType text/plain .py Many thanks David. Dave From greg.lindstrom at novasyshealth.com Fri Oct 29 15:44:37 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Fri, 29 Oct 2004 14:44:37 -0500 Subject: Collating Text and Images Message-ID: <006f01c4bdef$b99464c0$054b12ac@D18SYX41> Steve writes: The ReportLab open source kit is well capable of doing this, and will make your reports look better as well, as long as PDF is an acceptable output format. Greg replies: Indeed, the reportlab toolkit kicks butt!. I downloaded it and in less than 4 hours I was showing off the proof-of-concept to my coworkers. The merging of the two files is simple (though we are doing some manipulations which are not) and I am creating pdf files that may allow us to stop printing the reports off altogether (nearly 1000 pages per day). Thanks, everyone, for the great suggestions! Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From pmaupin at speakeasy.net Sun Oct 31 00:34:56 2004 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 30 Oct 2004 21:34:56 -0700 Subject: scripting languages vs statically compiled ones References: Message-ID: <653b7547.0410302034.58737996@posting.google.com> kosh wrote: In addition to your points and Alex's additions, I would add (as part of your step 4): To make Python faster (drumroll...) CACHE EVERYTHING!!! The concept of caching goes by various names (e.g. memoize) depending on the exact form it takes, but in any case it is usually _much_ easier to do simply and correctly in Python than in almost any other language, and can sometimes produce dramatic results. As an example, I wrote an assembler/linker combination in Python (with a little bit of Pyrex and a tiny bit of C for the scanner). When I started out, it was much slower than the C legacy system it replaced. Now, it is much faster, by a factor of around 4x for a full build. It is also much nicer, catches more errors, has a more flexible syntax, etc. In C, there is no way I would have been able to get the semantics right for usefully caching the results of partial evaluation of include files, but in Python it is a snap. (Note that I did not assert that it is not possible to do this in C, merely that _I_ would have been incapable of doing it in the time I would have been willing to spend on the task.) I also cache the object files (which are merely pickles) in preparation for doing a link, the source modules in preparation for doing a listing output (which can be done as a relative listing before the link, or an absolute listing after the link), and anything else I can think of. The Python version occupies a working set of around 75MB when it runs, compared to about 4MB for the C version. Good programmers have always known about time vs. memory tradeoffs, but the informed use of Python in conjunction with the staggering amount of memory available on today's average PC can produce truly startling results. Regards, Pat From jzgoda at gazeta.usun.pl Fri Oct 15 19:11:11 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 15 Oct 2004 23:11:11 +0000 (UTC) Subject: Eric3 + Qt licensing [was Re: The IDE question] References: <416f9663$0$94915$bed64819@news.gradwell.net> Message-ID: Stephen Waterbury pisze: >> Windows versions are named, royalty-free, commercial licenses. >> [... long, tortuous explanation ...] Hallo, any lawyers around here? > > As he said, "way too messy"! ;) I am not sure if Detlev can pose such exceptions... Well, Qt-and-around is not an easy shoot. ;) -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From vegard at mail.com Wed Oct 6 10:46:34 2004 From: vegard at mail.com (Vegard Bakke) Date: 6 Oct 2004 07:46:34 -0700 Subject: XSL transform with Python Message-ID: <33a013af.0410060646.3a821dc7@posting.google.com> Hi! All I want to do is transforming an XML into another XML using an XSLT stylesheet. >From what I have found on the web/usenet there are several xml/xsl libraries/wrapper, all in various stages of alpha/beta/stalled releases. (Sablotron, Sab-pyth, PySablot, libxml2, libxslt are some of those I found.) The script will be running in a production environment and must therefore be stable above all. Alphas and Betas are not that welcome. Can anyone give me a pointer to what module to use, what is stable, and what is and be stay standard for Python? Regards, Vegard Don't reply to the address above, It's a spam trap and won't be read -- My spelling is Wobbly. It's good spelling but it Wobbles, and the letters get in the wrong places. Winnie the Pooh From ialbert at mailblocks.com Wed Oct 27 10:40:53 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 27 Oct 2004 10:40:53 -0400 Subject: Open Source License Question In-Reply-To: <_-adnfiRi4tmPOLcRVn-1A@powergate.ca> References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <2u9hklF24n4b1U1@uni-berlin.de> <_-adnfiRi4tmPOLcRVn-1A@powergate.ca> Message-ID: Peter Hansen wrote: > I haven't been trying to keep up to date on this issue, but these > guys seem to feel there is something along those lines that can be done: > http://creativecommons.org/ (Specifically, IMO the problem with the licenses (the CC is no help in that) is that the terms are to vague. It is very easy to define what it means to give away all rights, but for anything more complicated it bogs down quickly: What is a derivative work? When is attribution properly done? What is a commercial use? What is fair use? Istvan. From theller at python.net Tue Oct 12 04:24:40 2004 From: theller at python.net (Thomas Heller) Date: Tue, 12 Oct 2004 10:24:40 +0200 Subject: Windows XP Balloon Tips? References: <1d6cdae3041011094946722f33@mail.gmail.com> Message-ID: Harald Massa writes: > Dave Benjamin, > >> Just out of curiosity, is there a way to do this also from PythonWin >> (without having ctypes installed)? > > the game is called "AnimateWindow". > I posted a ctypes-programm to pywin32 mailinglist two weeks ago. It just > was not robust enough to go into the wiki. You forgot to keep a reference to the callback function - a very common error. I hope to make this much easier in the next ctypes version, where ctypes does this itself automatically. > > With build 203 Python win32 extension by Mark Hammond also wrap the > AnimateWindow function (on XP), but they came out yesterday so I just read > the change notes that they do; did not find a demo. So... please download > pywin32 and try :))) Thomas From aahz at pythoncraft.com Tue Oct 12 16:26:52 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 Oct 2004 16:26:52 -0400 Subject: Parallelization on muli-CPU hardware? References: <6db3f637.0410042045.2171ad5f@posting.google.com> <416b9eed$0$11828$afc38c87@news.easynet.fr> <416bd75f$0$10909$afc38c87@news.easynet.fr> Message-ID: BTW, Nicolas, it'd be nice if you did not post quoted-printable. I'm leaving the crud in so you can see it. In article <416bd75f$0$10909$afc38c87 at news.easynet.fr>, Nicolas Lehuen wrote: > >Yeah I know this. My point was that when benchmarking single-threaded = >programs vs multithreaded ones, you have to choose the kind of program = >you use : CPU-intensive vs IO-intensive. On a single CPU machine, = >CPU-intensive program will always run better in a single-threaded model. = >But of course, if you have 2 procs and a nice threading model, you can = >even do 2 CPU-intensive tasks simultaneously, which Python cannot do if = >I've understood everything so far. Python itself cannot, but there's nothing preventing anyone from writing numeric extensions that release the GIL. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From psuspam at grinchcentral.com Mon Oct 4 16:14:41 2004 From: psuspam at grinchcentral.com (Erik Rose) Date: Mon, 4 Oct 2004 16:14:41 -0400 Subject: ActivePython/IIS Request Concurrency In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3022F28@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3022F28@exchange.hqamor.amorhq.net> Message-ID: <069C3857-1642-11D9-8DF7-000A95B6C878@grinchcentral.com> > It's sufficient. :) Check out > http://www.4guysfromrolla.com/webtech/082201-1.shtml for a good intro > to using pywin32 for ASP. Interestingly, that page espouses ActivePython, which I'm beginning to suspect is nothing more than a thin candy coating around pywin32. Do you know whether this is so? > FWIW, I don't use ASP for anything more than an envelope for "real" > Python scripts. [...] Such a scheme can keep you from tearing your > hair out trying to mix Python indentation rules with HTML's lack of > such. I hope to make it to that point eventually. Right now, I have >15K lines of VBScript that are going to have to interact peaceably with the new Python stuff. (This is why I can't even consider CGI.) I hope to do a bunch of inversion-of-control in Python and shove the VBScript out more and more into peripheral utility functions, where it can be translated at leisure. So, just to confirm, you ran a few instances of my original test scripts concurrently, and they completed almost simultaneously? Note that your machine may be faster than mine. Does the busy-wait loop take at least several seconds to run? If not, it would be hard to tell if the instances of it were running serially or not. If they are indeed concurrent, I'll be in touch soon to harrass you about your IIS settings. :-D Excitedly, Erik Rose Programmer/Analyst Pennsylvania State University From lutherrevisited at aol.com Wed Oct 20 15:46:35 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 20 Oct 2004 19:46:35 GMT Subject: Final thoughts SMTP Message-ID: <20041020154635.25562.00002510@mb-m29.aol.com> To clear up something which Gerhard advised me on regarding the login method. I've found that AOL's smtp server is unique compared to every other one I've seen. If you type auth plain, it will prompt you with: user:, then password:, that is why I did the s.docmd thing since AOL is daring to be different, I did find that if you went with auth login the s.login would work then, you just had to give the auth login cmd first.....go figure. At school I actually am able to directly get to smtp servers and am not rerouted to that nefarious aol server, and there I found that s.login works perfectly on every email server I use, except AOL....go figure, and then it will if you just do it the way they want you too. Thanks for all the help on this guys, pretty much everything I was told was dead on, AOL just has a psychotic way of doing things. From richardblackwood at cloudthunder.com Tue Oct 5 11:26:59 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Tue, 05 Oct 2004 11:26:59 -0400 Subject: New to Python: Features In-Reply-To: <1gl6e9j.1cn88p21wfi6s0N%aleaxit@yahoo.com> References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> <1gl6e9j.1cn88p21wfi6s0N%aleaxit@yahoo.com> Message-ID: <4162BD43.4050104@cloudthunder.com> >I agree with you that it does, though not as well as you appear to >believe (e.g. no `` 2 + "23" '' abominations in Ruby, either). Perl >might be better still for what he's asking -- said abomination does >work, he gets to mess with syntax (google for lingua latina perligata), >and so forth. > > >Alex > > Perl is a mess. Ruby is a mess. Python is generally clean and I love the whitespace. From ialbert at mailblocks.com Mon Oct 25 23:32:35 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 25 Oct 2004 23:32:35 -0400 Subject: Paid Research Project on Stackless 3.1 In-Reply-To: References: <468v42-c23.ln1@nb2.stroeder.com> Message-ID: Samir Patel wrote: > I hope in future people will be more respectful to all those heros who > works so much for python community. Hero or not remains to be seen, but there is nothing wrong in voicing a contradictory opinion, and such opinions should never be put down with *patriotic* arguments as the one above. Istvan. From mirko-individual at zeibig.net Fri Oct 1 13:51:40 2004 From: mirko-individual at zeibig.net (Mirko Zeibig) Date: Fri, 01 Oct 2004 19:51:40 +0200 Subject: recursing through files in a folder In-Reply-To: References: Message-ID: <2s5m32F149n27U1@uni-berlin.de> Larry Bates said the following on 10/01/2004 04:20 PM: > Scott Carlson wrote: > >>New to Python. Very new. >> >>I need to pass a parameter to the program I create that points to a >>folder. (How are params passed in?) >> >>Then, I need to be able to scroll through each file in the folder, >>looking for files with a particular naming convention. >> >>What is the best way to be able to look at each file in a folder and >>decide if I wish to use that one, and then go to the next file? >> >>Thanks, >>Scott > > > Use getopt to pick up the root directory from call line > Use os.path.walk to walk each of the files/directories > Use glob.glob to get a list of files that match I'd opt for `optparse` instead of `getopt` ;-). Since Python 2.3 it's included in the distribution, for older version search for `optik`, which is the old name of `optparse`. Regards Mirko From abra9823 at mail.usyd.edu.au Thu Oct 14 09:28:37 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Thu, 14 Oct 2004 23:28:37 +1000 Subject: UDP server socket In-Reply-To: References: Message-ID: <1097760517.416e7f0523337@www-mail.usyd.edu.au> Quoting Peter L Hansen : > Ajay wrote: > > whats the maximum number of datagrams that can queue up on a UDP > server > > socket? or is that system dependent? > > i have some code that iteratively handles datagrams, and while testing > it, > > i noticed that it responds to at most 3 datagrams (i tried sending 4, > 6, 8 > > and 10 datagrams / second) > > is that a system dependent feature or can i change that (i didn't see > > anything in the manual) > > I don't believe (though I'm not an expert in UDP) that you can > "queue up" UDP packets at all. At least, there are explicitly > NO guarantees as to whether any given packet will even make it > through the network, and I doubt any system provides explicit > guarantees as to how many UDP packets can be handled if there > is a backlog. If you are looking for reliable communications, > that's what TCP is for... otherwise you have to handle missed > or duplicated packets yourself. > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > i am afraid i have to stick with UDP and reliability is no issue. i used the word queue but what i really meant was buffer and what i really want to know is how many packets get buffered (the ones that make through). i dont believe that when i send 10 packets, 7 get lost and 3 make it through. Since when i send 3, i always get all 3 (well except perhaps once or twice) but i can never get any more than 3. i want to confirm if this is a buffering issue in my code i do something like while 1: data, address = self.UDPserversocket.recvfrom(1024) #do a lot of processing which usually takes between 4-8 seconds my question is whether the socket buffers incoming packets, what is the size of the buffer and is there any way of increasing it. If not, a solution may be to carry the processing in another thread, but thats going to increase the overhead (the app. is for a PDA). ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From skip at pobox.com Fri Oct 29 07:42:24 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 29 Oct 2004 06:42:24 -0500 Subject: Multiple XML-RPC calls over the same connection? In-Reply-To: References: Message-ID: <16770.11424.859808.183866@montanaro.dyndns.org> >> I want to be able to create a persistent connection between an >> XML-RPC client and server... i.e. I want to be able to login once, >> carry out a number of calls and then logout rather than send login >> info for every call. >> Is there a way to do this with the xml-rpc code in the standard >> library? Look at the multicall capability of the xmlrpclib library. It may do what you want. Skip From behnel_ml at dvs1.informatik.tu-darmstadt.de Wed Oct 20 12:52:24 2004 From: behnel_ml at dvs1.informatik.tu-darmstadt.de (Stefan Behnel) Date: Wed, 20 Oct 2004 18:52:24 +0200 Subject: Logging messages with dictionary args in Python 2.4b1 leads to exception In-Reply-To: <4176836E.4000507@holdenweb.com> References: <8cf2994e.0410200246.64e9e910@posting.google.com> <4176836E.4000507@holdenweb.com> Message-ID: Steve Holden schrieb: > A possible enhancement which might meet your arguments would allow the > user to provide EITHER a tuple of arguments OR a set of keyword > arguments. LogRecord could then say: > > if args: > msg = msg % args > else: > msg = msg % kwargs > > and you would then be able to make a call like > > logging.log(logging.FATAL, 'Test is %(test)s', **values) > > But with the code you presented, it's no use bleating that "values *is* > a mapping". While this is certainly true, values was unfortunately just > the only element in the args tuple, and it's the args tuple that's > currently used for substituion. I presume the patch you sent Vijay will > do something similar? What it does is: check if there is only one element in args and then unpack it. This leads to three different cases how msg = msg % args is evaluated: 1) the tuple is longer than one, i.e. args actually is a tuple => current beahaviour 2) the tuple contained one element, but not a dict, i.e. args is a value => replace the single template in msg with that value => current behaviour 3) the tuple contained one element, which was a dict, i.e. args is a dict => replace the dictionary templates in msg with the values in args I find this very much the expected behaviour, which when used by actual code looks like this: log("message %s %d", 1, 2) or log("message %(a) %(b)", {'a':1, 'b':2}) I find it absolutely wrong if the second raises an exception. That would differ from any other common use case of dictionaries in Python. Even this works: log("message %s", {'a':1, 'b':2}) So the only (!) change is the additional support for dictionary arguments. No drawbacks. I think, this is totally the right thing to do. Stefan From finite.automaton at gmail.com Mon Oct 11 19:08:01 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 11 Oct 2004 16:08:01 -0700 Subject: tokenise a string References: <86brfcq9nk.fsf@mut.mteege.de> <2sqeabF1nrio1U1@uni-berlin.de> Message-ID: <4b39d922.0410111508.3edbde0b@posting.google.com> The tokenize module is only useful for parsing Python code. That said, reading the code of tokenize.py might be helpful in writing your own tokenizer. Look into the re (regular expression) module, or PLY or Spark if you need more sophisticated parsers. Also check out SQLObject (http://sqlobject.org/) --- it makes SQL almost pleasant =) Cousin Stanley wrote in message news:<2sqeabF1nrio1U1 at uni-berlin.de>... > On 2004-10-09, Matthias Teege wrote: > > Moin, > > .... > > So I must parse the input, build tokens and map the fieldnames. > > > > Is there a special modul which I can use > > or are the standard string functions adequate? > > > > Matthias .... > > You might check the tokenize module .... > > import tokenize > > help( tokenize ) > > I only know of it, but have never used it myself .... From bokr at oz.net Sun Oct 17 02:29:36 2004 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Oct 2004 06:29:36 GMT Subject: How to get the size of a file? References: Message-ID: <4171fdec.13660092@news.oz.net> On Sun, 17 Oct 2004 03:13:46 GMT, User <1 at 2.3> wrote: >Anyone have ideas which os command could be used to get the size of a >file without actually opening it? My intention is to write a script >that identifies duplicate files with different names. I have no >trouble getting the names of all the files in the directory using the >os.listdir() command, but that doesn't return the file size. In order >to be identical, files must be the same size, so I want to use file >size as the first criteria, then, if they are the same size, actually >open them up and compare the contents. > >I have written such a script in the past, but had to resort to >something like: > >os.system('dir *.* >> trash.txt') > >The next step was then to open up 'trash.txt', and piece together the >information I need compare file sizes. The problems with this >approach are that it is very platform dependent (worked on WIN 95, but >don't know what else it will work on) and 8.3 filename limitations >that apply within this environment. That is the reason I'm looking >for some other command to obtain file size before the files are ever >opened. This should list duplicate files in the specified directory: You can hack to suit. Not very tested. Just what you see ;-) ------------------------------------------------ # get_dupes.py import os, md5 def get_dupes(thedir): finfo = {} for f in os.listdir(thedir): if os.path.isfile(f): finfo.setdefault(os.path.getsize(f), []).append(f) result = [] for size, flist in finfo.items(): if len(flist)>1: dupes = {} for name in flist: dupes.setdefault(md5.new(open(name, 'rb').read()).hexdigest(),[]).append(name) for digest, names in dupes.items(): if len(names)>1: result.append((size, digest, names)) return result if __name__ == '__main__': import sys try: dupes = get_dupes(sys.argv[1]) if dupes: print print '%8s %32s %s' % ('size','md5 digest','files with the given size, digest') print '%8s %32s %s' % ('----','-'*32 ,'---------------------------------') for duped in dupes: print '%8s %32s %s' % duped else: print 'No duplicate files in %r' % sys.argv[1] except: raise SystemExit, 'Usage: python get_dupes.py directory' ------------------------------------------- (I was surprised at the amount of duplicated stuff ;-) [23:23] C:\pywk\clp>python get_dupes.py . size md5 digest files with the given size, digest ---- -------------------------------- --------------------------------- 0 d41d8cd98f00b204e9800998ecf8427e ['z3', 'zero_len.py'] 111 ea70a0f814917ef8861bebc085e5e7d0 ['MyConsts.py', 'MyConsts.py~'] 163 f8e4add20e45bb253bd46963f25a7057 ['ramb.txt', 'rambxx.txt'] 4096 d96633a4b58522ce5787ef80a18e9c7b ['yyy2', 'yyy3'] 786 05956208d5185259b47362afcf1812fd ['startmore.py', 'startmore.py~'] 851 3845f161fa93cbb9119c16fc43e7b62a ['quadratic.py', 'quadratic.py~'] 1536 72f5c05b7ea8dd6059bf59f50b22df33 ['virtest.txt', '~DF30EC.tmp'] 1028 fbedc511f9556a8a1dc2ecfa3d859621 ['PaulMoore.py', 'PaulMoore.py~'] 1515 568f9732866a9de698732616ae4f9c3b ['loopbreak.py', 'loopbreak.py~'] 1662 f54414637ed420fe61b78eeba59737b7 ['for_grodrigues.py', 'for_grodrigues.r1.py'] 1702 23fa57926e7fcf2487943acb10db7e2a ['bitfield.py', 'bitfield.py~', 'packbits.py'] 3765 e69bf6b018ba305cc3e190378f93e421 ['pythonHi.gif', 'showgif.gif'] 5874 bae87bbed53c1e6908bb5c37db9c4292 ['testyenc.py', 'testyenc.py~'] 3990 4a5096efaf136f901603a2e1be850eb3 ['pns.py', 'pns.r1.py'] Regards, Bengt Richter From charleshixsn at earthlink.net Mon Oct 25 14:48:39 2004 From: charleshixsn at earthlink.net (Charles Hixson) Date: Mon, 25 Oct 2004 11:48:39 -0700 Subject: GPL and Python modules. In-Reply-To: References: <417d18bc$0$1313$a1866201@newsreader.visi.com> Message-ID: <417D4A87.1020405@earthlink.net> Peter Otten wrote: >Grant Edwards wrote: > > > >>Let's say I use a GPL'd python module (e.g. something installed >>in site-packages) in an application. >> >> > >I'd say everything that uses a GPL'd module is derived work and must also be >GPL'd. It doesn't matter how you distribute it. If the module is under the >LGPL you could use it in a closed source app but must make available any >changes to the original module. > >Peter > > > I don't think that's correct. If you distribute the source, then I don't think that you need to GPL the code (and if you GPL the code, you *must* distribute the source anyway...so....). The thing is, the source, although it depends on the GPL code to execute is not itself linked to the GPL code. It tells you (in the import statement) that you'll need it, but that's a different matter. You might just want to study how some part of it worked. I doubt that this is much help to you though. Usually when people ask such a question it's because they intend to distribute a closed source version, and I don't think you can do that. (But don't take my advice as a certainty. I'm quite biased in favor of the GPL.) From jzgoda at gazeta.usun.pl Fri Oct 15 15:39:10 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 15 Oct 2004 19:39:10 +0000 (UTC) Subject: Eric3 + Qt licensing [was Re: The IDE question] References: <416f9663$0$94915$bed64819@news.gradwell.net> Message-ID: Ville Vainio pisze: > Jarek> Ville Vainio pisze: > > >> This Qt licensing thing is way too messy, I'm not surprised > >> that so many developers are doing their best to avoid it... > > Jarek> No, it isn't. It's GNU GPL. What do you consider unclear? > > Isn't it just the Unix/X11 version that is GPL/QPL dual licensed? Yes, it is. In case of Eric3 too. Windows versions are named, royalty-free, commercial licenses. If you have one, you can distribute Qt runtime dll with your programs, but not the source. PyQt follows this rule and on Windows you need (1) commercial license for Qt and (2) commercial license for PyQt. Hovewer, if you have both, you can distribute you program on Windows as free software. But as you may have read in GNU Public License, if you link to non-free library, you must give special permission in your license statement (as in the case of Psi Jabber client). Since Eric3 is GPL-ed software, only Detlev Offenbach can give this permission, but he states in README, that "building for personal purposes is permitted, but distribution is not". IANAL, but I think GNU GPL does not allow such restriction. Hallo, any lawyers around here? -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From see at below.invalid Sat Oct 2 03:00:35 2004 From: see at below.invalid (Paul Foley) Date: Sat, 02 Oct 2004 19:00:35 +1200 Subject: Exception feature creep! (was: re-entering in the normal flow after an exception is raised) References: <4b39d922.0410011152.31fb1dae@posting.google.com> Message-ID: On 1 Oct 2004 12:52:38 -0700, Lonnie Princehouse wrote: > In a recent post, Michele Simionato asked about resumable (or > re-entrant) exceptions, the basic idea being that when raised and > uncaught, these exceptions would only propagate backwards through a > limited number of frames before being implicitly ignored. Alex What a strange idea. > Nonetheless, I tried to write some demo code that implemented > resumable exceptions, but ran face-first into a brick wall: I > couldn't find any way to manipulate the call stack (to execute code in > a frame other than the current one) The mistake you're making is to conflate Python's exceptions with the resumable exceptions you're trying to implement. Python exceptions are more like Common Lisp's catch/throw mechanism (sort of a dynamically scoped "goto") than they are like the condition system. You can use Python's exception mechanism for the primitive control transfer, and build something on top of that (but since you can't write syntax in Python it's going to be butt-ugly). That's what Shai Berger was trying to do. Keep a list of (exception-type, function) pairs. Where you want a try/except, write a try/finally instead, with the "try" part pushing "except" handlers on the front of this list, and the "finally" part taking them back off (to emulate dynamic binding...don't use threads). Instead of using raise, look up the exception type in this list and call the associated function, so it runs above the failure point in the call stack (but note that it has to transfer control somewhere else if you don't want to return). For restarts, do a similar thing, mapping restart names to ("randomly" named) exception subclasses (as catch tags); where you want a restart, write try/except using that subclass name, push it on the restarts list, and to invoke it look up the name and use raise on the tag. Or something. -- Malum est consilium quod mutari non potest -- Publilius Syrus (setq reply-to (concatenate 'string "Paul Foley " "")) From parker at hiredatum.demon.co.uk Sun Oct 3 05:50:13 2004 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Sun, 3 Oct 2004 10:50:13 +0100 Subject: idiom for debug code? [1/1] References: <6tadnfHqDdcg9cHcRVn-hQ@rogers.com> <0DoHajVjBwXBFwhr@hiredatum.demon.co.uk> Message-ID: In message , Dan Perl writes >Thanks, Ian. It's late Saturday for me now so I will look more at the code >later, but so far what I get from what you sent is only dprint and that is a >logging utility. That's not what I was looking for. OTOH, I see that your >posting was probably only a first installment, so I am looking forward to >more details, including more parts from your utility module. > >The solution that you are using for the dprint utility involves a global >variable. How do you change its value? Is that still by making a change in >the code, even if the change is only one place? I would like a solution >that does not involve any change in the code and is determined strictly at >run-time. I was thinking of something like an environment variable or a >configuration attribute. Of course, your solution can be adapted to set the >global variable based on an environment variable or based on configuration. > >As for rewriting your code, did you take a look at the newsgroup thread >about the new logging utility? > >Dan > >"Ian Parker" wrote in message >news:0DoHajVjBwXBFwhr at hiredatum.demon.co.uk... >> In message <6tadnfHqDdcg9cHcRVn-hQ at rogers.com>, Dan Perl >> writes >>>I was not thinking of actually removing code. The analogy to C++ >>>preprocessing was just an example. I am looking at something that can be >>>determined at run-time, not compile-time. >>> >>>And you're right, I'm not really concerned about the overhead of an "if" >>>because I will not use this extensively anyway. This problem occurred to >>>me >>>when I decided to add an import for win32traceutil. I'm looking for a way >>>to have that permanently in the code and enabling/disabling it only at >>>run-time. >>> >>>I have thought of alternatives like an environment variable or a >>>configuration parameter, but I was looking for other ideas. I thought >>>this >>>should be a common issue and that there could be an idiom for it. >>> >>>Dan >>> >>>PS: in the case of importing win32traceutil, I guess that checking the >>>environment would be necessary anyway, or the import should be in a try >>>statement, ignoring the exceptions. >>> >>>"Larry Bates" wrote in message >>>news:wfmdnXvIef4v1cHcRVn-vQ at comcast.com... >>>> Dan Perl wrote: >>>>> Is there a mechanism or an idiom for adding code for debugging so that >>>>> it >>>>> can easily be removed in the production code? I am thinking of >>>>> something >>>>> similar to the C/C++ preprocessor statements with which you can compile >>>>> an application with the debug code or without it (the default). >>>>> >>>>> Dan >>>> Personally I think you should consider NOT removing the debugging code. >>>> It never ceases to amaze me how many times I must have a client run >>>> the application with debug set so that the program logs details about >>>> the running process and intermediate results. The output logfile can >>>> then be easily emailed, faxed, etc. to me so that I can determine what >>>> is REALLY the problem. The overhead of these if _debug: "type" >>>> statements seems incredibly low compared to the ability to get this >>>> information when needed. Just some thoughts based on my experience >>>> of the last 30+ years. >>>> >>>> Larry Bates >>>> Syscon, Inc. >>> >>> >> >> I' use the following technique. I originally wrote it four years or so >> ago, so I'm sure it could be much improved. In fact looking at it now, >> I ma deeply embarrassed to post it, and know it could be dramatically >> improved both by using more modern features of Python, by better coding >> and by some comprehension of design. >> >> I have a utility.py module which contains my common functions and I >> import this in every module, plus a wrapper for the debug function: >> >> import utility >> >> debug = 0 >> >> def dprint( *args): >> """ >> print function toggled on or off by module debug variable >> """ >> global debug >> if debug: >> apply(utility._dprint,args) >> >> >> This allows me to scatter dprint functions throughout the module instead >> of print statements, and enable or suppress them by setting the global >> 'debug', e.g. >> >> def func(x): >> global total >> total += x >> dprint("total is currently",total) >> >> to get an output of something like: >> ! module.py:83 in func: total is currently 10 >> >> >> The relevant code from my utility.py is attached. >> > > >-------------------------------------------------------------------------------- > > >> >> I would welcome rewrites of this code, of course. >> >> Regards >> >> Ian >> -- >> Ian Parker >> > > That was indeed the only instalment. Yes, thinking about it now, dprint is simply a logging system, so I really should look at the logging module -(which didn't exist when I wrote dprint). Feel free to lift the code - I certainly lifted chunks of it from other examples I find on this newsgroup. Yes, 'debug' is a global variable. The reason for the inclusion of the dprint wrapper in each module is to make use of the module 'debug' to give a little more granularity. Two points: In a function, I frequently do what feels like a very clumsy hack: def func(x,y): global debug ; olddebug = debug # debug = 1 . . debug = olddebug return so that any embedded dprints can be controlled more specifically. One other feature of dprint: if you call it without parameters it will attempt to display the arguments of the function in which it occurs. What other functions do I have in my utility.py? The same as everybody else - all those things you find yourself writing that you think you will use often. No I'm not publishing it - the code is frequently even worse than that of dprint. Regards Ian -- Ian Parker From steve at holdenweb.com Sat Oct 2 19:26:42 2004 From: steve at holdenweb.com (Steve Holden) Date: Sat, 02 Oct 2004 19:26:42 -0400 Subject: (no subject) In-Reply-To: References: Message-ID: Campbell Kwok wrote: > Hi, I am trying to write a program for my school homework and I'm a > little stuck. The homework have to do with barcodes and I need to read > the barcode, then add up all the odd number positions(eg a barcode of > 123456789012, then the odd is 1,3,5,7,9,1) I do not know how to get the > odd number positions out of that str of numbers. Please help me > > _________________________________________________________________ > Scan and help eliminate destructive viruses from your inbound and > outbound e-mail and attachments. > http://join.msn.com/?pgmarket=en-ca&page=byoa/prem&xAPID=1994&DI=1034&SU=http://hotmail.com/enca&HL=Market_MSNIS_Taglines > Start enjoying all the benefits of MSN? Premium right now and get the > first two months FREE*. > for i in range(half-length): print 2*(i+1) regards Steve From peter at engcorp.com Tue Oct 5 07:52:23 2004 From: peter at engcorp.com (Peter L Hansen) Date: Tue, 05 Oct 2004 07:52:23 -0400 Subject: [OT] New to Python: Features In-Reply-To: References: Message-ID: Mark English wrote: > Python is generally 2000 to 3000 times faster than Java if you run Java > on a toaster and Python on a super-cooled space computer orbiting > Saturn. QOTW! And thanks for the gut-wrenching laughs, Mark. :-) My doctor will be sending you his bill... -Peter From jbperez808 at wahoo.com Sat Oct 9 05:23:20 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Sat, 09 Oct 2004 17:23:20 +0800 Subject: Python GUI, which one? In-Reply-To: References: Message-ID: <2spof9F1n9rjrU1@uni-berlin.de> Sells, Fred wrote: > I see there are several different choices for Python GUI API's. > > Is there any indication of which ones are > 1. the most commonly used? > 2. the most reliable? > 3. the most robust? PyGtk, PyQt, Tkinter, and wxPython are the most 'mature' and widely used. Greg Ewing's PyGUI (http://nz.cosc.canterbury.ac.nz/~greg/python_gui/) may be a promising candidate. But I'm not particularly excited by any of the above. Instead, I think the 'holy grail' would be if the Mozilla people became more receptive to the idea of letting us script XUL via Python (instead of Javascript). XUL is both a cross-platform widget toolkit _AND_ GUI specification language and it is so easy and fast to use I would rather use it to build a GUI rather than a visual designer! Too bad the Mozilla people see XUL's future as more or less evolving in the direction of Javascript, RDF and some obscure de jure W3C standards which I highly doubt will ever see the light of day. If only some genius could hack the existing XUL widget toolkit and its XPCOM interfaces to make it scriptable with Python instead of Javascript. Or, failing that, recreate an XUL implementation that works with Python (will not need XPCOM or RDF anymore). The ideal future would be a Mozilla browser that is scriptable directly with Python and which also includes a Python interpreter. That way, you can deploy full-fledged XUL-based GUI apps (written in Python instead of yucky Javascript) on the net which will run for anyone who uses Mozilla. Javascript + W3C DOM is mediocre at best, and unfixable, so we should be jumping to XUL for web app UIs instead. And XUL works just as well for desktop apps as well (as evidenced by the Mozilla suite of applications incl. FireFox and Thunderbird). With speculations that Google might want to make their own (Mozilla-based?) browser, http://news.com.com/Clues+may+point+to+Google+browser/2100-1032_3-5379625.html and knowing that Python is extensively used within the company, perhaps the time has come for Python to start supplanting Javascript as the client-side scripting language of the web, and for XUL to replace W3C DOM/DHTML as the interface specification language/API for web applications. From theller at python.net Tue Oct 12 12:36:12 2004 From: theller at python.net (Thomas Heller) Date: Tue, 12 Oct 2004 18:36:12 +0200 Subject: DCOM References: <221d8dbe.0410120039.1e4675b5@posting.google.com> Message-ID: srijit at yahoo.com writes: > Hello, > I am looking for examples of simple DCOM server and client in Python > on Win 2K or Win XP. I could not find anything worth mentioning during > Google search. > > I am also interested to learn whether ctypes module can be used for > writing DCOM server and client. > There isn't much difference between DCOM and COM, for the server and client programmer, at least. Mark Hammond's "programming python on win32" explains how to set up DCOM, fortunately the chapter containing this is the sample chapter that's available online at http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html#60057 It is still recommended to get this book. Thomas From anna at aleax.it Wed Oct 6 16:28:30 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Wed, 06 Oct 2004 20:28:30 GMT Subject: New to Python: Features In-Reply-To: References: <4162200b$0$59533$a1866201@newsreader.visi.com> Message-ID: Richard Blackwood wrote: > Grant Edwards wrote: > >> On 2004-10-05, Richard Blackwood >> wrote: >> >> >> >>> When I said "harsh", I meant being accused of trolling, >>> attempting to annoy, stir trouble, etc. None which was my >>> intent nor did I think that my post would be interpreted as >>> such (otherwise I wouldn't have posted it). >>> >> >> >> If you honestly didn't think you were being rude and weren't >> going to annoy anybody, you really, really do need to read how >> to ask questions the smart way. c.l.p is a very kind place, >> but should somebody as naive as you wander into the rest of >> Usenet... well, I just don't like to think of what might >> happen. >> >> >> > Apparently it is not a matter of "smartly" but don't ask at all. > > I get the point, grief. Honey, you ain't seen grief! If you'd posted any *one* question like that on misc.fitness.weights, you'd have been drawn, quartered, tarred and feathered, hung out to dry, and THEN they would start getting mean! Seriously - the feedback you're getting from several posters is that you're welcome to ask questions, but you need to show that you've done some work first of your own - you need to show that you've put some thought and research into it before posting a question. Some are just laughing or teasing but several honestly trying to help you understand. Please, don't back off and avoid asking - just learn from the responses *how* to ask and *when* to ask (i.e, after you've done some research, reading to learn what you can on your own, and mebbe even tried something out and then come back and have us help you fix it so it works). Anna From claird at lairds.us Fri Oct 1 17:08:20 2004 From: claird at lairds.us (Cameron Laird) Date: Fri, 01 Oct 2004 21:08:20 GMT Subject: GUI development: Java vs. Python (was: Calling (C)Python code from Java: Is it JPype?) References: Message-ID: In article , Neil Benn wrote: . . . > As I remember, the OP said that he was going to use Java - the >GUI toolkit for that is very nice and extremely portable (no cross >platform niggling little issues 'the window doesn't behave that way on >linux - well it does on windows!!') - the reason for this - Java GUI >(Swing ignore AWT for the point of this - AWT has the same problems as >other native GUI toolkits) is _not_ native. Although I must agree that . . . Mr. Benn, you're saying something important here, but something which merits, at least, qualification. Certainly the Java com- munity has given considerable attention to the "write once, run everywhere" goal. My own experience has been that their success in regard to GUIs is mixed, at best. Maybe it would help to clarify a bit--*which* "GUI toolkit" do you have in mind? I *think* you're talking about Swing--is that right? My conclusion: while Java undeniably aspires to be portable in its GUI, those with a stake in the outcome need to specify clearly their requirements. Java does *not* currently provide perfect portability. From grante at visi.com Tue Oct 5 00:11:40 2004 From: grante at visi.com (Grant Edwards) Date: 05 Oct 2004 04:11:40 GMT Subject: New to Python: Features References: <4162142c$0$59860$a1866201@newsreader.visi.com> <4162185c$0$59860$a1866201@newsreader.visi.com> Message-ID: <41621efc$0$59533$a1866201@newsreader.visi.com> On 2004-10-05, Richard Blackwood wrote: >>>>>Hi, I'm new to Python and I'd like to know if Python has the following >>>>>support: *please answer to each individually, thanks* >>>>> >>>>Wow. Rude much? >>>> >>>>http://www.catb.org/~esr/faqs/smart-questions.html >>>>http://www.python.org/ >>>> >>>What does "Rude much" mean? >> >>You've _got_ to be kidding... > > I don't think that that is proper english. Oh. My. Gaawwwd! Which one, the "Rude much?" crack or the "You've got to be kidding..." crack? The latter isn't all that improper (especially not for Usenet). The former is colloqial US English. More specifically it's "Valley Speak" -- made popular outside "The Valley" by movies like "Valley Girl", "Mall Rats", "Heathers", and just about any John Hughes movie (especially Sixteen Candles). The first two are crap, but "Heathers" is a good movie, and I still like "Sixteen Candles". > Anyhow, I wasn't trying to muster up anything or annoy anyone. > My sincere apologies to all who were offended. Apology accepted on the condition that you read how-to-ask-smart-questions, and go browse around www.python.org for 15 minutes. -- Grant Edwards grante Yow! Uh-oh!! I forgot at to submit to COMPULSORY visi.com URINALYSIS! > Anyhow, I wasn't trying to muster up anything or annoy anyone. My > sincere apologies to all who were offended. -- Grant Edwards grante Yow! I would like to at urinate in an OVULAR, visi.com porcelain pool -- From nid_oizo at yahoo.com_remove_the_ Tue Oct 12 15:37:22 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 12 Oct 2004 15:37:22 -0400 Subject: Order in metaclass Message-ID: In the following example: class MyMetaclass(type): pass class MyBaseType(object): __metaclass__ = MyMetaclass class MyType(MyBaseType): x = 4 y = 5 z = 6 Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere? Thx and regards, Nicolas From aleaxit at yahoo.com Thu Oct 14 03:42:22 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 14 Oct 2004 09:42:22 +0200 Subject: sequence of objects References: Message-ID: <1glm5um.i9c2tj15atfjpN%aleaxit@yahoo.com> Neal D. Becker wrote: > What is the recommended way to create a sequence of objects? Assume the > objects have a default constructor: > > class X: > def __init__(self): > something > > This doesn't work: > a = 64*(X(),) > > This creates a tuple of 64 copies of a single identical object, not 64 > instances of X. > > I could create an empty list, then call append (X()) 64 times, but that's > not very eligant (or maybe efficient). Any suggestions? I suspect you can't do much better than a list comprehension: a = [X() for i in xrange(64)] A _little_ better, maybe, with itertools: import itertools as it a = [X() for i in it.repeat(0,64)] or even: a = list(it.starmap(X, it.repeat((), 64))) The itertools-based solutions DO go faster on my machine (at least with Python2.4): kallisti:~/cb alex$ python2.4 timeit.py -s'class X:pass' -s'import itertools as it' '[X() for i in xrange(64)]' 1000 loops, best of 3: 208 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'class X:pass' -s'import itertools as it' '[X() for i in it.repeat(0,64)]' 10000 loops, best of 3: 168 usec per loop kallisti:~/cb alex$ python2.4 timeit.py -s'class X:pass' -s'import itertools as it' 'list(it.starmap(X, it.repeat((), 64)))' 10000 loops, best of 3: 138 usec per loop However, unless you're really squeezed for cycles (which is why I'm doing the measurements with 2.4: if you ARE squeezed, upgrading to 2.4 and its generally better speed may be urgent for you), the simplicity of the list comprehension may probably be preferable to these speedups (at 20% or even 35%, they sure look yummy, but remember, this is with a class without even an __init__ -- add an __init__ doing any substantial work, and the relative % speedup will decrease). Alex From neil.benn at arcor.de Mon Oct 25 14:49:46 2004 From: neil.benn at arcor.de (Neil Benn) Date: Mon, 25 Oct 2004 20:49:46 +0200 Subject: what are the most popular building and packaging tools for python ?? In-Reply-To: <5a309bd30410250301b26f445@mail.gmail.com> References: <5a309bd30410250301b26f445@mail.gmail.com> Message-ID: <417D4ACA.3090409@arcor.de> Steve wrote: > > >(the suits are yet to be enlightened about >the benefits of OSS). > Hello, A word of warning, if you get a knowledgeable suit (hmm, I wear street clothes at work, does that make me a street!!) then they may start looking at reverse compilation. This is something it it possible to do in most 'bytecode' languages - other bytecode implementations (java, .NET) use 'obfuscators' that will make your code unreadable if someone tries to decompile it. To this end, I've not seen a python obfuscation tool - this is a real shame because it does mean I have to release my source code if I'm writing a commercial app. To my mind the 'make your client sign an agreement' policy doesn't always work, especially if I'm selling low value (sub $10K) tools where I don't want to go through the bother of waving a legal agreement under somebody's nose when I'm selling software (any more than a typical EULA) and I certainly wouldn't have the clout to enforce it! This includes the EULA as well so you basically need a good licence manager. As to why I wouldn't open source my code - well what I'm doing hasn't been done before in my industry - if I release source code then someone can lift the ideas out of my code or simply bypass the licence manager to install multiple clients for the cost of one. This means that I either have to write my licence manager in C or bridge out to another language. Before you ask - I buy my music!! If anyone has heard of an obfuscator for python bytecode - let me know please. Cheers, Neil From steve at holdenweb.com Thu Oct 21 19:36:34 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Oct 2004 19:36:34 -0400 Subject: Logging messages with dictionary args in Python 2.4b1 leads to exception In-Reply-To: <2e37dc1.0410201242.9bca574@posting.google.com> References: <8cf2994e.0410200246.64e9e910@posting.google.com> <2e37dc1.0410201242.9bca574@posting.google.com> Message-ID: Vinay Sajip wrote: >>I thought a logging API was usually trying to do costly things only when >>it knows it has to. You /could/ do that, but since it doesn't come for >>free - why not first do the check if you will actually log this message? > > > Right. > > >>I'd simply say that constructing a log message from arguments is such a >>common thing that it is worth providing efficient API support for it. And >>I think it's truely counter-pythonic to prevent the usage of dictionaries >>at this point. > > > Patch checked into CVS. Now: > > >>>>logging.warn('%(string)s and the %(number)d dwarves', {'string': > > 'Snow White', 'number':7}) > > gives > > WARNING:root:Snow White and the 7 dwarves > > Regards, > > > Vinay But how much simpler logging.want("%(string)s and the %(number)d dwarves", string="Snow White", number=7) seems (to me). Use kwargs! regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From adalke at mindspring.com Sun Oct 10 05:42:11 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 10 Oct 2004 09:42:11 GMT Subject: Why can't I xor strings? In-Reply-To: <416864b1$0$547$a1866201@newsreader.visi.com> References: <41683653$0$411$a1866201@newsreader.visi.com> <416864b1$0$547$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > What if you saw > > string1 xor string2? > > Wouldn't you expect it to be equivalent to > > (string1 and (not string2)) or ((not string1) and string2) I would expect it to give a syntax error. If not, and 'xor' did become a new boolean operator in Python I would expect it to act more like xor_f(x, y) where 'xor_f' the function is defined as def xor_f(x, y): x = bool(x) y = bool(y) return (x and not y) or (not x and y) Why the distinction? In your code you call bool on an object at least once and perhaps twice. The truth of an object should only be checked once. You also have asymmetric return values. Consider s1 s2 s1 xor s2 "A" "B" False "A" "" True "" "B" "B" "" "" False Esthetics suggest that either "A"/"" return "A" or that ""/"B" return True. Mine does the latter. Yours does neither. Probably the Pythonic way, assuming 'xor' can be considered Pythonic, is to return the object which gave the True value, like this def xor_f(x, y): bx = bool(x) by = bool(y) if bx: if not by: return bx return False else: if by: return by return False In any case, 'xor' the binary operator is rarely needed and as you've shown can be interpreted in a couple different ways. Each alone weighs against it. Both together make it almost certainly a bad idea for Python. Andrew dalke at dalkescientific.com From andreas at kostyrka.org Thu Oct 7 08:30:03 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 7 Oct 2004 14:30:03 +0200 Subject: End of file In-Reply-To: <1glag26.95flqcwuwn89N%aleaxit@yahoo.com> References: <6a13a506.0410062329.5de9e695@posting.google.com> <4164f407$0$5963$d4d0a361@news.speedlinq.nl> <1glag26.95flqcwuwn89N%aleaxit@yahoo.com> Message-ID: <20041007123003.GF17428@kostyrka.org> On Thu, Oct 07, 2004 at 01:38:43PM +0200, Alex Martelli wrote: > duikboot <"adijkstra at baanders NOSPAM consultancy.nl"> wrote: > > > Kat wrote: > > > Hi , > > > How do you identify the last line of a file? I am in a "for" loop and > > > need to know which is the last line of the file while it is being read > > > in this loop. > > > > > > Thanks > > > Kat > > > > f = open("test.txt").readlines() > > lines = len(f) > > print lines > > counter = 1 > > for line in f: > > if counter == lines: > > print "last line: %s" % line > > counter += 1 > > A slight variation on this idea is using the enumerate built-in rather > than maintaining the counter by hand. enumerate counts from 0, so: > > for counter, line in enumerate(f): > if counter == lines-1: is_last_line(line) > else: is_ordinary_line(line) > > If the file's possibly too big to read comfortably in memory, of course, > other suggestions based on generators &c are preferable. This should do it "right": f = file("/etc/passwd") fi = iter(f) def inext(i): try: return i.next() except StopIteration: return StopIteration next = inext(fi) while next <> StopIteration: line = next next = inext(fi) if next == StopIteration: print "LAST USER", line.rstrip() else: print "NOT LAST", line.rstrip() From onurb at xiludom.gro Sat Oct 9 09:55:34 2004 From: onurb at xiludom.gro (bruno modulix) Date: Sat, 09 Oct 2004 15:55:34 +0200 Subject: class constructors: class vs. instance defaults In-Reply-To: <416472df@nntp.zianet.com> References: <416472df@nntp.zianet.com> Message-ID: <4167ef81$0$22563$636a15ce@news.free.fr> Erik Johnson wellkeeper a ?crit : > I am rather new to Python and still learning the finer points. I wanted > to have a class which has a member dictionary of other class instances, a > constructor that would initiate that dict with an empty dict if you didn't > provide one, and a member function to stick more other classes into that > dictionary. > > I wrote something akin to this: > > #! /usr/bin/python > > #======================================================================= > class Bar: > > def __init__(self, foo_d={}): > self.foo_d = foo_d Woops ! What this does is probably not what you'd think, and I guess that you will complain that all instances of Bar share the same dict... > def add_foo(self, foo): > self.foo_d[foo.key] = foo > #======================================================================= > > > #======================================================================= > class Foo: > pass > #======================================================================= > > > You might be surprised to find out that all the Bar objects end up > sharing the same foo_d dictionary. Bingo !-) > I certainly was. I'm not. But I certainly was first time I stumbled upon this !-) This is a FAQ. The correct idiom is : class Bar: def __init__(self, foo_d=None): if foo_d is None: self.foo_d = {} else : self.foo_d = foo_d > A single, shared dictionary is definitely not what I wanted or expected > and didn't see why it was happening. So... I struggled with that for a > while and eventually reasoned that the {} in the argument list to my > constructor is executed at the time of class definition, Exactly. > and is essentially > a reference to an instantiated dictionary object and therefor there is a > little empty dictionary sitting in memory somewhere prior to me ever > instantiating a Bar object. New Bar objects constructed without providing > their own foo_d end up sharing that one. I think this makes sense enough, > now (if I'm missing something, speak up). > So, one work-around is to do this: > > #======================================================================= > class Bar: > > def __init__(self, foo_d=None) > if foo_d: > self.foo_d = foo_d > else: > self.foo_d = {} You've almost got it. You just want to test against None, not again False, since an empty dict evaluate to False in a boolean test. Python 2.3.3 (#2, Feb 17 2004, 11:45:40) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d = {} >>> if d: ... print "d" ... else: ... print "woops" ... woops >>> d is None False > This works. No. There's still a bug, but more subtle. Guess what will happen if you try something like : >>> b1 = Bar() >>> b2 = Bar(b1.foo_d) >>> b1.foo_d['foo1'] = Foo() >>> b2.foo_d['foo1'] > I reasoned that, unlike above, the {} in this definition is > not executed until a Bar object is instantiated. But there is a little voice > in my head saying "This is clunky. There must be some smarter, more Pythonic > way to do this sort of default handling without ending up with a single > shared object" (snip) > So... Yes? Is there a better way to do this sort of thing, or is that > perfectly reasonable code? For mutable default args, testing against None is the default pythonic way. Now there are a lot of tricks when it comes to dynamically doing thing with Python, and you will probably discover'em sooner or later. The python cookbook at o'reilly.com may be a good starting point, even if some recipes are somewhat out of date. > Thanks for taking the time to read my post! :) You're welcome. From deets.nospaaam at web.de Tue Oct 5 13:07:17 2004 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Tue, 05 Oct 2004 19:07:17 +0200 Subject: XML and UnicodeError References: <5339b60d.0410050013.6bbc673d@posting.google.com> Message-ID: <2sg2hcF1ku1t8U1@uni-berlin.de> Just for the record: Don't confuse unicode with utf-8 - the former beeing a specification of more or less all characters used on this planet, the latter an actual encoding of these that maps common ascii characters to their well-known values and has escapes defined to encode all others, like umlauts. So u'some text' is not UTF-8 - its a unicode object. If you do this: u'some text'.encode('utf-8') it becomes a binary string which is encoded using utf-8. Specifying the coding of the python file using the # -*- encoding: iso-8859-1 -*- syntax means that found in u'' are interpreted using the latin1-codec - so u'' is a shorthand for 'some-text'.decode('iso-8859-1') Regards, diez From fluxent at yahoo.com Fri Oct 29 17:43:06 2004 From: fluxent at yahoo.com (Bill Seitz) Date: 29 Oct 2004 14:43:06 -0700 Subject: using old timeout_socket with UDP Message-ID: I need to send some messages with UDP, using a version of Python pre-2.3, but with some control over timeout period. I've been pointed at http://www.python.or.kr/pykug/timeoutsocket I tweaked its line 142 to import SOCK_DGRAM from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM Then my main function calls timeoutsocket.setDefaultSocketTimeout(5) and later uSock = timeoutsocket.timeoutsocket(timeoutsocket.AF_INET,timeoutsocket.SOCK_DGRAM) Does that make sense? From bokr at oz.net Wed Oct 13 05:39:36 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Oct 2004 09:39:36 GMT Subject: Order in metaclass References: Message-ID: <416cf48f.140377111@news.oz.net> On Wed, 13 Oct 2004 09:04:03 +0200, Peter Otten <__peter__ at web.de> wrote: >Nicolas Fleury wrote: > >> In the following example: >> >> class MyMetaclass(type): pass >> class MyBaseType(object): __metaclass__ = MyMetaclass >> class MyType(MyBaseType): >> x = 4 >> y = 5 >> z = 6 >> >> Is there any way to modify MyMetaclass to keep the order of x,y,z >> somewhere? > >If you want to record the order of these definitions, you need to pass a >custom dictionary that keeps track of assignments in the class generation >code (basically a normal python function comprising the class suite). >Unfortunately that dictionary - which you see later as the classdict >parameter of the metaclass __new__() method - is always a dict created in C, >as was recently discussed on c.l.py (sorry, but all keywords I remember are >'metaclass' and 'martelli' - not very selective :-). Below is my (clumsy) >attempt for a workaround: > >import itertools > >class OrderedValue(object): > newIndex = itertools.count(1).next > def __init__(self, value): > self.value = value > self.index = self.newIndex() > >class Meta(type): > def __new__(mcl, name, bases, classdict): > assert "ordered_names" not in classdict > > values = [] > for (n, v) in classdict.iteritems(): > try: > v, i = v.value, v.index > except AttributeError: > pass > else: > values.append((i, n, v)) > values.sort() > > ordered_names = [] > for (i, n, v) in values: > ordered_names.append(n) > classdict[n] = v > classdict["ordered_names"] = ordered_names > > return type.__new__(mcl, name, bases, classdict) > > >class Base: > __metaclass__ = Meta > >class Demo(Base): > alpha = 0 > beta = OrderedValue(1) > gamma = OrderedValue(17) > delta = OrderedValue(3) > >print Demo.ordered_names >print Demo.alpha, Demo.beta > Or, an ugly hack that might work for a while, depending on how co_names is really generated. It seems in order of occurrence (including right hand sides of assignment, but still top down) ... >>> import sys >>> def getnames(): return sys._getframe(1).f_code.co_names ... >>> def MC(cname, cbases, cdict): ... names = cdict.get('ordic',[]) ... names = [name for name in names if name in cdict] ... cdict['ordic'] = dict([(name,i) for i,name in enumerate(names)]) ... return type(cname, cbases, cdict) ... >>> class C(object): ... __metaclass__ = MC # really a function shortcut ... x = 123 ... y = sys ... z = 0 ... ordic = getnames() ... >>> C.ordic {'ordic': 5, '__module__': 0, '__metaclass__': 1, 'y': 3, 'x': 2, 'z': 4} >>> class D(object): ... __metaclass__ = MC # really a function shortcut ... x = 123 ... def m(self): pass ... def sm(): print getnames() ... sm = staticmethod(sm) ... ordic = getnames() ... >>> D.ordic {'ordic': 5, '__module__': 0, '__metaclass__': 1, 'm': 3, 'sm': 4, 'x': 2} >>> D.sm >>> D.sm() ('getnames',) Regards, Bengt Richter From redhog at takeit.se Mon Oct 11 12:17:07 2004 From: redhog at takeit.se (Egil M?ller) Date: 11 Oct 2004 09:17:07 -0700 Subject: Fatal error: GC object already tracked Message-ID: I'm developing a larger Python program, and one component (a text parser for a networking protocol) happend to be terribly slow, while quite a simple piece of code, so I decided to reimplement it in C. However, my code seems to do something in err, since the program semi-randomly locks somewhere outside my C-code (after returning to python), and semi-randomly issues a "Fatal error: GC object already tracked". As this is my first C-module ever, nearly straight from the HOWTO, I don't have much clue as to what is really wrong with my code... The code is available for inspection at http://grimoire.takeit.se/files/CReader.c, and the error happens at line 1111 in that file... TIA /Egil From mwh at python.net Thu Oct 14 10:57:45 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Oct 2004 14:57:45 GMT Subject: Compiled Byte code References: <1097675350.5192.206374341@webmail.messagingengine.com> Message-ID: Cliff Wells writes: > On Wed, 2004-10-13 at 19:19 +0530, Soumitri wrote: > > Hi, > > > > Is there a dependency of version or platform for running a snippet of > > python compiled code? I have a .pyc (possibly created on a *nix box) > > that was created off ver 1.5.2 and returns a "Bad Magic Number in .pyc > > file" error when i run a box with XP and Python 2.3. > > IIRC, I believe bytecode (pyc files), while mostly portable across > platforms (I've used the same pyc files on Linux and Windows) Uh, *entirely* portable, I hope, or you've found a bug :-). Oh, well, you might get into trouble with things like floating point constants that turn out to be NaNs (e.g. 1e3000). But you'll have trouble with those even without moving .pycs between platforms. And floating point numbers in general might be problematical if the libc on the generating platform really sucks. Err, yeah, mostly portable :-) > aren't portable across major versions of Python. To be clearer, major version in this sense means that bytecode for 2.X is not guaranteed to (and in practice, won't) run on 2.Y, but bytecode for 2.X.Y *will* run on 2.X.Z. Cheers, mwh -- > Well, as an American citizen I hope that the EU tells the MPAA > and RIAA to shove it where the Sun don't shine. Actually they already did. Only first they bent over and dropped their trousers. -- Shmuel (Seymour J.) Metz & Toni Lassila, asr From tim.peters at gmail.com Sun Oct 17 13:34:43 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 17 Oct 2004 13:34:43 -0400 Subject: md5 and large files In-Reply-To: <4172AA52.9030606@vt.edu> References: <4172a5f6$0$28202$9b622d9e@news.freenet.de> <4172AA52.9030606@vt.edu> Message-ID: <1f7befae041017103471925b71@mail.gmail.com> [Brad Tilley] > I would like to verify that the files are not corrupt so what's the most > efficient way to calculate md5 sums on 4GB files? The machine doing the > calculations is a small desktop with 256MB of RAM. You'll find md5sum.py in your Python distribution. It reads 8KB at a time, so requires little RAM regardless of file size. You can use it directly, or copy the small calculation loop into your program. Note that reading 4GB of data will take significant time no matter what you do. From rganesan at myrealbox.com Fri Oct 29 02:28:52 2004 From: rganesan at myrealbox.com (Ganesan R) Date: 29 Oct 2004 11:58:52 +0530 Subject: ctypes 0.9.2 released References: Message-ID: >>>>> "Thomas" == Thomas Heller writes: > Future plans > The ultimate purpose of the 0.9 release series is to shake out the > remaining bugs, especially on platforms I have no access to, and > to target a rock stable ctypes 1.0 release. > When ctypes 1.0 is released, the com framework will be split off > into a separate framework named 'comtypes'. Congratulations! I maintain ctypes for debian. I am holding off uploading the 0.9 versions because they don't support Python 2.2. A Python 2.2 package was present in debian for ctypes 0.6.2, I want to be sure that no one is using it before uploading 0.9.x. That aside, I am wondering if it isn't time to push ctypes for inclusion into the standard Python distribution. Too late for Python 2.4, but how about Python 2.5? Ganesan From jerf at jerf.org Mon Oct 11 17:29:31 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 11 Oct 2004 21:29:31 GMT Subject: Why can't I xor strings? References: <41683653$0$411$a1866201@newsreader.visi.com> <416864b1$0$547$a1866201@newsreader.visi.com> <41695598$0$534$a1866201@newsreader.visi.com> <4169982d.4238722751@news.oz.net> <4169c7ad.4250882926@news.oz.net> <416a0afc$0$5686$a1866201@newsreader.visi.com> <416ae09b$0$5691$a1866201@newsreader.visi.com> Message-ID: On Mon, 11 Oct 2004 19:35:55 +0000, Grant Edwards wrote: > I don't know what you mean. Two's compliment, one's > compliment, signed-magnitude, and excess-N _all_ use a single > bit for sign. I meant a single bit exclusively for sign, such that 1 00001001 and 0 00001001 are the same absolute value. The complements don't work that way. I guess that does leave a question for whether 1 is positive or negative, but for the purposes of my point, that doesn't matter much. From bokr at oz.net Mon Oct 11 00:51:28 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Oct 2004 04:51:28 GMT Subject: End of file References: <6a13a506.0410062329.5de9e695@posting.google.com> <1glatop.p9hsopf3b9m4N%aleaxit@yahoo.com> <2sucjlF1p5plpU1@uni-berlin.de> Message-ID: <416a09c4.4267802054@news.oz.net> On Mon, 11 Oct 2004 16:22:28 +1300, Greg Ewing wrote: >Alex Martelli wrote: >> Since an immediate instance of type object has no possible use except as >> a unique, distinguishable placeholder, > >That's not true -- you can also assign attributes to such >an object and use it as a record. (It's not a common use, >but it's a *possible* use!) > I originally thought that too, but (is this a 2.3.2 bug?): Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> obj = object() >>> obj.x = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'x' >>> dir(obj) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', ' __reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] >>> type(obj) >>> obj __setattr__ is there, so how does one make it do something useful? OTOH, making a thing to hang attributes on is a one liner (though if you want more than one instance, class Record: pass; rec=Record() is probably better. why is class apparently not legal as a simple statement terminated by ';' ? (I wanted to attempt an alternate one-liner ;-) >>> class Record:pass; rec=Record() ... Traceback (most recent call last): File "", line 1, in ? File "", line 1, in Record NameError: name 'Record' is not defined >>> class Record:pass ... >>> rec=Record() >>> rec = type('Record',(),{})() >>> rec.x=1 >>> vars(rec) {'x': 1} >>> type(rec) >>> rec <__main__.Record object at 0x00901110> Regards, Bengt Richter From franz.steinhaeusler at utanet.at Fri Oct 8 06:46:49 2004 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Fri, 08 Oct 2004 12:46:49 +0200 Subject: Country specific date format Message-ID: Hello, with following function, i get a human readable date/time format. mtime = time.strftime(self.timeformat ,time.localtime(st.st_mtime)) However is there a simple solution to get a country specific format: for example 10/08/2004 and for German: 08.10.2004 I looked in locale class, but I didn't get more wise. Thank you in advance, -- Franz Steinhaeusler From fredrik at pythonware.com Tue Oct 12 15:02:53 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Oct 2004 21:02:53 +0200 Subject: Using os.system() and string concatenation References: <7a2229ee041012114353157c1d@mail.gmail.com> Message-ID: Wayne Witzel III wrote: > Currently I process three files and build the output of those files in > to lists using for statements. > > I think take those lists and provide them to an os.system() call. > > cmd = "/usr/sbin/useradd" > os.system(cmd + list1[0] + list1[1] + list2[0] + list3[0]) > > This executes without any errors, but doesn't execute the command > supplied to os.system(). Now if I place them all in cmd first, then > supply it to os.system() it executes just fine. So there really isn't > a problem, just wanting to know what would cause such behavior. the + sign doesn't add a space, so you're probably trying to execute "/usr/sbin/useraddsomethingsomethingsomethingsomething" instead of "/usr/sbin/useradd something something something something". From aleaxit at yahoo.com Tue Oct 12 03:17:12 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 12 Oct 2004 09:17:12 +0200 Subject: Country specific date format References: <1yhad.18386$b5.906421@news3.tin.it> Message-ID: <1glijqw.1fgyc7q151ti5aN%aleaxit@yahoo.com> Franz Steinhaeusler wrote: ... > >I would look at dateutil. It has some pretty nifty stuff for handling > >timezones and locale-specific date issues... > > > >HTH > >Anna > > Hello, > > thanks, > > did you mean "datetime" instead of "dateutil". > (I couldn't find a dateutil) (Hmmm, I'd better try to answer for her, she's flying USwards right now and I'm not sure how good her newsgroup access will be for a while...!) I think she really meant dateutil -- a wonderful 3rd party extension. Google for it... it IS worth it (IMHO, and I believe in Anna's too:-). Alex From jerf at jerf.org Thu Oct 21 20:12:05 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 22 Oct 2004 00:12:05 GMT Subject: Python and generic programming References: <1gm17og.ctwoqv17vkctxN%aleaxit@yahoo.com> Message-ID: On Fri, 22 Oct 2004 00:25:28 +0200, Alex Martelli wrote: > Roman Suzi wrote: > >> I wonder, does Python support generic programming paradigm, and to what extent > > It appears to me to support generics at least as well as C++ does. I > just write normal code (no typechecks) and voila, the equivalent of C++ > templates (at least). What do you think is missing? The handcuffs. From pierre.barbier at cirad.fr Fri Oct 29 13:26:12 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 29 Oct 2004 19:26:12 +0200 Subject: Interface of the set classes In-Reply-To: References: <41824654$0$1779$636a15ce@news.free.fr> Message-ID: <41827d0b$0$313$636a15ce@news.free.fr> Steven Bethard a ?crit : > Pierre Barbier de Reuille cirad.fr> writes: > >>For me, sets are first sequences. I use set where lists are inefficient >>or inadapted, for example when I need to remove redundancy and that I >>don't care about the positions of my elements. > > > If you still need a fixed ordering after removing duplicates, why don't you just > revert to a list? I don't _need_ __getitem__ for itself. I need it because I don't know how to iterate over a list and store the current position for future use. If I really need to access a given element by position, obviously, set would not be the right container. But the sets as they are implemented now only allows simple traversal, and that's not acceptable for lots of algorithms (or at the cost of complexity and complexity in Python becomes quickly critical because iterating is a slow operation). > > >>>>l = [11, 1, 2, 2, 3, 5, 11, 3, 7, 5] >>>>list(set(l)) > > [1, 2, 3, 5, 7, 11] > >>>>d = list(set(l)) >>>>d[3] > > 5 > > Of course, if you want to maintain the order that items are inserted, you can > easily do this manually: > > >>>>class orderedset(set): > > ... def __init__(self, seq): > ... super(set, self).__init__() > ... self._items = [] > ... for item in seq: > ... self.add(item) > ... def add(self, item): > ... if item not in self: > ... self._items.append(item) > ... set.add(self, item) > ... def __iter__(self): > ... return iter(self._items) > ... def __getitem__(self, i): > ... return self._items[i] > ... > >>>>list(orderedset([11, 1, 2, 2, 3, 5, 11, 3, 7, 5])) > > [11, 1, 2, 3, 5, 7] > >>>>orderedset([11, 1, 2, 2, 3, 5, 11, 3, 7, 5])[2:4] > > [2, 3] > > And, while you're writing your own class to do this, you can change your method > names to append, etc. if you like. =) > > The point here, I guess, is that the uses you intend for sets probably do not > align so well with the uses everyone else has for sets. Personally, I don't > expect any ordering in a set, and if I need such ordering I convert back to a > list. I also almost never use the lst[x] syntax, preferring in general to just > iterate with a for-loop (or list comprehension, or generator expression...) If > you find you do need the lst[x] syntax all the time, first, I'd double-check to > see if I couldn't write things better with a for-loop, and then, if I was still > pretty sure I couldn't, I'd write my orderedset class as above... > > Steve > I agree, I can always create my own structure (and that's what I did in exporting the STL set and hash_set) but I feel it's a shame to do so when the builtin structure has all the needed characteristic, but my algorithm cannot use it without a complete rewritting (and debugging ...) Pierre From duncan.booth at invalid.invalid Wed Oct 13 10:03:37 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Oct 2004 14:03:37 GMT Subject: locks References: Message-ID: Cliff Wells wrote: > I'm no expert at dis nor Python bytecode, but I'll give it a shot :) > >>>> l = [] >>>> dis.dis(l.append(1)) > 134 0 LOAD_GLOBAL 0 (findlabels) > 3 LOAD_FAST 0 (code) > 6 CALL_FUNCTION 1 > 9 STORE_FAST 5 (labels) > > > ... > > ... > > 172 >> 503 PRINT_NEWLINE > 504 JUMP_ABSOLUTE 33 > >> 507 POP_TOP > 508 POP_BLOCK > >> 509 LOAD_CONST 0 (None) > 512 RETURN_VALUE >>>> > > > It looks fairly non-atomic to me. The append method of a list returns None. dis.dis(None) disassembles the code from the last traceback object, nothing at all to do with your l.append(1) code. Try this instead: >>> def f(): l.append(1) >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (l) 3 LOAD_ATTR 1 (append) 6 LOAD_CONST 1 (1) 9 CALL_FUNCTION 1 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE From claird at lairds.us Fri Oct 29 00:08:06 2004 From: claird at lairds.us (Cameron Laird) Date: Fri, 29 Oct 2004 04:08:06 GMT Subject: scripting languages vs statically compiled ones References: <3064b51d.0410280904.55f2fa4@posting.google.com> Message-ID: <5dr852-obu.ln1@lairds.us> In article , Richard Blackwood wrote: . . . >Is Python not bytecode interpreted? It has no JIT with the standard >distro but otherwise, it is no less byte-code than Java. Misleading. . . . Like many propositions in this thread, this one bears repetition and examination. Even people in authority reiterate that "Java is compiled, while Python is interpreted." Outsiders are going to hear this said by people who appear to be speaking truthfully. It's at best misleading, of course, as Mr. Blackwood recognizes. There ought to be a way to armor the innocent against it ... From mcfletch at rogers.com Tue Oct 12 11:29:57 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 12 Oct 2004 11:29:57 -0400 Subject: How to: get list of modules in a package In-Reply-To: References: <4OudnSEQhLvFyfbcRVn-pg@rogers.com> Message-ID: <416BF875.9050401@rogers.com> Peter L Hansen wrote: ... > Given the dynamic nature of Python, I doubt that's easy to do. > I'm not sure even os.listdir(), for example, can be relied on, > given that you can import modules from zip files, or if the > import hook is used, even from remote locations or, presumably > (though I haven't seen it done yet), from "thin air" where > the module is generated dynamically. I used to do this somewhere in mcf.vrml (old VRML97 processing package). The idea was to generate a module to hold classes which were also generated on-the-fly (from VRML97 prototypes). You could then import the classes from the non-existent module as long as the module itself (which roughly corresponded to a VRML97 file) was part of your pickle. The package holding those modules was empty until such time as you either generated one of those modules or loaded one from a pickle, and there was just no reasonable way to know what would eventually show up there. Advances in Python (and my moving away from my perverse love of such tricks ;) ) made that particular usage obsolete, but it definitely has been done in the past... Enjoy, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From steve_erickson at hotmail.com Thu Oct 14 08:01:48 2004 From: steve_erickson at hotmail.com (Steve Erickson) Date: 14 Oct 2004 05:01:48 -0700 Subject: Problem with logging module References: <78406811.0410130851.5cf73a75@posting.google.com> Message-ID: <78406811.0410140401.4d466185@posting.google.com> "Diez B. Roggisch" wrote in message news:... > > self.logger = logging.getLogger(name) > > self.logger.propagate = False > > handler = logging.FileHandler(dir + '/' + name + '.log') > > self.logger.addHandler(handler) > ^^^^ > Thats your problem - only set the handler once for the runtime of your > program. Thanks. Coming from C++, I thought that the local logger instance in each test method would go away when I went out of the context of the method. Sounds like the logging class in Python maintains artifacts that affect instantiations in other methods. Or maybe I'm confused about how Python handles local versus class variables. From matt.price at utoronto.ca Thu Oct 28 17:38:07 2004 From: matt.price at utoronto.ca (Matt Price) Date: Thu, 28 Oct 2004 17:38:07 -0400 Subject: moving files across devices Message-ID: <20041028213807.GA8036@utoronto.ca> Hi folks, I'm trying to move files across devices on my linux box. Here's what I had: os.rename(sFileName, dir + newName) which gives: Traceback (most recent call last): File "/usr/local/scripts/sort_mp3s.py", line 68, in ? localSort(i, defaultSaveDir) File "/usr/local/scripts/sort_mp3s.py", line 34, in localSort os.rename(sFileName, dir + newName) OSError: [Errno 18] Invalid cross-device link ok, so that doesn't work. is there another method? thx, matt ------------------------------------------- Matt Price matt.price at utoronto.ca History Department, University of Toronto (416) 978-2094 -------------------------------------------- please don't use the following addresses: zeus at derailleur.org aardvark at derailleur.org From donn at drizzle.com Fri Oct 29 23:54:51 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 30 Oct 2004 03:54:51 -0000 Subject: (python), uid 80: exited on signal 11 References: Message-ID: <1099108489.859673@yasure> Quoth Andrew MacIntyre : | On Thu, 28 Oct 2004, Ksenia Marasanova wrote: | |> But I am just curious what that signal 11 means. | | Near as I can figure (on FreeBSD 4.8), signal 11 is SEGV (segment | violation). | | Did you test the scripts outside the Apache environment? On the face of | your description, I'd have to say that one of the modules you've added to | the scripts has a build problem of one sort or another... If I remember right, the problem seemed to be associated with a (C) db module. "Python" programs should be pretty safe from memory access errors like that, but of course a C module is not safe at all. Could be a build problem, I guess, but I think more likely some parameter isn't checked properly and when called in an invalid or unexpected way, that function crashes. The "kill -l" shell command enumerates the signals, in order starting with SIGHUP == 1 (or some versions show the number too.) They're fairly standardized up to SIGUSR2. Donn Cave, donn at drizzle.com From heuer at quixs.com Tue Oct 26 11:59:09 2004 From: heuer at quixs.com (Lars Heuer) Date: Tue, 26 Oct 2004 17:59:09 +0200 Subject: Python Webshop? Message-ID: <41383863.20041026175909@quixs.com> Hi all, I wonder if there's a OpenSource Python web shop? While every PHP programmer seems to have written her own shop, my searches for web shop based on Python are not every fruitful. Would be nice if the shop would not require Zope. Best regards, Lars From anna at aleax.it Mon Oct 4 12:40:49 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Mon, 04 Oct 2004 16:40:49 GMT Subject: metaclass and customization with parameters In-Reply-To: <1gl55lu.yovfmt1kquac3N%aleaxit@yahoo.com> References: <3b59a80.0410021910.17b31c29@posting.google.com> <1gl3wcp.15oxvkd1jdp8dbN%aleaxit@yahoo.com> <4edc17eb.0410040223.4aa4f24b@posting.google.com> <1gl55lu.yovfmt1kquac3N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Carlos Ribeiro wrote: >>Figuring out the obvious tend to be a big barrier to the learning >>process. For experienced writers, it tends to be a problem also, >>because it's so obvious that one feels compelled to leave it out of >>the explanation. But that's the issue here -- the fact that what I'm >>freely calling 'class declarations' in Python are not really >>declarations (in the same sense of C++, for example), are just > > > Well, _this_ experienced writer keeps repeating this fact over and over > and over again in _his_ explanations (e.g., Nutshell p. 32: "Unlike > other languages, Python has no declarations"), but of course that > doesn't help all that much if one's explanations just aren't read. > > Some simple google search such as: > mages&ie=UTF-8&as_ugroup=comp.lang.python&as_uauthors=martelli&lr=&num=2 > 0&hl=en> > can further show you that I _ceaselessly_ keep repeating this... > *hundreds* of times...: "def is not a declaration: it's an executable > statement", "Python has no declarations", "For that, you'd need some > kind of declaration. Python does not have declarations", "Right, since > we have no declarations." -- over and over and OVER again. And there > are just snippets readable in the short google summaries of the FIRST > page out of 351 hits. > > So, for once, it seems to me that, on this specific subject at least, I > should be held blameless: far from feeling compelled to leave it out, I > am _obsessive_ about pointing it out again and again and AGAIN. I don't > think I can do much more to get the point across that "*Python has no > declarations, only executable statements*", except maybe personally seek > out every poster who speaks of "declarations in Python", grab them by > their lapels and shout the truth out in their faces. Sorry, I get too > many frequent flier miles as it, without adding all of these side trips > too. If (at least some) experienced writers are doing the best they > possibly can to get this crucial point across, and some readers still > just can't get it no matter what, perhaps it's not all that useful to > blame the writers -- and the READERS should perhaps take SOME > responsibility for listening to the unceasing repetitions in > question...?! Being completely unbiased, of course, I will say that you do a damn fine job of mostly avoiding the "expert's error" of leaving out the "obvious" stuff. Anna From exarkun at divmod.com Thu Oct 14 14:42:17 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Thu, 14 Oct 2004 18:42:17 GMT Subject: get list of callable methods In-Reply-To: Message-ID: <20041014184217.24030.951151985.divmod.quotient.476@ohm> On Thu, 14 Oct 2004 12:46:15 -0500, John Hunter wrote: > > What is the best way to get a list of all functions actually defined > in a module, ignoring those functions that the module may have > imported but not defined? > > The following gets a list of all the callables, but includes functions > that some.module imports > > funcs = [] > for o in dir(some.module): > if o.startswith('_'): continue > p = getattr(some.module, o) > if not callable(p): continue > funcs.append(p) > __all__ is the best indicator. Since not all modules define it, though, inspect.getsourcefile() is a reasonable fallback to filter things based on the file of their definition. Jp From jerf at jerf.org Thu Oct 28 23:01:10 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 29 Oct 2004 03:01:10 GMT Subject: P2P framework References: <4180f21f$0$43632$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: On Thu, 28 Oct 2004 14:21:03 +0100, Boria Feigin wrote: > Hi All, > > I am looking for a networking (p2p, if you like) framework with Python > bindings. Requirements are very basic - a node should be able to: > o join/leave the network (perhaps with some auth. mechanism, but not > essential at this stage) > o broadcast a message to other nodes > o communicate with another node on the network If you want a relatively small number of nodes, Jabber might work here. "Broadcasting" would be by creating "chat rooms", then all messages sent to the address representing the chat room go to all members. This will eventually bog down if you have too many entities in that room. Communication with other entities is straighforward; to shuffle around large hunks of data use Out Of Band connections (i.e., you set up a direct socket). From macrocosm at fastmail.fm Fri Oct 8 11:13:12 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Fri, 08 Oct 2004 11:13:12 -0400 Subject: ann: Pysch, Scheme runtime environment in Python In-Reply-To: References: <1e015c2a.0410070804.6e84016d@posting.google.com> Message-ID: <4166AE88.2090006@fastmail.fm> David Rush wrote: >olepar at gmail.com (Oleg Paraschenko) writes: > > >>Pysch: >>http://pysch.sourceforge.net/ >> >>Pysch relies on Bigloo to preprocess a source code of >>Scheme programs (expand macros) and to save the result >>as XML. Pysch interprets only the refined XML. >> >> > >This should get listed as the most bizarre implementation methodolgy >ever adopted. I think you have definitively showed the equivalence >between s-exprs and XML, if nothing else. > >And for the tone-of-voice challenged, I do not intend to convey >sarcasm. Rather I am amazed that such an approach works well >enough to: > > > >>Pysch supports only a subset of the Scheme functions >>library. Anyway, the subset is big enough to run >>SXPath and SXSLT code. >> >> > >How fast? > >david rush > > If you had checked the website you would know the answer. It is stated clearly on the website that it is VERY slow, primarily for research, and therefore not for production purposes. From andymac at bullseye.apana.org.au Wed Oct 13 07:49:48 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 13 Oct 2004 21:49:48 +1000 (EST) Subject: passing a socket to a spawned process. In-Reply-To: <1glkjad.ckwu451mkf5mxN%aleaxit@yahoo.com> References: <5d00592f.0410110923.2bb2b1ea@posting.google.com> <1glkjad.ckwu451mkf5mxN%aleaxit@yahoo.com> Message-ID: <20041013214008.S59890@bullseye.apana.org.au> On Wed, 13 Oct 2004, Alex Martelli wrote: > Marcos Dione wrote: > > > On Mon, Oct 11, 2004 at 10:23:27AM -0700, Mike M wrote: > > > Is it possible? In the parent process, I have a socket that binds, > > > listens and then accepts new connections (which creates new sockets in > > > the process). I want to be able to pass some of these new sockets to > > > a spawned process. Is it possible, and if so how? > > > > just accept() before fork()'ing. the socket will be cloned. then close the > > socket on the parent, unless needed. > > Unfortunately I believe that's platform-dependent. Specifically: your > suggestion should work on any sensible operating system... BUT a tad > over 50% of Python programs are estimated to run on Windows, and, on > THAT platform, I know your idea can't work (no fork!) and I don't know > how to answer the OP's question (except by suggesting he move, if > feasible, to any sensible platform -- any BUT Wind0ws...!-). I've not tried this on Windows, but on OS/2 using the native sockets (which is close to the Windows socket model as far as I can tell) you have to pass the socket handle (an integer) to the child (usually via the command line), which then attaches to the socket, and signals the parent that it can close its reference to the socket. The EMX (OS/2, Win32) and Cygwin (Win32) runtime environments synthesize fork() and socket inheritance over the native environment, though at a significant cost in run time and resources. ------------------------------------------------------------------------- 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 danperl at rogers.com Wed Oct 6 19:21:00 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 6 Oct 2004 19:21:00 -0400 Subject: class constructors: class vs. instance defaults References: <416472df@nntp.zianet.com> Message-ID: Yes, that's right! I didn't try it in the context of a function definition and thus I only checked that the dict({}) makes a different copy each time. I realize now that what happens is that there is now still a 'd' object (only in the context of the function) and it is shared by every instance. The more I think about it, that's the way it's supposed to work, the default value for the argument is calculated only once, when the function is defined, no matter how that calculation is made. Dan "Michael Hoffman" wrote in message news:ck1trn$r46$1 at gemini.csx.cam.ac.uk... > Dan Perl wrote: > >> I think that a more "pythonic" way to implement your class is with a >> change in the definition of your __init__: >> def __init__(self, foo_d=dict({})): >> This will create a separate copy for each one of your class instances >> instead of the common object that you are creating in the definition of >> the function. > > Actually it does exactly what the original code did . > > >>> def x(d=dict({})): return d > ... > >>> a = x() > >>> b = x() > >>> a > {} > >>> b > {} > >>> a[3] = 4 > >>> b > {3: 4} > > Taking out the {} doesn't help either. > -- > Michael Hoffman From cmedcoff at hotmail.com Wed Oct 6 22:10:02 2004 From: cmedcoff at hotmail.com (Chuck) Date: Wed, 6 Oct 2004 22:10:02 -0400 Subject: logging question References: <10m9743ahe15012@corp.supernews.com> Message-ID: > Each logger can have multiple handlers attached to it, with each of the > handlers having their own threshold. You can easily create a file > handler, a stream (stdout) handler, and an email handler, all attached > to your (root) logger. Any logged messages should go to all of the > attached handlers. But if you, for example, give the email handler a > threshold of 'critical', then 'info' and 'error' messages will go to the > file and to stdout but won't get emailed. Go it... import logging log = logging.getLogger("app.log") fmt = logging.Formatter('%(asctime)s %(levelname)s %(message)s') h1 = logging.StreamHandler() h1.setFormatter(fmt) h2 = logging.FileHandler('.//app.log') h2.setFormatter(fmt) log.addHandler(h1) log.addHandler(h2) From p at ulmcnett.com Mon Oct 4 17:40:59 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 4 Oct 2004 14:40:59 -0700 Subject: wxPython - problem dynamically adding widgets? In-Reply-To: <37f621d3.0410041214.305eb3e9@posting.google.com> References: <37f621d3.0410041214.305eb3e9@posting.google.com> Message-ID: <200410041440.59722.p@ulmcnett.com> Fazan writes: > The sizer approach seems pretty straightforward but I can't > figure out why the app always locks up. Anyone have ideas > about how to solve this? TIA You should really post your question on the wxPython-users list, which is at: http://www.wxpython.org/maillist.php And in order to solve your problem, you're really going to need to show us some code: what have you tried? As a hunch, I'm guessing that you are adding your windows to the sizer but not to a real parent window. A sizer isn't a window, it is just an object. A window, such as a grid or a textctrl or a static bitmap, needs a parent, such as your top-level frame. You need to add your window to the parent (frame), and then separately add your window to the sizer. -- Paul McNett Independent Software Consultant http://www.paulmcnett.com From fumanchu at amor.org Mon Oct 11 00:01:16 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 10 Oct 2004 21:01:16 -0700 Subject: Using tuples correctly? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F59@exchange.hqamor.amorhq.net> BJ?rn Lindqvist wrote: > I like tuples alot. But in some situations you seem to be forced to > access the elements of a tuple via its indexes and that is pretty > ugly. For example: > > # make_color() returns a rgb tuple (r, g, b). I.e. (255, 0, 0) > print "The red value is: ", make_color()[0] > > Not nice at all. It is maybe OK for a rgb tuple that only has three > elements, but for a tuple that has 10+ elements, index access is > rediculous. In that case, unpacking wont helpe either. What you would > like to write is: > > print "The red value is: ", make_color().r >8 > After some more browsing of the Python Cookbook and googling it seems > like lots of people is trying to emulate structs on the fly in python. > So why aren't there a tuple-with-named-attributes type in python? The tuple-with-named-attributes is called a 'class' in Python. class RGB(object): def __init__(self, r=0, g=0, b=0): self.red = r self.green = g self.blue = b > So you could write stuff like this: > > return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30) color = RGB(10, 20, 30) print "The red value is: ", color.red If you *must* have a tuple to throw around, give your class a 'tuple' method: class RGB(object): def __init__(self, r=0, g=0, b=0): self.red = r self.green = g self.blue = b def tuple(self): return (self.r, self.g, self.b) Why bother to shoehorn all of the name scaffolding into tuples when it's already present in classes? Robert Brewer MIS Amor Ministries fumanchu at amor.org From boria at NOSPAM.fbg.uklinux.net Thu Oct 28 09:21:03 2004 From: boria at NOSPAM.fbg.uklinux.net (Boria Feigin) Date: Thu, 28 Oct 2004 14:21:03 +0100 Subject: P2P framework Message-ID: <4180f21f$0$43632$ed2e19e4@ptn-nntp-reader04.plus.net> Hi All, I am looking for a networking (p2p, if you like) framework with Python bindings. Requirements are very basic - a node should be able to: o join/leave the network (perhaps with some auth. mechanism, but not essential at this stage) o broadcast a message to other nodes o communicate with another node on the network Basically, something like Sun's JXTA (www.jxta.org) would be more than sufficient. They do have a Python bindings project (jxtapy.jxta.org) but that seems dead and I'd rather avoid using Jython for the time being. All and any advice appreciated. Boris From Bobidoo10 at aol.com Fri Oct 1 09:09:09 2004 From: Bobidoo10 at aol.com (Bobidoo10 at aol.com) Date: Fri, 1 Oct 2004 09:09:09 EDT Subject: please read! Message-ID: <148.34ce48a6.2e8eb0f5@aol.com> PLEASE STOP SENDING ME EMAILS FROM PEOPLE THAT I DO NOT KNOW!! I HAVE NOT GIVEN MY EMAIL ADDRESS TO THESE PEOPLE AND DO NOT WISH TO RECIEVE EMAIL FROM THEM, I HAVE HAD OVER 100 EMAILS THIS MORNING SINCE 10 O CLOCK. Return-Path: <_python-list-bounces+bobidoo10=aol.com at python.org_ (mailto:python-list-bounces+bobidoo10=aol.com at python.org) > Received: from rly-yi04.mx.aol.com (rly-yi04.mail.aol.com [172.18.180.132]) by air-yi02.mail.aol.com (v101_r1.4) with ESMTP id MAILINYI22-7c5415d54e51aa; Fri, 01 Oct 2004 09:00:32 -0400 Received: from smtp-vbr7.xs4all.nl (smtp-vbr7.xs4all.nl [194.109.24.27]) by rly-yi04.mx.aol.com (v101_r1.5) with ESMTP id MAILRELAYINYI43-7c5415d54e51aa; Fri, 01 Oct 2004 09:00:21 -0400 Received: from bag.python.org (bag.python.org [194.109.207.14]) by smtp-vbr7.xs4all.nl (8.12.11/8.12.11) with ESMTP id i91D0KlC099543 for <_bobidoo10 at aol.com_ (mailto:bobidoo10 at aol.com) >; Fri, 1 Oct 2004 15:00:20 +0200 (CEST) (envelope-from _python-list-bounces+bobidoo10=aol.com at python.org_ (mailto:python-list-bounces+bobidoo10=aol.com at python.org) ) Received: from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with ESMTP id ADB9C1E4009 for <_bobidoo10 at aol.com_ (mailto:bobidoo10 at aol.com) >; Fri, 1 Oct 2004 15:00:20 +0200 (CEST) Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit4.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!border1.nntp.d ca.giganews.com!nntp.giganews.com!local1.nntp.dca.giganews.com!nntp.powergate. ca!news.powergate.ca.POSTED!not-for-mail NNTP-Posting-Date: Fri, 01 Oct 2004 07:55:15 -0500 Date: Fri, 01 Oct 2004 08:55:15 -0400 From: Peter L Hansen <_peter at engcorp.com_ (mailto:peter at engcorp.com) > User-Agent: Mozilla Thunderbird 0.8 (Windows/20040913) X-Accept-Language: en-us, en MIME-Version: 1.0 Newsgroups: comp.lang.python References: <_9c3edc58.0409302034.54f93dd2 at posting.google.com_ (mailto:9c3edc58.0409302034.54f93dd2 at posting.google.com) > In-Reply-To: <_9c3edc58.0409302034.54f93dd2 at posting.google.com_ (mailto:9c3edc58.0409302034.54f93dd2 at posting.google.com) > Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Message-ID: <__PmdnZJ4xYsuzsDcRVn-tA at powergate.ca_ (mailto:_PmdnZJ4xYsuzsDcRVn-tA at powergate.ca) > Lines: 36 NNTP-Posting-Host: 66.38.136.15 X-Trace: sv3-RDb9gkCDW2HP27BmNz4HwGB+1IoXcwwBQYrS0CKQwTQ3Ez3qP06nxVUGTapYzqGhUt30riW4RG24wt/!WCja4MeazB99JlmP5pJwirw3v91DnZGZr2pRq+L4wOBoggEb53St+pO7+q8OqB FrfZR+xqyUBrZG X-Complaints-To: _abuse at powergate.ca_ (mailto:abuse at powergate.ca) X-DMCA-Complaints-To: _abuse at powergate.ca_ (mailto:abuse at powergate.ca) X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.17 Xref: news.xs4all.nl comp.lang.python:340085 To: _python-list at python.org_ (mailto:python-list at python.org) Subject: Re: A newbie in more need.... X-BeenThere: _python-list at python.org_ (mailto:python-list at python.org) X-Mailman-Version: 2.1.5 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: <_http://mail.python.org/mailman/listinfo/python-list_ (http://mail.python.org/mailman/listinfo/python-list) >, <_mailto:python-list-request at python.org?subject=unsubscribe_ (mailto:python-list-request at python.org?subject=unsubscribe) > List-Archive: <_http://mail.python.org/pipermail/python-list_ (http://mail.python.org/pipermail/python-list) > List-Post: <_mailto:python-list at python.org_ (mailto:python-list at python.org) > List-Help: <_mailto:python-list-request at python.org?subject=help_ (mailto:python-list-request at python.org?subject=help) > List-Subscribe: <_http://mail.python.org/mailman/listinfo/python-list_ (http://mail.python.org/mailman/listinfo/python-list) >, <_mailto:python-list-request at python.org?subject=subscribe_ (mailto:python-list-request at python.org?subject=subscribe) > Sender: _python-list-bounces+bobidoo10=aol.com at python.org_ (mailto:python-list-bounces+bobidoo10=aol.com at python.org) Errors-To: _python-list-bounces+bobidoo10=aol.com at python.org_ (mailto:python-list-bounces+bobidoo10=aol.com at python.org) X-Virus-Scanned: by XS4ALL Virus Scanner X-AOL-IP: 194.109.24.27 X-AOL-SCOLL-SCORE: 0:0:0: X-AOL-SCOLL-URL_COUNT: 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Sun Oct 17 11:13:26 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 17 Oct 2004 17:13:26 +0200 Subject: acting on items passed to a method via a dictiomary References: Message-ID: <1glsuhc.10eukauy09rs8N%aleaxit@yahoo.com> Diez B. Roggisch wrote: > Donnal Walter wrote: > > > The following method is defined in one of my classes: > > > > def setup(self, items={}): ... > First of all, don't use {} as default value for items. Many have stepped > into this trap: While perfectly legal, it will be evaluated only once, when > the method setup is found the first time. So then an instance of a dict is > created. But now if subsequent calls to setup alter that dict items points > to, they all share the same dict!! This small example illustrates that However, there are no problems whatsoever with the issue you remark on, as long as the method never alters the 'items' object. As long as only nonmutating methods get called on 'items', i.e., 'items' is practically treated as "read-only", Donnal Walter's approach is just fine. The issue you remark on does deserve to be made, but it's also important to understand when it does matter and when it doesn't. Alex From aleaxit at yahoo.com Wed Oct 6 17:45:05 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 6 Oct 2004 23:45:05 +0200 Subject: [ANN] PySQLite 1.0 References: Message-ID: <1gl9dev.1j87pnh1j1dlmvN%aleaxit@yahoo.com> Gerhard Haering wrote: > ============================= > Announcement for PySQLite 1.0 > ============================= > > I'm pleased to announce that PySQLite has reached version 1.0 now. Cheers and celebrations!!! It's always important to hear when a developer deems his code mature and solid enough to risk the "1.0" label -- and this goes double for the _excellent_ PySQLite, which was a pretty solid and mature and _incredibly useful_ piece of code for quite a while already. Bravo Gerhard! I hope the DBAPI SIG's efforts to make a better DBAPI 3.0 aren't quite stalled...? I think it's high time to standardize down to ONE format for argument substitution and support _iteration_ on fetches rather than having to either fetch one, or a list... that's a minimum set on which I hope agreement could be reached... For a far more ambitious goal, look al psycopg2 -- YUM... adaptation roolz!!! (My secret dream is to have psycopg2 and PySQLite 2.0 support the same API -- at which point I will care little what the DBAPI does, since, unless a client twists my arm _and_ dangles bags of gold in front of me, PostgreSQL and SQLite are the only two RDBMSs I really need...!-). Considering the nationalities of the psycopg[2] and PySQLite developers, might I suggest rekindling the goot olt Rome-Berlin Axis, or would that automatically invoke Goodwin's Law & kill the thread?-) Alex From danperl at rogers.com Fri Oct 8 10:29:45 2004 From: danperl at rogers.com (Dan Perl) Date: Fri, 8 Oct 2004 10:29:45 -0400 Subject: wxPython problem switching between 2 wx.SplitterWindow's Message-ID: I have posted this problem also on the wxpython-users list, but maybe someone here can also help. I want to keep 2 different views for the same object, both views using SplitterWindow. So I am trying to create 2 SplitterWindow's, keeping both in memory, and alternately show only one of them. However, that doesn't work and I've tried all kinds of combinations of Show, SplitVertically, UpdateSize, and Layout. I think I have isolated the problem in this code snippet (also attached). This code actually works. But un-comment the 2 lines for splitter2 and you will see the problem: #!/usr/bin/env python import wx class myFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent=parent) self.SetClientSize(wx.Size(600, 500)) self.splitter1=wx.SplitterWindow(self) self.splitter1.Hide() #self.splitter2=wx.SplitterWindow(self) # un-comment and you'll #self.splitter2.Hide() # see the problem def showSplitter(self, id): if id==1: self.splitter1.Show() if id==2: self.splitter2.Show() class myApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() self.mainWin = myFrame(None) self.mainWin.Show() self.SetTopWindow(self.mainWin) self.mainWin.showSplitter(1) return True if __name__ == '__main__': application = myApp(0) application.MainLoop() I have cut it down to the bone, so there are no children in the SplitterWindow's and they are not even splitted. I assure you that the same is happening in those cases. I am not invoking any Layout( ) here, but I've tried that too. Can anyone explain what is happening here? Am I missing a step somewhere? Or could this actually be a bug in SplitterWindow? Dan From R.Brodie at rl.ac.uk Fri Oct 1 11:24:26 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 1 Oct 2004 16:24:26 +0100 Subject: Python in Process Control? References: Message-ID: "Neil Benn" wrote in message news:mailman.4176.1096636511.5135.python-list at python.org... > IMHO, I think that Python is not a suitable piece of software for > industrial control as it has poor support for bytes (a string shouldn't > be used to store bytes!) That's largely a matter of attitude I think; many would argue that byte strings shouldn't be used to store text. From DesertLinux at netscape.net Sat Oct 9 23:41:21 2004 From: DesertLinux at netscape.net (Byron) Date: Sun, 10 Oct 2004 03:41:21 GMT Subject: The IDE question In-Reply-To: References: Message-ID: Hi DA, I don't know if you will find this to be helpful, but one of my favorite IDEs is DrPython, which is free and allows you to have multiple files open at the same time. Check it out... http://drpython.sourceforge.net/ Byron --- dataangel wrote: > I'm trying to find an IDE for python that I'm comfortable with. For my > needs IDLE actually works 99% of the time, but on my current project I > need to have lots of files open at once, and I would really prefer to > have tabbed browsing. I'd even try to code this into IDLE myself but I > have no experience with Tk. > > All of the IDEs I've found (google + python wiki page) are either A) > Commercial or B) Written for either an older version of python or > wxPython or C) Are syntax highlighting in eclipse and that's it. > > All I'm really looking for is the equivalent of IDLE with tabbed > browsing. Anyone have any suggestions? > > From justinstraube at charter.net Wed Oct 13 23:06:31 2004 From: justinstraube at charter.net (justin) Date: Wed, 13 Oct 2004 20:06:31 -0700 Subject: Tkinter Dialog boxes Message-ID: Hello, Ive looked through what I could find on the Tk dialog boxes, but was not able to find what i wanted. I am looking for one that will allow me to select a directory rather than a file. Any suggestions what I can try? Thanks, justin straube From peter at engcorp.com Mon Oct 4 17:54:07 2004 From: peter at engcorp.com (Peter L Hansen) Date: Mon, 04 Oct 2004 17:54:07 -0400 Subject: wxPython - what classes are available? In-Reply-To: <470ec500.0410040000.7dcad024@posting.google.com> References: <470ec500.0410040000.7dcad024@posting.google.com> Message-ID: moff wrote: > There seems to be a heck of a lot of wxEWindows classes available. > Can someone tell me (or send me a link of) what is compatable with > wxPython? > > It can't be the whole lot, can it? > > (Wow, wxPython looks GREAT!) (a) yes it does. :-) (b) It's called wxWidgets now, not wxWindows. (c) As far as I know, effectively all classes are provided in wxPython which are not already provided by standard Python. For example, wxList is not provided, since Python has its own lists. Similarly with networking and threads. The GUI stuff is pretty much complete. (d) Download wxPython, install, and run the demo. It shows *everything* (roughly speaking)... -Peter From aleaxit at yahoo.com Tue Oct 19 15:30:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 19 Oct 2004 21:30:31 +0200 Subject: itertools candidate: warehouse() References: Message-ID: <1glx9uk.19y2l5yvlo403N%aleaxit@yahoo.com> Peter Otten <__peter__ at web.de> wrote: ... > >>iavailable = chain(stock, starmap(random.random, repeat(()))) ... > No, you cannot pass a callable to repeat() and have it called. In the above > line repeat(()) yields the same empty tuple ad infinitum. The trick is that > starmap() calls random.random() with that empty tuple as the argument list, Stylistically, I prefer iter(random.random, None) using the 2-args form of the built-in iter, to itertools.starmap(random.random, itertools.repeat(())) However, itertools IS a speed demon...: kallisti:~/cb alex$ python -m timeit -s 'import random, itertools as it' \ > 'list(it.islice(iter(random.random, None), 666))' 1000 loops, best of 3: 884 usec per loop kallisti:~/cb alex$ python -m timeit -s 'import random, itertools as it' \ > 'list(it.islice(it.starmap(random.random, it.repeat(())), 666))' 1000 loops, best of 3: 407 usec per loop Alex From __peter__ at web.de Tue Oct 19 12:12:06 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 19 Oct 2004 18:12:06 +0200 Subject: Referencing objects own functions References: <48a9916d.0410190745.4c9d0536@posting.google.com> Message-ID: pip wrote: > Hi all, > > Pretend I have the following: > > class foo: > commands = [ > 'name': 'help', > 'desc': 'Print help', > ] > > def print_help(self): > print "Help is on the way!" > > I would like to add another entry to the commands dict. called 'func' > or something which contains a reference to a function in the foo > class. What would the entry look like if atall possible? > > I would rather not use eval if possible. As a rule of thumb, you can do everything in a class suite that can be done in a function definition. def print_help(self): # code binds the print_help name to a function object in the same way as one = 1 binds 'one' to the integer object 1. Therefore you have to define it before you can use the reference: >>> class foo: ... def print_help(self): ... print "help is on the way" ... commands = dict( ... name="help", ... desc="print help", ... func=print_help) ... >>> fooinst = foo() There are two ways to call commands["func"], but both require that you explicitly provide the self parameter: >>> fooinst.commands["func"](fooinst) help is on the way >>> foo.commands["func"](fooinst) help is on the way While calling the function stored in the commands dictionary is a bit more tedious than normal method invocation, all efforts to simply that depend heavily on what you actually want to do with the function stored in the dictionary. Peter From lists.python.org at bdash.net.nz Tue Oct 19 03:01:27 2004 From: lists.python.org at bdash.net.nz (Mark Rowe) Date: Tue, 19 Oct 2004 20:01:27 +1300 Subject: Building email threads from unix mailboxes In-Reply-To: <1098138259.303424.280500@z14g2000cwz.googlegroups.com> References: <1098138259.303424.280500@z14g2000cwz.googlegroups.com> Message-ID: On Oct 19, 2004, at 11:24 AM, Jed Parsons wrote: > What headers to I have to know about to build thread trees from Unix > mailboxes? > > Is it enough to get the In-Reply-To header for each message and build a > dictionary of { Message-ID: message } pairs? Or is it more complicated > than that? has a good write-up about the threading algorithm used by Netscape Mail and News 2.0 and 3.0, and Grendel (). Jamie Zawinski was responsible for the design of Netscape Mail and News 2.0 and 3.0. > If there isn't already a module to do this (and apologies if there is > one and I don't know about it), are the current tools of choice the > 'email' and 'mailbox' modules? (And I guess I'd want to use the mime > decoding tools in 'email' to deal with messages that come with > attachments or html or other stuff.) A.M. Kuchling has made a Python implementation of JWZ's algorithm available at . > Thanks for any tips, > > Jed Regards, Mark Rowe From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Thu Oct 7 18:07:23 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Thu, 07 Oct 2004 23:07:23 +0100 Subject: difficult zipefile Question In-Reply-To: References: Message-ID: matthiasjanes wrote: > maybe someone has an idea. Someone has more than an idea. I already posted the answer to your question, but you apparently only bothered to read part of my message. -- Michael Hoffman From nick at craig-wood.com Wed Oct 6 05:29:58 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 06 Oct 2004 09:29:58 GMT Subject: Retrieving the full path of Unix apps References: Message-ID: Andrew Dalke wrote: > Here's an incomplete implementation of 'which' > > import os > > def is_executable(filename): > # Placeholder: not sure how to do this > return 1 def is_executable(filename): return os.access(filename, os.X_OK) Is probably close enough unless you are running setuid (and even then it probably does the right thing!) > def which(app): > dirnames = os.environ["PATH"].split(os.path.pathsep) > for dirname in dirnames: > filename = os.path.join(dirname, app) > if (os.path.exists(filename) and > os.path.isfile(filename) and > is_executable(filename)): > return filename > return None -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jcarlson at uci.edu Sat Oct 16 13:19:16 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 16 Oct 2004 10:19:16 -0700 Subject: undefined variable ? In-Reply-To: <20041016084913.09DB.JCARLSON@uci.edu> References: <20041016084913.09DB.JCARLSON@uci.edu> Message-ID: <20041016101732.09DE.JCARLSON@uci.edu> > >>> t = time.time();tf(1000000);time.time()-t > 27.0 The above timing should be for tf2(), I accidentally duplicated a line. tf2() runs in 27 seconds (all timings done on a dual-processor intel celeron 400mhz machine using Python 2.3.2). - Josiah From irmen at -nospam-remove-this-xs4all.nl Sat Oct 30 09:52:11 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 30 Oct 2004 15:52:11 +0200 Subject: Plugin system In-Reply-To: <2uhjppF2a61u6U1@uni-berlin.de> References: <2uhjppF2a61u6U1@uni-berlin.de> Message-ID: <41839c8b$0$78279$e4fe514c@news.xs4all.nl> Reinhold Birkenfeld wrote: > How would you implement a plugin system (for a web-based application)? This is so general a question that I cannot think of anything concrete to answer. Please ask again, with more detail about what you want/need/have in mind. --Irmen From duncan-news at grisby.org Wed Oct 13 11:29:39 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 13 Oct 2004 17:29:39 +0200 Subject: PythonCom equivalent on Linux! References: Message-ID: In article , John wrote: >Is there an equivalent of COM on Linux that I can get through Python. >My need is to have some sort of language independent component >framework. I can think of CORBA but I have to have a server running. I >prefer not to. I just need Python components for local consumption in >other languages. I remember Gnome libs having some thing like this. >Any thoughts? Other people have already mentioned that CORBA may be a good choice for you, and pointed you to some of my presentations about the issues. One thing nobody has mentioned yet is your statement that for CORBA you "have to have a server running". That is one of the common myths about CORBA. For CORBA to work, there is no need for some kind of separate server. Processes using CORBA talk to each other directly, not through some other server. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From niemeyer at conectiva.com Wed Oct 6 09:48:02 2004 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Wed, 6 Oct 2004 10:48:02 -0300 Subject: re bug In-Reply-To: <3e96ebd7.0410052341.113f75c5@posting.google.com> References: <3e96ebd7.0410050057.29a15174@posting.google.com> <3e96ebd7.0410052341.113f75c5@posting.google.com> Message-ID: <20041006134801.GA4479@burma.localdomain> > > Btw, the only reason that the OP's expression didn't got stuck > > in the first two test cases is because the expression matched. > > I don't really understand what you mean. You can easily change str3 > such that rx matches. Nevertheless, you will have to wait a long time > to get a result. If you're waiting a long time, your expression isn't matching. Try to use "mm/mm/cn:nom:akk:2:3" as the last term of your third expression. It executes in 0.045 seconds here. -- Gustavo Niemeyer http://niemeyer.net From chrisks at NOSPAM.udel.edu Sun Oct 17 02:33:57 2004 From: chrisks at NOSPAM.udel.edu (Chris S.) Date: Sun, 17 Oct 2004 06:33:57 GMT Subject: Efficient String Lookup? In-Reply-To: <5Ikcd.5517$6k2.1064@newsread3.news.pas.earthlink.net> References: <5Ikcd.5517$6k2.1064@newsread3.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > Here's the output I got when I ran it > > > abadb? We've got a 'Antimatter containment field breach' warning! > abcdef? We've got a 'Reactor meltdown imminent' warning! > zxc? That's okay. > abcq? We've got a 'Antimatter containment field breach' warning! > b1234f? We've got a 'Coffee too strong' warning! Actually, I've noticed some strange behavior. It seems to match more than one character per wild card. For instance, your code matches 'abaxile', 'abaze', and 'abbacomes' to the pattern 'ab##'. I'm not an expert with rex, but your expression looks correct. What could be causing this? From ville at spammers.com Fri Oct 15 16:52:35 2004 From: ville at spammers.com (Ville Vainio) Date: 15 Oct 2004 23:52:35 +0300 Subject: operation with strings and numbers References: <6rWbd.142269$35.6913604@news4.tin.it> Message-ID: >>>>> "liquid" == GMTaglia writes: liquid> Ville Vainio wrote: >> >> Did you mean Italian SCHOOLboy, be any chance? Don't be afraid to say >> so, because everyone can guess anyway. >> liquid> sorry what you mean? Well, it was a school assignment, right? -- Ville Vainio http://tinyurl.com/2prnb From xeranic at yahoo.com Fri Oct 22 08:05:45 2004 From: xeranic at yahoo.com (Xin Wang) Date: Fri, 22 Oct 2004 05:05:45 -0700 (PDT) Subject: About lambda. Message-ID: <20041022120545.85978.qmail@web90003.mail.scd.yahoo.com> Some c++ guru said c++ is hard to learn but easy to use. Is python easy for both aspect? I found lot's of confused in coding. #code from Tkinter import * def on_click(m): print m def lamb_on_click(m): return lambda : on_click(m) root = Tk() btns = ['0', '1', '2', '3'] for n in btns: b = Button(root, text=n, command=lamb_on_click(n)) #Ok! b.pack() root.mainloop() # Or, #code ... b = Button(root, text=n, command=lambda x=n: click(x)) #Ok! ... # The code above works well too, but follow is NOT! WHY? #code ... b = Button(root, text=n, command=lambda : on_click(n)) ... # Whichever button be clicked, this only print '3'. Keyword 'lambda' is just like a macro in c or templete in c++ or not? _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From danperl at rogers.com Tue Oct 26 20:27:25 2004 From: danperl at rogers.com (Dan Perl) Date: Tue, 26 Oct 2004 20:27:25 -0400 Subject: request for feedback: pyfmf Message-ID: pyfmf is a project I started a few months ago and that is registered with sourceforge (http://pyfmf.sourceforge.net, http://sourceforge.net/projects/pyfmf). It consists of a framework for file management, with a console based toolkit (zigo) and a graphical platform (zago) based on the framework. Both zigo and zago are still alpha releases, addressed only to python enthusiasts. I just released a new version of zigo and the first release of zago. There have been a few tens of downloads of previous releases of zigo (which is not bad) but I never received any feedback (at least I didn't get any bad feedback either). I would like to hear what other people think about it. I am interested in comments on uses, design, coding or just simply whether you think this is interesting and useful. Please take a look at the home page of the project: http://pyfmf.sourceforge.net. Thanks, Dan Perl From cpl.19.ghum at spamgourmet.com Mon Oct 11 08:40:07 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 11 Oct 2004 12:40:07 +0000 (UTC) Subject: Python to Python communication Message-ID: Hello, I have a group of Python programms which I want to teach to "talk to each other". All run on Windows, on the same computer or in the same intranet. Security of communication is not an issue (encryption on lower level protocols / intra computer communication). Partially these programs are using wxPython. It is important that the communcation is "only an added feature", I am not willing to spend big memory / computing ressources on it. So I googled and came up with at least the following opportunities: XMLRPC - quite "simple" to implement within python, contained in my favourite web framework Quixote / medusa SOAP - around the same amount of work as XMLRPC ----> these two are fully buzzword compatible to enterprise communication needs. But are they really lightwight and needed? Banana - within the twisted framework. Is described as high performance with very litte ressources. From my scanning of twisted it is meanwhile possible to integrate it within wxPython and you only need to sell the soul of your firstborn for it; but I got the impression twisted rather needs a total commitment than a "I just need some banana, man" pyro - Python Remote Objects. Irmen de Jong has a "get Firefox" icon on it's page and he plays with the name "pyro", which makes a good impression. It looks rather "ripe", but: he is talking about "pyro 4.0" which will be incompatible with pyro 3.4 and a total redesign. That makes me shudder. COM / DCOM. From our favourite software company, available mainly within windows. Wrapped excellently with pywin32 ... but needs some seriuos type-mangeling to get through and around 2 Gig of Browser Cache to read all the MSDN documentation, which is quite C-ish. socket / select. Within the standard lib. Does not look to hard to get to work, working samples included in the nutshell. ---- so, I am stranded ... and ask C.L.P. for recommendations. What library have you used and would recommend? Harald From mfranklin1 at gatwick.westerngeco.slb.com Mon Oct 11 09:02:06 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 11 Oct 2004 14:02:06 +0100 Subject: Python to Python communication References: Message-ID: On Mon, 11 Oct 2004 12:40:07 +0000 (UTC), Harald Massa wrote: > Hello, > > I have a group of Python programms which I want to teach to "talk to each > other". > > All run on Windows, on the same computer or in the same intranet. > Security of communication is not an issue (encryption on lower level > protocols / intra computer communication). Partially these programs are > using wxPython. > > It is important that the communcation is "only an added feature", I am > not willing to spend big memory / computing ressources on it. > [SNIP] > > pyro - Python Remote Objects. Irmen de Jong has a "get Firefox" icon on > it's page and he plays with the name "pyro", which makes a good > impression. It looks rather "ripe", but: he is talking about "pyro 4.0" > which will be incompatible with pyro 3.4 and a total redesign. That makes > me shudder. > [SNIP] > Harald Harald, I only have experience with Pyro, so am biased, but from your rather sketchy description I think it would have the smallest impact (in terms of existing code re-work) as it can simply be bolted on with the inclusion of a couple of extra classes. At least that was my experience when I needed to get a couple of python applications talking... Just my tupence worth :-) Martin -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From martin at v.loewis.de Fri Oct 29 03:12:32 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 29 Oct 2004 09:12:32 +0200 Subject: Tkinter and utf-8 In-Reply-To: References: <4181cc21$0$3620$8fcfb975@news.wanadoo.fr> Message-ID: <4181ED60.5010703@v.loewis.de> Justin Ezequiel wrote: > Any tips for a Mandrake newbie for getting a few more characters displayed > WYSIWYG? What characters specifically are you missing? In general, the answer is "install more fonts". Tk is pretty smart in finding the right font, provided an appropriate font is available. Do xlsfonts(1) to see whether you have a good number of fonts installed. On my system, I get martin at mira:~/work/py2.4/Lib$ xlsfonts|wc 8317 10959 495020 and I'm confident that Tk would display any character I could ever encounter. Regards, Martin From ville at spammers.com Mon Oct 4 15:40:25 2004 From: ville at spammers.com (Ville Vainio) Date: 04 Oct 2004 22:40:25 +0300 Subject: metaclass and customization with parameters References: <3b59a80.0410021910.17b31c29@posting.google.com> <1gl3wcp.15oxvkd1jdp8dbN%aleaxit@yahoo.com> <4edc17eb.0410040223.4aa4f24b@posting.google.com> <1gl55lu.yovfmt1kquac3N%aleaxit@yahoo.com> Message-ID: >>>>> "Carlos" == Carlos Ribeiro writes: Carlos> During the learning process, more often than not I would Carlos> try to solve *all* problems with a metaclass, as if it was Carlos> the only tool available. Now that I'm starting to feel Carlos> comfortable, things start to fall back into the correct Carlos> perspective once again. But of course, now I'm better Carlos> equiped with a powerful addition to my toolset :-) Let's Carlos> not abuse it though. Good idea. If I was to review a piece of code that introduced a metaclass (as opposed to just using one that came with a framework), I would be prone to ask the author whether he really exhausted *all* the other avenues before going the metaclass route. Not documenting metaclasses in the standard, bundled documentation is a good thing. -- Ville Vainio http://tinyurl.com/2prnb From no at spam.please Mon Oct 11 18:08:43 2004 From: no at spam.please (Doug Holton) Date: Mon, 11 Oct 2004 17:08:43 -0500 Subject: [ANN] Boo 0.4.3 - python-like language for .NET/Mono In-Reply-To: <8-ydnZX55r3oYffcRVn-vw@giganews.com> References: <8PGdnS7wN_uwg_rcRVn-qw@comcast.com> <8-ydnZX55r3oYffcRVn-vw@giganews.com> Message-ID: <8JCdnZdSROT1mfbcRVn-sg@comcast.com> Istvan Albert wrote: > "Python-like" means very little. Make it run python code > then you'll see a lot more interest from this group. > This does not appear to indicate that boo is any faster > than python... > > Istvan. Nice talking to you From bruno at octantis.com.br Sat Oct 23 21:30:27 2004 From: bruno at octantis.com.br (Bruno R. Dias) Date: Sat, 23 Oct 2004 22:30:27 -0300 Subject: Interesting coding idea In-Reply-To: <9ckln0tm2ubr7t8hafe27p66kfileceabu@4ax.com> References: <2tvup4F24iddjU1@uni-berlin.de> <9ckln0tm2ubr7t8hafe27p66kfileceabu@4ax.com> Message-ID: <2u0bd8F23g8afU1@uni-berlin.de> Jack Klein wrote: > On Sat, 23 Oct 2004 18:54:55 -0300, "Bruno R. Dias" > wrote in comp.lang.c: > > >>Perhaps it would be interesting to program a virtual machine simulating >>an ancient computer (such as the pdp-7). Then, it would be rather >>interesting to code for it (porting gcc to it maybe?). I think it would >>be fun to play with the long-forgotten art of coding in machine language. >> >>And what about a fictional computer, such as one that works on an >>entirely different way (such as a non-binary computer)? >> >>It wouldn't be very useful, but it wouold be a very fun and very >>interesting thing to hack on. > > > And what exactly does this have to do with the C language? I suspect > it is equally off-topic in comp.lang.python. > It would be *programmed* in a language, obviously. It's just that C is rather appropriate for that kind of stuff, It's one of my favorite languages, and It's a subject that should interest C programmers. The same goes for Python. -- -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GCS/E/L d-- s+:+ a--- C++ UL+ P--- L++>+++ E W++ N+ o+ K++ w--- !O M-- V--PS++ PE++ Y>+ PGP>+ t++(+++) 5? X R+ tv@ b+++@ DI++++ D--- G+ e- h! r-- y ------END GEEK CODE BLOCK------ From aleaxit at yahoo.com Fri Oct 15 03:04:54 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 15 Oct 2004 09:04:54 +0200 Subject: I sing the praises of lambda, my friend and savior! References: <2qtl0oF139gn6U1@uni-berlin.de> <10mli0vohrtf8b6@corp.supernews.com> <10mllq67t1qah3b@corp.supernews.com> <10mo6q66oi0kj04@corp.supernews.com> <10mqr0rlj9h6r69@corp.supernews.com> <10mrev24df58k60@corp.supernews.com> Message-ID: <1gloawd.1evwxaa1arg2g0N%aleaxit@yahoo.com> Jeff Shannon wrote: ... > certainly entitled to his opinion, but there are others who *do* agree > with Python's design goals. ISTM that it would therefore be better, > overall, for those who disagree with Pythonic philosophy to look for a > different language that suits them better, and those who agree with > Pythonic philosophy to keep using Python. Trying to please everyone > with a single language just isn't gonna work, nor should it be expected Amen, hallelujah. There are thousands and thousands of programming languages, and more are born all the time. Trying to make one language please all is a doomed endeavour: "if you want PL/I, you know where to find it" (apparently that was Ritchie's stock answer to Thompson's occasional whines that C didn't allow this, that, or the other -- C shares with Python the underlying ideal of "there should be one obvious way", indeed Python shares 4.5 of the 5 principles that the ANSI C Standard introduction defines as "the Spirit of C"). > Oh, and I almost agree with you about list comprehensions -- they'd do > just as well to be left out of Py3K, because they've been superseded by > generator comprehensions. ;) "Generator expressions" is the recommended terminology nowadays. But I agree, list(x+x for x in foo) is a perfectly acceptable alternative to the equivalent List Comprehension [x+x for x in foo] and in Python 3.0 the latter is therefore likely to be removed, as part of the overall idea of removing many "legacy" things, accumulated over the years, and make Python more pythonic. Hacking on CPython on a vast scale is too hard to bother, but if and when pypy matures, assuming 3.0 still looks far away at that point, I'd like to make a "prototype 3.0" based strictly on removing stuff (moving some redundant stuff to a legacy package in the standard library where feasible, or else just excising it). Ah well, one can dream!-) Alex From peter at engcorp.com Fri Oct 29 10:59:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Oct 2004 10:59:00 -0400 Subject: Python package anthologies In-Reply-To: <1gmfdi1.9ccj14oq43dgN%aleaxit@yahoo.com> References: <1gmeuqj.1p0mkh41y1zvfcN%aleaxit@yahoo.com> <1gmfclt.1g61j8z1uatvgzN%aleaxit@yahoo.com> <1gmfdi1.9ccj14oq43dgN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Peter Hansen wrote: > The problem I can see with "sets of a dozen interrelated packages" is: > what happens to users who need two of them, when the two packages use > and include the same extension... in two different versions... Uh, test first? Why don't we try it and see how big a problem it is? (Using the impersonal "we", of course. :-) -Peter From bulliver at badcomputer.no-ip.com Fri Oct 8 11:18:36 2004 From: bulliver at badcomputer.no-ip.com (Darren Kirby) Date: Fri, 8 Oct 2004 08:18:36 -0700 Subject: Can wxWidgets/wxPython 2.4 and 2.5 co-exist on same PC? In-Reply-To: References: Message-ID: <200410080818.42832.bulliver@badcomputer.no-ip.com> quoth the R Baumann: > I would like to be able to run Boa Constructor, which does not yet use 2.5, > but I would also like to work with Dabo which does. > > Anyone have any ideas about how to accomplish this? > > Thanks > Ruben I would imagine it depends on your platform. For instance, Gentoo Linux has a mechanism called slots that allows multiple versions of the same app to be installed. -d -- Part of the problem since 1976 http://badcomputer.no-ip.com Get my public key from http://keyserver.linux.it/pks/lookup?op=index&search=bulliver "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bokr at oz.net Wed Oct 13 08:57:34 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Oct 2004 12:57:34 GMT Subject: strange side effect with lists!? References: <1glllnv.9f2gdijdroqgN%aleaxit@yahoo.com> Message-ID: <416d22ac.152182767@news.oz.net> On Wed, 13 Oct 2004 14:19:56 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: > wrote: > >> Hello, >> >> I'm new to Python and playing around. I'm confused by the following >> behaviour: >> >> >>> l1 = [1] # define list >> >>> l2 = l1 # copy of l1 ? >> >>> l2,l1 >> ([1], [1]) >> >>> l2.extend(l1) # only l2 should be altered !? >> >>> l2,l1 >> ([1, 1], [1, 1]) # but also l1 is altered! >> >> So what is the policy of assignment? When is a copy of an object created? >> Where to find dox on this? > >Bruno's answer seems very thorough so I'll just try to briefly summarize >the answers: > >1. simple assignment (to a bare name, at least), per se, never > implicitly copies objects, but rather it sets a reference to an > object (_another_ reference if the object already had some). > >2. a new object is created when you request such creation or perform > operations that require it. Lists are particularly rich in such > operations (see later). Simple assignment to a bare name is not > an operation, per se -- it only affects the name, by making it refer > to whatever object (new, or used;-) is on the righht of the '='. > >3. I believe any decent book on Python will cover this in detail. > >Now for ways to have a new list object L2 made, with just the same items >and in the same order as another list object L1 ("shallow copy"): > >a. import copy; L2 = copy.copy(L1) > >This works to shallow-copy _any_ copyable object L1; unfortunately you >do have to import copy first. Module copy also exposes function >deepcopy, for those rare cases in which you wish to recursively also get >copies of all objects to which a "root object" refers (as items, or >attributes; there are some anomalies, e.g., copy.deepcopy(X) is X when X >is a class, or type...). > >b. L2 = list(L1) > >I find this is most often what I use - it works (making a new list >object) whatever kind of sequence, iterator, or other iterable L1 may >be. It is also what I recommend you use unless you have some very >specific need best met otherwise. > >c. various operations such as...: > L2 = L1 * 1 > L2 = L1 + [] > L2 = L1[:] >i.e. "multiply by one", "concatenate the empty list", or "get a slice of >all items". I'm not sure why, but the latter seems to be very popular, >even though it's neither as concise as L1*1 nor as clear and readable as >list(L1). > I got curious: >>> L = range(5) >>> L [0, 1, 2, 3, 4] Make it self-referential: >>> L[2]=L >>> L [0, 1, [...], 3, 4] >>> import copy >>> Lc = copy.copy(L) >>> Lc [0, 1, [0, 1, [...], 3, 4], 3, 4] >>> Ldc = copy.deepcopy(L) >>> Ldc [0, 1, [...], 3, 4] Interesting that the deep copy made the copy self-referential (i.e., to the copy itself) like the original's reference to its (different) self: >>> id(Ldc) == id(Ldc[2]) True Unlike the shallow copy: >>> id(Lc) == id(Lc[2]) False ...whose middle reference was merely copied and sill refers to L: >>> id(Lc[2]) == id(L) True But like the original: >>> id(L) == id(L[2]) True I'm impressed ;-) Regards, Bengt Richter From exarkun at divmod.com Tue Oct 12 09:41:28 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Tue, 12 Oct 2004 13:41:28 GMT Subject: Core dump with increased recursionlimit In-Reply-To: Message-ID: <20041012134128.19317.733535534.divmod.quotient.1584@ohm> On 12 Oct 2004 09:29:58 GMT, Nick Craig-Wood wrote: >I've just discovered that my python (Python 2.3.4 from debian package > 2.3.4-1 running on debian testing x86 + linux 2.4.26) core dumps when > I set recursionlimit very high and do lots of recursion. > You probably have a buggy version of glibc. There is a version which automatically sets the stack limit to a fairly small value (I forget what the limit is exactly, 2 MB perhaps). If this is the case and you strace your program, you will see a setrlimit() call near the beginning of the run. Jp From __peter__ at web.de Sun Oct 10 05:27:50 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Oct 2004 11:27:50 +0200 Subject: Sorting and list comprehension References: Message-ID: Tran Tuan Anh wrote: > Hi all, > > I would like to do the followings, but I am quite new to Python hence > have not figured it out how... > > salary = dictionary > salary["Bob"] = 11 > salary["Marry"] = 4 > salary["me"]= 45 > > How can I have a sort_value() function acts like this: > result = sortvalue(salary) > result = ["Marry","Bob","me"] > > In sort, I would like to sort the key according to the values. >>> def sorted(items, key): ... tmp = [(key(v), i, v) for (i, v) in enumerate(items)] ... tmp.sort() ... return [v[2] for v in tmp] ... >>> salary = dict(Bob=11, Mary=4, me=45) >>> result = sorted(salary, key=salary.__getitem__) >>> result ['Mary', 'Bob', 'me'] Python 2.4 will have a similar sorted() function as a builtin. > Regarding the list construction, how can I do this: > > list = [item for item in list1 if for all item2 in list2 NOT > bad_condition(item, item2] I would use a conventional loop: >>> list1 = [1, 2, 3, 4] >>> list2 = [6, 2] >>> result = [] >>> def bad_condition(a, b): ... return a*2 == b ... >>> for item1 in list1: ... for item2 in list2: ... if bad_condition(item1, item2): ... break ... else: ... result.append(item1) ... >>> result [2, 4] By contrast, the listcomp solution is messy and does no short-circuiting: >>> [item1 for item1 in list1 if True not in [bad_condition(item1, item2) for item2 in list2]] [2, 4] Peter From rtilley at vt.edu Mon Oct 18 20:34:10 2004 From: rtilley at vt.edu (Brad Tilley) Date: Mon, 18 Oct 2004 20:34:10 -0400 Subject: bz2 module In-Reply-To: References: Message-ID: Jeff Epler wrote: > Is it possible that you've fallen for the common pitfall > "I named my test program xxx.py, and module xxx doesn't work"? > > If your program is called bz2.py, then rename it, and remove bz2.pyc. > Now things may work better. > > Jeff That is it exactly. thank you! From martin at v.loewis.de Tue Oct 19 14:32:07 2004 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 19 Oct 2004 20:32:07 +0200 Subject: md5 and large files In-Reply-To: <2tl2r4F20u7baU1@uni-berlin.de> References: <41743897$0$24525$9b622d9e@news.freenet.de> <2tl2r4F20u7baU1@uni-berlin.de> Message-ID: <41755da5$0$9599$9b622d9e@news.freenet.de> Tobias Pfeiffer wrote: >>You may well search the space of >>all possible files (in all file lengths), and never find a single >>file that hashes the same as your original file. > > > Are you sure about that? I have no clue about what the md5 algorithm > works like, but I'd think one could prove that with an number large > enough, every hash occurs twice. At last, md5 is not random. I'm not sure. However, I'm also not sure of the contrary. It is well possible to define a hash function which produces certain hash values only for a single input. Consider this hash function (operating on byte strings): def hash(s): if len(s)==100: for c in s: if c != 'X': break else: return 0 return len(s)+1 This hash function returns 0 only for a string of 100 Xs. For any other input, it returns a different value. So even though there are many collisions in the hash, there is one input which never collides. The same may true for md5. Whether it actually is true is still an open question, AFAIK. The proof could go either way: - here is string S which hashes as md5(S), and I can prove that no other string can possibly hash as md5(S). - here is a procedure which, for every hash value H, produces two distinct strings S1 and S2 so that H==md5(S1)==md5(S2). Regards, Martin From steve at holdenweb.com Tue Oct 5 20:10:44 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Oct 2004 20:10:44 -0400 Subject: printing file/image on default Printer In-Reply-To: References: Message-ID: Askari wrote: > Hi, > I search how "I" can printing file/image with a script but the user (who > use my script) must DO NOTHING (other that dealing with my GUI). e.g. : > with AdobeAcrobat, the user must click "ok" in the "pre"printing windows. > > My solutions, but NOT ok : > - Build a .pdf (with reportLab) and print with Adode > - Build a image file and print it with "DisplayImage.py" but don't work > (error raised) > > (note : the OS, for my problem, is just Windows) > > Someone have a other idea/solution? > > Askari Take as look at wxPython, which has a brilliant demo. One of the demo programs shows you how you can drive a printer from Python using the standard Windows print dialog (which is what I presume you are seeking). regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From jerf at jerf.org Tue Oct 19 16:24:27 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 19 Oct 2004 20:24:27 GMT Subject: bz2 & cpu usage References: Message-ID: On Tue, 19 Oct 2004 10:08:39 -0400, Brad Tilley wrote: > The part I wrote about the "Windows GUI" is not clear. I meant the Windows > XP Desktop. My script has no GUI. Sorry for the mix-up. Before going too deeply into programmatic solutions, I'd try your program on a completely different machine (different manufacturer or something so the hardware is different). Excepting maybe priority setting, which is a good idea anyhow. While this was par for the course for Win9x, XP really shouldn't be behaving like that in my experience. A little jumpy, maybe, but not "unusable". Either: * You're running it on a machine well below the stated XP requirements (I've jammed XP onto a Pentium 233 w/ 96MB ram, but I don't recommend that for most people; it was basically a server for me doing one specific task.), or * You're taking *way* too much data at a time, filling up your RAM, and causing excessive swapping (though you ought to notice this), or * You've got crappy hardware and your hardware can't handle the interrupt load from the IO and the graphics at the same time; this is typically caused by cheap motherboards, often from Via. If your problem is hardware, you've pretty much already lost and your only hope is different hardware. Otherwise, as a hack, you can decompress as a stream and use the sleep commands to voluntarily sleep for some period of time after some amount of time or data has gone by, but this will still cause some jumpiness. From agriff at tin.it Tue Oct 5 02:10:17 2004 From: agriff at tin.it (Andrea Griffini) Date: Tue, 05 Oct 2004 06:10:17 GMT Subject: Python in Process Control? References: Message-ID: On Sun, 03 Oct 2004 20:59:07 -0400, Peter L Hansen wrote: >Having companies always rewrite their own copy of something >from scratch is a stupid, stupid way to do business, when >their business is not supposed to be writing drivers for >obscure pieces of hardware. Actually I've observed that the "closed" behaviour is not only from companies; but even in the research field. For example on 3D graphics you can find a plethora of documents on the internet down to the level of the smallest detail and paper *sold* from universities are the exception. I saw this being the opposite (a lot of papers are sold, a few are free and they don't get to the details) even about problems that have been probably solved a jillion times like "good" path computation under dynamic constraints or motor control. In my case I preferred solving the problem myself for the context I faced instead of buying docs about the solution (after all I don't expect the quality of them to be terribly high... I wonder for example if researchers in this area buy each other papers to know what others are investigating in and what results they got). In this field seems to me that really people try to get above by standing on each other feet instead than on each other shoulders; but this doesn't look to me like just a software problem. May be there are reasons for this being the status quo... for example research in this area is terribly more expensive than in the pure software field where you can get quite far just with a $500 PC and some pizza. ... >I'd say the "best thing" to do would be to start by >collecting the various licenses involved and actually >looking them over. I haven't done that with PyGame, >but unless it includes GPL stuff, there's a decent >chance that there's no real impediment to using it >in a closed source product, except perhaps your guilt >at attempting to profit from the hard work of many >others without even a token attempt to contribute >something back to the community. ;-) A problem is the LGPL licensing that requires you to allow your users to re-link the program with a newer version of the library. This is IMO both basically a nonsense in this field (I can't think to a customer even *wanting* to change the library version in a NC machine he bought, often the investments are rather high and the approach I see is "if it works just don't dare to think about touching it") and annoying. Also I don't understand what is required if a new version of the library for example changes part of the interface ... does this imply you're forced to leave the source code so that it can be adapted to the new library interface (even if may be not the rights to use it past the re-linking requirement) ? For pygame I've rewritten (mostly as an exercise in writing python extensions) the part that I really need that is just a little part of the screen and surface handling as a C module ... after all I'm not going to need sounds or other fancy things present in pygame like CD, joystick, or movies. I don't know if this trying to be opaque to competitors is really the root of all evil... but even if this is the case I'm not in the position to decide about those issues. My impression is that being forced to be transparent if using python would simply mean wiping python out from the option list. Andrea From null at trit.org Tue Oct 19 08:49:21 2004 From: null at trit.org (Dima Dorfman) Date: Tue, 19 Oct 2004 12:49:21 +0000 Subject: Style question on recursive generators In-Reply-To: <1glwdd4.s05uuadrav97N%aleaxit@yahoo.com> References: <1glv17s.hq00886bg9exN%aleaxit@yahoo.com> <864d370904101807572c49d989@mail.gmail.com> <1F0E17D2-2137-11D9-8317-000A95EFAE9E@yahoo.com> <1glwdd4.s05uuadrav97N%aleaxit@yahoo.com> Message-ID: <20041019124703.GR660@trit.org> Alex Martelli wrote: > Dima Dorfman wrote: > > yield *other > > say: > a = b, *c, d > meaning the same as > a = (b,) + tuple(c) + (d,) > or the old, currently out of favour proposal > a, b, c, *d = e Both of these are intuitive to me. I'm generally in favor of expanding the use of '*' to mean aggregation in this manner, but someone else is gonna have to organize the crusade if they want one. > where d gets (an iterator for) 'the rest of e' after the first three > items of e are unpacked to a, b, and c. FWIW, the implementation for the unpacking case is mostly straight- forward (I did one a while back). The only caveat is what to do with *d. You suggest storing an iterator for the rest of e, but this is unuseful if e is a real sequence, like a tuple. It's easy enough to special-case tuples and lists, but what about other user-defined types? Maybe slice off the rest? Real iterators (iter(x) is x) would have to be treated specially in any case. From Anna at nospam.invalid Mon Oct 18 19:35:57 2004 From: Anna at nospam.invalid (Ann) Date: Mon, 18 Oct 2004 23:35:57 GMT Subject: Python + Java knowledge References: <41743e26$1@news.unimelb.edu.au> Message-ID: "Maurice LING" wrote in message news:41743e26$1 at news.unimelb.edu.au... > Hi, > > I've learnt and used Java and Python for a few years now, on bits of my > thesis work etc etc. I will have to say that I love both languages and > the possibilities they can provide. More recently, due to the toolkit > that I use, I've been using Python. And I found that my Jva knowledge > slacks a little. So, I'm looking for some tips on how to maintain the > knowledge on both areas. > > Has anyone done it? > > Thanks > Maurice I would say to look for some of those "what's different in xxx" files and go from there. From danb_83 at yahoo.com Tue Oct 5 04:43:18 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Oct 2004 01:43:18 -0700 Subject: New to Python: Features References: Message-ID: Richard Blackwood wrote in message news:... > Hi, I'm new to Python and I'd like to know if Python has the following > support: *please answer to each individually, thanks* Most of your questions are answered at http://docs.python.org/ > 1. Multi line comments No. But multi-line docstrings are supported. > 2. Functions as variables: > a. functions can be stored in variables, passed as arguments to > other functions, and returned as results. Yes. >>> def deriv(f, x, delta=1e-8): ... "Centered difference approximation of f'(x)" ... return (f(x + delta) - f(x - delta)) / (2 * delta) ... >>> deriv(lambda x: x * x, 2) 3.9999999756901161 > 3. Function nesting with proper lexical scope (i.e. closures) Yes. > 4. Operator overloading (inc. the ability to define new operators) Yes. This is done by defining the special methods __add__, __mul__, etc. > 5. Can I do this? print("Hello " .. "World") --> Hello World If ".." is supposed to be the string concatenation operator, then yes. >>> print "Hello " + "World!" Hello World! > 6. Constructors Yes. They're defined like this: class MyClass: def __init__(self, arg1, arg2): # ... and called like this: x = MyClass(arg1, arg2) > 8. "Repeat-Until" as in : > repeat > line = os.read() > until line ~= "" > print(line) There isn't a special syntax for posttest loops. You have to write them like while True: line = os.read() if not line: break print line > 10. Can I call an object's method as object:method(arg) and have that > translate into object.method(object, arg) >>> class MyClass: ... def foo(self, arg): ... pass ... >>> m = MyClass() >>> m.foo(0) >>> MyClass.foo(m, 0) > 11. Can I make dynamic statements and nature like with eval() in Javascript? Yes. >>> x = 1; y = 2 >>> z = eval("x + y") >>> exec "print z" 3 > 12. Can I make calls to a function with a varying number of arguments? Yes. >>> def func(fixedArgA, fixedArgB, *args): ... print "called with", 2 + len(args), "arguments" ... >>> func(1, 2, 3, 4) called with 4 arguments >>> func(1, 2, 3, 4, 5, 6) called with 6 arguments > 13. Named arguments Yes. >>> datetime.date(month=10, day=5, year=2004) datetime.date(2004, 10, 5) > 14. Tables with built-in methods for manipulation such as sort, etc. Try the built-in "list" type. Also, "dict". > 15. Table filters I'm not quite sure what you're asking. Do you mean something like >>> [n for n in xrange(2, 20) if isprime(n)] [2, 3, 5, 7, 11, 13, 17, 19] ? > 15. Proper Tail Call (otherwise known as Proper Tail Recursion) No. > 16. The ability to call a function without brackets Fortunately, no. > 17. Is the Python interpreter a JIT? Does it have a bytecode? Is it as > fast as Java? For the standard interpreter: No. Yes. No. But try Psyco (psyco.sourceforge.net). > 21. May modules be stored in variables, passed to and produced from > functions, and so forth? Yes. >>> import sys >>> import os >>> modules = [sys, os] >>> modules[1].getcwd() '/home/dan' > 22. Is the self parameter hidden from me as a programmer? Can I > hide/unhide it as I wish? No. > 25. A fully implemented .NET counterpart (I should be able to write > Python scripts for both with the same code) It's not fully implemented yet, but there is a .NET version (http://www.ironpython.org). > 33. Function/Method overloading No, but it can often be simulated by default parameters, or by "isinstance" checks. > 34. In pure Python, can I change and add new constructs to the Python > syntax? No. > 43. Embedding variables in strings like: print "Hello, World. Time: > #{Time.now}" No, but this can be written almost as easily using the % operator. >>> print "Hello, World. Time: %s" % datetime.datetime.now() Hello, World. Time: 2004-10-05 03:12:14.750796 or >>> now = datetime.datetime.now() >>> print "Hello, World. Time: %(now)s" % locals() Hello, World. Time: 2004-10-05 03:14:01.111879 > 44. Case or Switch statements with functionality as such: > case score > when 0...40 > puts "Horrible!" > when 40...60 > puts "Poor" > when 60...80 > puts "You can do better!" > when 80...95 > puts "Now that's acceptable" > when 95..100 > puts "That the best you can do? j/k" > else > puts "Didn't take the test?" > end Python does not have a switch/case construct. Your example would normally be written as an if...elif...else ladder. From pythongnome at hotmail.com Wed Oct 13 17:47:45 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 13 Oct 2004 21:47:45 GMT Subject: EVIL AMERICAN GOVT (aka FBI) is full of SADISTS and PERVERTS References: <11a9e0b9.0410100611.1d8028b0@posting.google.com> Message-ID: <5ohbd.3444$SZ5.1968@newsread2.news.atl.earthlink.net> Sorry about that. "Odysseus" wrote in message news:odysseus1479-at-580B18.19305912102004 at news.telus.net... > In article , > "Lucas Raab" wrote: > >> You can't help but love these little messages. >> >> "vicky" wrote in message >> news:11a9e0b9.0410100611.1d8028b0 at posting.google.com... >> > SUMMARY: >> > >> > THREE YEARS of and continuing MENTAL TORTURE, TERRORISM, SADISM and >> > BLATANT human rights violations by FBI SADISTS and PERVERTS. >> > > > [snip nearly 600 lines] > > Love them or not, I don't think anyone needs them reposted in their > entirety, thanks. > > -- > Odysseus From grante at visi.com Mon Oct 4 23:43:24 2004 From: grante at visi.com (Grant Edwards) Date: 05 Oct 2004 03:43:24 GMT Subject: New to Python: Features References: <4162142c$0$59860$a1866201@newsreader.visi.com> Message-ID: <4162185c$0$59860$a1866201@newsreader.visi.com> On 2004-10-05, Richard Blackwood wrote: > Grant Edwards wrote: > >>>Hi, I'm new to Python and I'd like to know if Python has the following >>>support: *please answer to each individually, thanks* >> >>Wow. Rude much? >> >>http://www.catb.org/~esr/faqs/smart-questions.html >>http://www.python.org/ >> > What does "Rude much" mean? You've _got_ to be kidding... -- Grant Edwards grante Yow! An Italian is COMBING at his hair in suburban DES visi.com MOINES! From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Oct 11 11:42:17 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 11 Oct 2004 17:42:17 +0200 Subject: Python to Python communication In-Reply-To: References: Message-ID: <416aa9d9$0$566$e4fe514c@news.xs4all.nl> Harald Massa wrote: > pyro - Python Remote Objects. Irmen de Jong has a "get Firefox" icon on > it's page and he plays with the name "pyro", which makes a good > impression. Hey, thanks :) > It looks rather "ripe", but: he is talking about "pyro 4.0" > which will be incompatible with pyro 3.4 and a total redesign. That makes > me shudder. Pyro is "ripe"... version 3.0 was released Q4, 2002, so the 3.x versions have been around and in active use for 2 years now. I've been talking about Pyro 4.0 for a long time, but we haven't even begun the real design of it. Partly because of lack of time, partly because Pyro 3.x does its job so well (not my own words). What is it that makes you shudder? If you don't want to switch to Pyro 4.0 once (if??) it is released, just continue using Pyro 3.x. I have no intentions of abandoning the 3.x version: if there is an itch, or a bug, it will be addressed. Regards, Irmen de Jong From kraus at hagen-partner.de Thu Oct 7 02:48:19 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 07 Oct 2004 08:48:19 +0200 Subject: 2 Newbie questions. In-Reply-To: References: Message-ID: Len Sumnler wrote: > Hi All > > I am running SuSe Linux ver. 9.0. I have written the famous "Hello > World" program and want to run it as an executable. I have searched > the net and performed chmod +x mypython.py and added as the first > line of my program #!/usr/bin/env python. When I try to run the > program as follows $ mypython.py I get the error message of, "bash: > mypython.py: command not found". What am i doing wrong. Your current directory is not in your PATH environment variable, so you have to call it with ./mypython.py or set your PATH. BTW your prompt looks like you are user "root", don't do that, login as a normal user! > Second, I am looking for a good online tutorial for some one who > knows other programming languages assembler, cobol, etc any > suggestions. http://www.python.org/topics/learn/prog.html > Thanks Len Sumnler, Jr HTH, Wolfram From jwaixs at linuxmail.org Sun Oct 10 16:19:01 2004 From: jwaixs at linuxmail.org (jwaixs) Date: Sun, 10 Oct 2004 22:19:01 +0200 Subject: Problem executing IDLE References: <_Ofad.102571$He1.29537@attbi_s01> Message-ID: <3606b$4169958e$53e8229a$5021@freeler.nl> Len Sumnler wrote: > Hi all > > I am trying to learn python. When I try to run IDLE on my Windows XP it > does not appear to run. Does anyone know why this is happening. > > Thanks > Len Sumnler Is it possible to run the interactive mode in dos of python? ----------------------------JW-19-XS----------------------------------- From kartick_vaddadi at yahoo.com Mon Oct 25 08:56:34 2004 From: kartick_vaddadi at yahoo.com (kartik) Date: 25 Oct 2004 05:56:34 -0700 Subject: int/long unification hides bugs Message-ID: <940ee3e8.0410250456.65445bbd@posting.google.com> there seems to be a serious problem with allowing numbers to grow in a nearly unbounded manner, as int/long unification does: it hides bugs. most of the time, i expect my numbers to be small. 2**31 is good enough for most uses of variables, and when more is needed, 2**63 should do most of the time. granted, unification allows code to work for larger numbers than foreseen (as PEP 237 states) but i feel the potential for more undetected bugs outweighs this benefit. the other benefit of the unification - portability - can be achieved by defining int32 & int64 types (or by defining all integers to be 32-bit (or 64-bit)) PEP 237 says, "It will give new Python programmers [...] one less thing to learn [...]". i feel this is not so important as the quality of code a programmer writes once he does learn the language. -kartik From jonathan at gennick.com Wed Oct 27 10:05:07 2004 From: jonathan at gennick.com (Jonathan Gennick) Date: Wed, 27 Oct 2004 10:05:07 -0400 Subject: Looking for more Cookbook contributors Message-ID: <0kavn019dk6vf7ini32t3muc9e6r9j7t1n@4ax.com> Once again, I find myself looking to contact contributors to the Python Cookbook, this time for chapter 2. If you know how to contact any of the people listed below, please contact me at jgennick at oreilly.com . It would be a big help. Matteo Dell'Amico Sebastien Keim Yakov Markovitch Amos Newcombe John Nielsen Chris Perkins Nick Perkins Noah Spurrier Chui Tey Robin Thomas Jeremy Zucker Again , any help in contacting these people would be much appreciated. Best regards, Jonathan Gennick Editor, O'Reilly Media 906.387.1698 mailto:jgennick at oreilly.com From steve at holdenweb.com Wed Oct 6 18:40:26 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Oct 2004 18:40:26 -0400 Subject: Parallelization on muli-CPU hardware? In-Reply-To: <3nQ8d.16242$5O5.16154@news-server.bigpond.net.au> References: <6db3f637.0410042045.2171ad5f@posting.google.com> <6db3f637.0410052100.31bbe86f@posting.google.com> <3nQ8d.16242$5O5.16154@news-server.bigpond.net.au> Message-ID: Neil Hodgson wrote: > Steve Holden: > > >>Until that time I hadn't realized that the laptop was built on a >>multi-core processor. > > > It is more likely you had a machine that featured 'hyperthreading' which > is much less than multiple cores. Somewhere between two sets of registers > and two processors. > Aah, the penny drops and I realize you are indeed correct. It's using hyperthreading. > >>Fortunately the task was easily partitioned into >>two independent processes, each dealing with a separate set of database >>rows, so the run completed well under the necessary 24 hours. > > > Did you measure a real performance increase, that is, elapsed time to > completion of job? Many benchmarks show minimal or even negative performance > improvements for hyperthreading. Relying on secondary indicators such as CPU > busyness can be misleading. > No, I *was* actually measuring elapsed time to completion, and I was surprised that the speedup was indeed just about linear. Not often you come across a task that can be cleanly partitioned in that way. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From irmen at -nospam-remove-this-xs4all.nl Mon Oct 4 14:42:44 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 04 Oct 2004 20:42:44 +0200 Subject: Encouraging Python adoption in your organization In-Reply-To: <40a939c9.0410021235.623eb6f6@posting.google.com> References: <40a939c9.0410021235.623eb6f6@posting.google.com> Message-ID: <416199a3$0$65124$e4fe514c@news.xs4all.nl> Alia Khouri wrote: > Recently, I've been fortunately placed in a position to possibly > mandate the use of python for certain tasks in my new organization. [...] > Given this context, I'm mulling over strategies to encourage the > productivity-enhancing benefits and 'joy' of python scripting to my > developers. Of course, I'd rather be persuasive than coercive. > > Any ideas? My Python-compared-to-Java pages may be of some interest: http://www.razorvine.net/python/PythonForJavaProgrammers They don't really talk about Python's strong points or why you "should dump Java and go with Python bla bla", but they do provide a quick means of showing the way Python works to people already proficient in Java. --Irmen From __peter__ at web.de Wed Oct 13 12:18:02 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Oct 2004 18:18:02 +0200 Subject: Order in metaclass References: <416cf48f.140377111@news.oz.net> Message-ID: Carlos Ribeiro wrote: > executed (which count() can guarantee). There are two situations where > the simpler counter works, but the getframe hack doesn't: > > -- if I have a loop inside my class that is used to declare bunch of > attributes, all of them will have the same line number... but a > different sequence number if the simpler method is chosen. > > -- if a function is called that returns a bunch of attributes (not > common practice, but still possible). All attributes are at the same > line in this case. Example: > > class Foo: > a,b,c?=?myfunc(...) Do you have an example handy? I had so far no success breaking Bengt's code. Peter From theller at python.net Mon Oct 18 04:54:17 2004 From: theller at python.net (Thomas Heller) Date: Mon, 18 Oct 2004 10:54:17 +0200 Subject: py2exe with opengl References: Message-ID: <1xfwieyu.fsf@python.net> Szucs Szabolcs Laszlo writes: > Hello, > > I do `python setup.py py2exe --exclude=OpenGL --includes=Tkinter'. > It runs, OK. No error messages. I copy the whole > OpenGL dir. next to the .exe file. > > When I run the .exe, it don't find the OpenGL module. Why? I guess you have to insert the directory of the .exe into sys.path - py2exe doesn't do this itself. Thomas From fredrik at pythonware.com Sun Oct 10 03:39:15 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 10 Oct 2004 09:39:15 +0200 Subject: module name not recognized References: Message-ID: Darren Dale wrote: >I have built two basic modules using distutils. One of them installs fine, > but the other, I can't import modules from it. I've been pouring over the > code and I cant find the problem. > > I know the file has been copied to site-packages/mypackage, but I cant do > > from mypackage import mymodule really? do you mean that you could type that into your mail program, but not into a Python program? that's weird... (read on) > Could I get suggestions as to why a module would be installed but not > registered? if you run python with the -vv option, it tells you where it looks. $ python -vv ... >>> from mypackage import mymodule # trying mypackage.so # trying mypackage.py # trying mypackage.pyc ... btw, note that if that import finds a mypackage without a mymodule, it says ImportError: cannot import name mymodule if it cannot find mypackage itself, it says ImportError: No module named mypackage (this is why you should *always* include tracebacks when asking about an error... "can't do" or "doesn't work" or "an error" or even "an import error" doesn't contain all the information you have, so you're forcing us to guess. don't do that, if you can avoid it) From aleaxit at yahoo.com Sun Oct 17 11:13:24 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 17 Oct 2004 17:13:24 +0200 Subject: operation with strings and numbers References: Message-ID: <1glsu2s.t92mev7jx81cN%aleaxit@yahoo.com> Hellas wrote: > I told "italian boy" only for my English that's orrible > > Everyone says that in italian the english school is not good May I suggest newsgroup it.comp.lang.python -- there, we talk about Python in Italian. Posso suggerire il gruppo it.comp.lang.python in cui parliamo di Python in Italiano. Alex From peter at engcorp.com Sat Oct 9 08:57:20 2004 From: peter at engcorp.com (Peter L Hansen) Date: Sat, 09 Oct 2004 08:57:20 -0400 Subject: How do I refer to a data file relative to a package or installation directory? In-Reply-To: References: Message-ID: Parzival wrote: > I have a package that includes some data files. I am planning to use a > distutils setup script to install the package. How can I compute a path > name for such a data file that will always be relative to my package > root directory (i.e. both when installed, and in my development directory?) > > Or to rephrase, say the data file is mypkg/data/foo.dat relative to the > package root "mypkg" (the directory that holds __init__.py). Is there an > enquiry that will return the absolute path prefix for mypkg? Presumably you meant that relative to the package root "mypkg", the data file is actually at "data/foo.dat", or as some might write it "./data/foo.dat"? If not, you've got an extra layer there confusing things. Basically, just use __file__ inside the __init__.py module to find that file's location, then use os.path.split() to pull off the path part and os.path.join() to add the "data/foo.dat" part. If that's not enough, please post some kind of code snippet to help explain things better. -Peter From daniel at syrinx.net Tue Oct 12 07:50:44 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Tue, 12 Oct 2004 07:50:44 -0400 Subject: Dict lookup shortcut? In-Reply-To: References: Message-ID: <2t1uifF1q15srU1@uni-berlin.de> M. Clift wrote: > Hi All, > > Can someone tell me is there a shorthand version to do this? > > l1 = ['n1', 'n3', 'n1'...'n23'...etc...] > > Names = {'n1':'Cuthbert','n2' :'Grub','n3' :'Dibble' etc...} > > for name in l1: > print Names[name], > > Rather than listing all the name+numbers keys in the dictionary can these > keys be shortened somehow into one key and a range? > > Thanks, > > M > > I'm not sure what you're trying to do, but you should probably be doing this instead: names = {'n1':'Cuthbert', 'n2':'Grub', 'n3':'Dibble'} for key in names.keys(): print names[key], No need for the initial list. Alternatively, you could just have all the names in a list to start with and iterate over that: names = ['Cuthbert', 'Grub', 'Dibble'] for name in names: print name, Dan NB: all code untested From i_munoz at euskalnet.net Fri Oct 1 07:52:54 2004 From: i_munoz at euskalnet.net (=?ISO-8859-1?Q?I=F1igo?=) Date: Fri, 01 Oct 2004 13:52:54 +0200 Subject: Python libraries for playing MP3 files Message-ID: <415D4516.4010207@euskalnet.net> Hello everybody: I am newbie in python. I am searching libraries in python capable of playing MP3/OGG files, stopping and so on. I don't know if that is possible using python. That was my doubt. Thank you for your answers From jdhunter at ace.bsd.uchicago.edu Sun Oct 17 15:40:25 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 17 Oct 2004 14:40:25 -0500 Subject: interface boilerplate Message-ID: In matplotlib, a plotting library with an OO API and a matlab-like procedural interface, I have a lot of functions defined in the matlab interface module that wrap similarly named class methods defined in the Axes class of the axes module. Eg, the Axes class defines a plot method and the matlab interface defines a plot function that gets the current Axes instance, calls the plot method on that instance, and does some error handling. Here is the matlab interface wrapper (gca() returns the current Axes instance) def plot(*args, **kwargs): try: ret = gca().plot(*args, **kwargs) except ValueError, msg: msg = raise_msg_to_str(msg) error_msg(msg) else: draw_if_interactive() return ret plot.__doc__ = Axes.plot.__doc__ This is mostly boilerplate code that a lot of matlab interface functions use, and I'd like to automatically generate it. This appears to (mostly) work def _wrap_axfunc(name): def wrapper(*args, **kwargs): try: func = getattr(gca(), name) ret = func(*args, **kwargs) except ValueError, msg: msg = raise_msg_to_str(msg) error_msg(msg) else: draw_if_interactive() return ret wrapper.__doc__ = getattr(Axes, name).__doc__ #wrapper.__name__ = name return wrapper plot = _wrap_axfunc('plot') The only problem I've seen so far is that the name of the function in pydoc string is 'wrapper', and I want it to appear as "plot". I tried setting the __name__ attribute, but it is read only. Any suggestions on how to best define these matlab interface functions by automatically wrapping the Axes instance functions? I'd like to support python2.2 so python2.2 compliant solutions especially welcome. JDH From jdhunter at ace.bsd.uchicago.edu Thu Oct 14 13:46:15 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 14 Oct 2004 12:46:15 -0500 Subject: get list of callable methods Message-ID: What is the best way to get a list of all functions actually defined in a module, ignoring those functions that the module may have imported but not defined? The following gets a list of all the callables, but includes functions that some.module imports funcs = [] for o in dir(some.module): if o.startswith('_'): continue p = getattr(some.module, o) if not callable(p): continue funcs.append(p) JDH From klaus_neuner82 at yahoo.de Wed Oct 6 03:10:53 2004 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 6 Oct 2004 00:10:53 -0700 Subject: re bug References: <3e96ebd7.0410050057.29a15174@posting.google.com> Message-ID: <3e96ebd7.0410052310.7fc1bff1@posting.google.com> > Yes. Use signal.alarm(). See: > > http://www.python.org/doc/current/lib/node304.html Thank you very much. You saved me a lot of time. From steve at holdenweb.com Mon Oct 11 08:16:01 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 11 Oct 2004 08:16:01 -0400 Subject: (solved) smtplib, capturing output from set_debuglevel ?? In-Reply-To: References: <00ab01c4ad2a$bfe9aa90$ccbefea9@twilliams><41668EDD.8090808@holdenweb.com> <00e701c4ad3f$b5e78390$ccbefea9@twilliams> Message-ID: <416A7981.1060601@holdenweb.com> Tim Williams wrote: > ----- Original Message ----- > From: "Tim Williams" > >>----- Original Message ----- >>From: "Steve Holden" > > [snip] > >>Yeah, I did wonder about changing the code (though it's not my first >>choice. I've done it before and caught a crab later), or could I do it >>with Subclassing? >> [...Tim fixes smtplib...] > > Took me about 4 minutes !! > > now I can call s.debug() and get a list containing the debug information. > s.debug() can be called at anytime including after s.quit() > > As a side benefit, I can use s.do_debug( msg ) at any time to get the > program to add (comment) lines to the debug information. This will be > useful when reading the full retrieved debug information at a later date. > > set_debuglevel() works exactly as it did before. > > I have to tidy up the formatting/handling of the messages, and I think I'm > going to add an option to retrieve the debug information without the > message data (as its usually superfluous to the debugging process) , but > other than that it does just what I need already. > > Is it worth asking for something like this to be added permanently to > smtplib, I can't be the only one that needs to log outgoing smtp > conversations, or debug to a file/log ? > > Thanks for everyone's help > Correct action under these circumstances would be to submit a patch. This sounds intimidating of you've never done it before, but the process isn;t that difficult once you've created your SourceForgew account, and there are meny experienced hands on the list who will help you if you get stuck. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From lonetwin at gmail.com Wed Oct 27 08:38:19 2004 From: lonetwin at gmail.com (Steve) Date: Wed, 27 Oct 2004 18:08:19 +0530 Subject: Example of how to use logging for both screen and file In-Reply-To: References: <2e37dc1.0410221237.2609dcad@posting.google.com> <2e37dc1.0410230702.38bb4912@posting.google.com> Message-ID: <5a309bd3041027053844d82610@mail.gmail.com> Hi Ville, On 27 Oct 2004 15:08:16 +0300, Ville Vainio wrote: > >>>>> "Steve" == Steve writes: > > Steve> flog = logging.getLogger("mylog") > Steve> slog = logging.getLogger("mylog.slog") > > I'm a logging newbie, but - > > You shouldn't "get" loggers according to the "log name", but rather > the application area name. I.e. > > log = logging.getLogger("myApp") > > And then add different handlers to the same log object. I.e. don't > create several loggers, create several handlers for the same Logger > object, as I did in the initial example of this thread (just > substitute StreamHandler w/ sysloghandler). I do understand that. The code above was just an example. What I do want is, different loggers for different areas of the application. let me explain that. All the components in the system would have to log to syslog, some components additionally would log to other places (like files). So, for example: core_app_logger = logger.getLogger('core') sub_component_logger = logger.getLogger('core.sub_component') core_app_logger.addHandler(logging.handler.SysLogHandler()) sub_component_logger.addHandler(logging.FileHandler('/tmp/sub_comp_log") Now, because of the way logging is designed, any message sent to sub_component would also get handled by the core-logger's handler (SysLogHandler). ....or so it would seem ...I still haven't got the SysLogHandler working :( Regards Steve > > > > -- > Ville Vainio http://tinyurl.com/2prnb > -- > http://mail.python.org/mailman/listinfo/python-list > From charleshixsn at earthlink.net Tue Oct 26 21:33:49 2004 From: charleshixsn at earthlink.net (Charles Hixson) Date: Tue, 26 Oct 2004 18:33:49 -0700 Subject: What does [...] mean? Message-ID: <417EFAFD.6090509@earthlink.net> I'm getting a list that I build which when printed is displaying, well, e.g.: d = << ['electronic', 'path', 'open', 'for', 'the', 'next', 'reader', '.', [...], 'Do', 'not', 'remove', 'thi', '.', [...]] >> Clearly I have a problem with the truncation of the final this, but what does the internal [...] mean? It's generated by doing: print "d = <<", d, ">>" If it matters, I'm using Python 2.3.4 on Linux. From claird at lairds.us Tue Oct 5 00:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 05 Oct 2004 04:08:05 GMT Subject: Miscellaneous personal prejudices (was: Dr. Dobb's Python-URL! - weekly Python news and links (Oct 4)) References: Message-ID: <36i932-lr5.ln1@lairds.us> In article , Ville Vainio wrote: . [lots of other important and exciting material] . . > Jacek Generowicz is looking for a metaclass that would allow > introducing several methods with the same name in a class, spawning a > long and educational thread about metaclasses and learning a simpler > way of achieving the goal using the upcoming decorator syntax. > http://groups.google.com/groups?threadm=tyfekkoeyk2.fsf%40pcepsft001.cern.ch . . . > Srijit Kumar Bhadra posts a version of the same program using > PythonNet, IronPython and Boo, showcasing the similarity in the way > code is written. > http://groups.google.com/groups?selm=221d8dbe.0409302041.3798265d%40posting.google.com . . . > control applications. A discussion about the sorry state of software > for industrial control in general, and the suitability of Python in > particular ensues. People actually seem to have plans for improving . . . > Andrew Kuchling would like to see the focus of Python development > moving away from hacking the interpreter and towards improving the > standard library. > http://www.amk.ca/diary/archives/cat_python.html#003382 . . . Magazines have definite appetites for, among other things, articles of the "What's new in Release 2.x and how to make best use of it" and "X-ing with three different technologies: concrete examples of good style" sorts. I feel responsible for escalating the pugnacity of the process- control thread. That adds to my responsibility to clarify: FAR more than any narrow technical complaints about the software of industrial automation I have, I'm ready to take over as dictator and change the *approach* of the vendors. It's not so much that I think the applications and libraries are bad, as that they're senselessly closed and ludicrously misdocumented. In general. In my opinion. Finally, AMK is soooooooo right. His statement is so perfect, even I can't find anything to add to it. From moof at boof.moof Mon Oct 11 05:47:48 2004 From: moof at boof.moof (Roose) Date: Mon, 11 Oct 2004 09:47:48 GMT Subject: String replace with return value? Message-ID: <8Fsad.11445$nj.10631@newssvr13.news.prodigy.com> How can I do a "".replace operation which tells me if anything was actually replaced? Right now I am doing something like: if searchTerm in text: text = text.replace( searchTerm, 'other' ) But to me this seems inefficient since the 'in' operation will search through the whole string, and then the 'replace' will as well. The strings are quite large, they're whole web pages. Thanks for any help. Roose From cjbottaro at alumni.cs.utexas.edu Wed Oct 13 13:58:21 2004 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Wed, 13 Oct 2004 12:58:21 -0500 Subject: MySQLdb exception documentation...? Message-ID: The MySQLdb (mysql-python) documentation doesn't really cover which functions (methods) throw what exceptions. Where can I find this info? Development is such a pain when unhandled exceptions keep halting the program! Thanks for the help. From wolfgang.keller.nospam at gmx.de Wed Oct 6 02:46:30 2004 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Wed, 6 Oct 2004 08:46:30 +0200 Subject: Python in Process Control? References: Message-ID: <1skb5kv22vk9g$.pxvuoyw24hel.dlg@40tude.net> Am Fri, 01 Oct 2004 09:14:40 -0400 schrieb Peter L Hansen: > Wolfgang Keller wrote: >> There seem to be some Python bits out there, for example MatPLC and >> Lintouch use Python and some commercial products as well (PyDACHS), but >> unfortunately there doesn't seem to be a more or less consistent library >> for industrial automation or a coordinated effort to build up one. > > What, in your opinion, would it take to start one? Work? >:-> A SIG would already be more than nothing, then start to set up a site with a few links to things that are already available (whether free or commercial), then start to collect things which are open-source and/or free, then start to improve them and complete what's missing andsoon... I have a dream :-): A Python library for industrial automation that is as complete and well-documented as, for example, twisted for TCP/IP communication. You need an OPC server/client? - Import a module, instantiate a class and there you go. You need to talk ? Same procedure... Ah yes, and obviously have Python ported to all those RTOSes and embedded controllers (PowerPC, StrongArm/XScale, MIPS, SH)... RRRRRIIIIINNNNNNGGGGGGG - Uh, what?! Already time to get up and go to the office? - Please NO! >:-> Best regards, Wolfgang Keller From adalke at mindspring.com Mon Oct 25 15:25:41 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 25 Oct 2004 19:25:41 GMT Subject: 2 questions about scope In-Reply-To: References: <20041025105736.0B0D.JCARLSON@uci.edu> Message-ID: Neal D. Becker wrote: > Actually, these don't introduce a block in c++ either. The braces do. In C++ for (int i=0; i<100; spam(i), ++i) ; the 'i' is in the for statement's scope even though there are no braces. To respond to the OP's question, one big difference between C++ and Python's scoping systems is that Python doesn't have a distinct variable declaration. In C++ you could say { char i[] = "something"; ... for (int i=0; i<100; i++) { ... } } and the compiler knows you want a new variable 'i'. In Python, the equivalent might be i = "something" for i in range(100): ... There's nothing to tell Python that the 'i' used in the for statement is different than the i in the outer scope, so it assumes you meant the same variable. The only scopes created in Python are for modules, classes, and functions. As I pointed out a couple weeks ago, you could fake scope with a class statement, as in i = "something" class scope: for i in range(100): ... but you really shouldn't. Or use a function scope, i = "something" def scope(): for i in range(100): ... scope() I mostly use the last when I want some non-trivial initialization in my module and don't want the various variables hanging around in the process space. I'll also follow it up with a "del scope" so that no one can reference the initialization code. Andrew dalke at dalkescientific.com From carribeiro at gmail.com Sun Oct 31 16:37:50 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 31 Oct 2004 19:37:50 -0200 Subject: Python in Free Music Software In-Reply-To: <40a939c9.0410310827.112f13a1@posting.google.com> References: <40a939c9.0410291820.fada696@posting.google.com> <40a939c9.0410310827.112f13a1@posting.google.com> Message-ID: <864d370904103113373b9698f0@mail.gmail.com> Why not post this list on the main Python Wiki? It seems something nice to have there... On 31 Oct 2004 08:27:56 -0800, Alia Khouri wrote: > I just realized how badly worded the subject line of the prior posting > was on this topic... ;-) > > Anyways, > > Here's an update to the list (which is not comprehensive at this > stage), but which includes items that haven't been mentioned in Pypi > or in Parnassus: > > > Hi, > > > > Here are the results (in no particular order) of an informal survey of > > open-source / free music applications which use python in some form or > > the other. If you know of any other other examples please add them to > > the list. > > > > Enjoy (-; > > > > AK > > > > ---------------------------------------------------------------------- > > Survey of use of Python Language in Open-source / Free Music Software > > ---------------------------------------------------------------------- > > > > pymps > > http://www.anti-particle.com/pymps.shtml > > Pymps is the PYthon Music Playing System - a web based mp3/ogg > > jukebox. It's written in Python and utilises the PostgreSQL database. > > > > m3ute2 > > http://sourceforge.net/projects/m3ute2/ > > m3ute2 is program for copying, moving, and otherwise organizing M3U > > playlists and directories. m3ute2 can also generate detailed reports > > about lists of files. > > > > fmod > > http://www.fmod.org/ > > FMOD is the fastest, most powerful and easiest to use sound system on > > Windows, Linux, and Windows CE there is, and now Macintosh, > > GameCube, PS2 & XBox!. FMOD supports 3d sound, midi, mods, mp3, ogg > > vorbis, wma, aiff, recording, obstruction/occlusion, cd playback > > (analog or digital), cd ripping, mmx, internet streaming, dsp effects, > > spectrum analysis, user created samples and streams, synchronization > > support, ASIO, EAX 2&3, C/C++/VB/Delphi and more. > > > > pysonic > > http://pysonic.sourceforge.net/ > > pySonic is a Python wrapper around the high performance, cross > > platform FMOD sound library. You get all the benefits of the FMOD > > library, but in a Pythonic, object oriented package. > > > > PMIDI > > http://sourceforge.net/projects/uncassist > > The PMIDI library allows the generation of short MIDI sequences in > > Python code.The interface allows a programmer to specify songs, > > instruments, measures, and notes. Playback is handled by the Windows > > MIDI stream API so proper playback timing is handled by the OS rather > > than by client code. The library is especially useful for generating > > earcons. > > > > PythonMIDI > > http://www.mxm.dk/products/public/pythonmidi > > The Python Midi package is a collection of classes handling Midi in > > and output in the Python programming language. > > > > PythonSound > > http://pythonsound.sourceforge.net/ > > The Python Sound Project aims to develop a productive community around > > Python, Csound and other synthesis engines as tools for algorithmic > > and computer assisted composition of electroacoustic music. > > > > AthenaCL > > http://www.flexatone.net/athena.html > > AthenaCL is an open-source, cross-platform, command-line program that > > functions as both a pitch (class) set theory utility (capable of both > > set and voice-leading modeling and analysis) as well as an > > object-orientated, Python-scriptable algorithmic front-end to Csound. > > Combining these features allows rapid and flexible scoring of Csound > > instruments with the elegance of Python-written texture algorithms. > > These simple algorithms allow the organization of pitch-materials by > > ordered content-groups, employing 12-tone set-class and pitch-class > > notations. Rather than writing its own music, AthenaCL is a > > compositional assistant: the algorithms create complex textural > > surfaces, leaving the limitless mixture and placement of these > > textures and their attributes entirely in the hands of the composer. > > > > PyJack > > http://www.a2hd.com/software/ > > This is a Python C extension module which provides an interface to the > > Jack Audio Server. It is possible to access the Jack graph to perform > > port connections/disconnections, monitor graph change events, and to > > perform realtime audio capture and playback using Numeric Python > > arrays. This is released under the GPL. > > > > Csound / CsoundVST > > http://www.csounds.com/ > > Csound is a programming language designed and optimized for sound > > rendering and signal processing. The language consists of over 450 > > opcodes - the operational codes that the sound designer uses to build > > "instruments" or patches. Although there are an increasing number of > > graphical "front-ends" for the language, you typically design and > > modify your patches using a word processor. Usually, you create two > > text files - a .orc (orchestra) file containing the "instruments," and > > a .sco (score) file containing the "notes." In Csound, the complexity > > of your patches is limited by your knowledge, interest, and need, but > > never by the language itself. For instance, a 22,050 oscillator > > additive synthesizer with 1024 stage envelope generators on each is > > merely a copy-and-paste operation. The same goes for a 1 million voice > > granular texture! Have you ever dreamed of sounds such as these? Well > > in Csound you can. And in Csound these dreams can come true! > > > > dublin > > http://seqdublin.sourceforge.net/ > > Dublin is an object oriented framework to generate events in pd. Every > > objects is defined in python and then it interacts with other objects > > in pure-data. The goal is not only the provide an external python > > facility to pd but also to give the functionality of a sequencer. As > > for the user interface, it uses Idle, the Python IDE to edit and run > > event scripts. > > > > MusicKit > > http://musickit.sourceforge.net/ > > The MusicKit is an object-oriented software system for building music, > > sound, signal processing, and MIDI applications. It has been used in > > such diverse commercial applications as music sequencers, computer > > games, and document processors. Professors and students in academia > > have used the MusicKit in a host of areas, including music > > performance, scientific experiments, computer-aided instruction, and > > physical modeling. Using the Python to Objective C bridge PyObjC > > enables applications and utilities to be written in Python, an > > interpreted object-oriented language. > > > > GNU Solfege > > http://solfege.org/ > > GNU Solfege is a computer program written to help you practice ear > > training.It can be useful when practicing the simple and mechanical > > exercises. > > > > Snack > > http://www.speech.kth.se/snack/ > > The Snack Sound Toolkit is designed to be used with a scripting > > language such as Tcl/Tk or Python. Using Snack you can create powerful > > multi-platform audio applications with just a few lines of code. Snack > > has commands for basic sound handling, such as playback, recording, > > file and socket I/O. Snack also provides primitives for sound > > visualization, e.g. waveforms and spectrograms. It was developed > > mainly to handle digital recordings of speech, but is just as useful > > for general audio. Snack has also successfully been applied to other > > one-dimensional signals. The combination of Snack and a scripting > > language makes it possible to create sound tools and applications with > > a minimum of effort. This is due to the rapid development nature of > > scripting languages. As a bonus you get an application that is > > cross-platform from start. It is also easy to integrate Snack based > > applications with existing sound analysis software. > > > > Pygame > > http://pygame.org/ > > Pygame is a set of Python modules designed for writing games. It is > > written on top of the excellent SDL library. This allows you to create > > fully featured games and multimedia programs in the python language. > > Pygame is highly portable and runs on nearly every platform and > > operating system. > > > > Pyper > > http://www.stanford.edu/~andyszy/pyper/ > > Pyper is a musical development environment. It allows you to write > > Python scripts that generates music in real-time. Pyper uses QuickTime > > Musical Instruments for synthesis. > > blue > http://csounds.com/stevenyi/blue/index.html > blue is a java program for use with Csound. It's interface is much > like a digital multitrack, but differs in that there timelines within > timelines (polyObjects). This allows for a compositional organization > in time that seems to me to be very intuitive, informative, and > flexible. soundObjects are the building blocks within blue's score > timeline. soundObjects can be lists of notes, algorithmic generators, > python script code, csound instrument definitions, and whatever > plugins that are developed for blue. these soundObjects may be text > based, but they can be completely GUI based as well. > > ID3.py > http://id3-py.sourceforge.net/ > This module allows one to read and manipulate so-called ID3 > informational tags on MP3 files through an object-oriented Python > interface. > > id3reader.py > http://www.nedbatchelder.com/code/modules/id3reader.html > Id3reader.py is a Python module that reads ID3 metadata tags in MP3 > files. It can read ID3v1, ID3v2.2, ID3v2.3, or ID3v2.4 tags. It does > not write tags at all. > > PyID3 > http://icepick.info/projects/pyid3/ > pyid3 is a pure python library for reading and writing id3 tags > (version 1.0, 1.1, 2.3, 2.4, readonly support for 2.2). What makes > this better than all the others? Testing! This library has been > tested against some 200+ MB of just tags. > > OSC.py > http://web.tiscali.it/mupuxeddu/csound/OSC.py > Python classes for OpenSoundControl library client functionality. The > OSC homepage is at http://cnmat.cnmat.berkeley.edu/OpenSoundControl/ > > PMask > Python implementation of CMask, a stochastic event generator for > Csound. > http://web.tiscali.it/mupuxeddu/csound/index.html > > winmidi.pyd > http://www.sabren.net/code/python/midi/ > A demo? of a python extension interfacing to the native windows midi > libs. This was probably a development from this point > http://www.sabren.net/rants/2000/01/20000129a.php3 > > PyMIDI > http://www.hyperreal.org/~est/python/MIDI/ > The MIDI module provides MIDI input parsers for Python. > > Nam: not about music > http://www.quitte.de/nam.html > A Python Extension for Digital Music Applications. Its purpose is > Flexible realtime MIDI and audio processing and sequencing. > > midi.py > http://groups.google.com/groups?hl=en&selm=3C0F67FE.96E7CAE8%40alum.mit.edu > Python MIDI classes: meaningful data structures that represent MIDI > events and other objects. You can read MIDI files to create such > objects, or generate a collection of objects and use them to write a > MIDI file. > > hYPerSonic > http://arrowtheory.com/software/hypersonic/index.html > hYPerSonic is for building and manipulating sound processing > pipelines. It is designed for real-time control. It includes objects > for oscillators, filters, file-io, soundcard and memory operations. > > pyTTS > http://www.sourceforge.net/projects/uncassist > pyTTS is a Python wrapper for the Microsoft Speech API (SAPI). The > library requires Mark Hammond's win32com extension and SAPI 5.1+. > > see also: > The Vaults of Parnassus: > http://www.vex.net/parnassus/apyllo.py/63131194 > Pypi: http://www.python.org/pypi?:action=browse&asdf=338 > -- > http://mail.python.org/mailman/listinfo/python-list > -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From finite.automaton at gmail.com Mon Oct 25 16:13:30 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 25 Oct 2004 13:13:30 -0700 Subject: Pythonic function composition References: <10nq3c4j3lst8e2@corp.supernews.com> Message-ID: <4b39d922.0410251213.546f70d6@posting.google.com> How about some recursion? def compose(f, *fns): if not fns: return f else: return lambda x: f(compose(*fns)(x)) ... >>> from math import * >>> foo = compose(sin, sqrt, abs) # sin(sqrt(abs(x))) >>> foo(-((pi/2.)**2)) 1.0 ...or you could try it this way, which makes some assumptions about function names, but will possibly run faster: def compose(*fns): fnames = [f.__name__ for f in fns] expr = "%s(x%s" % ('('.join(fnames),')'*len(fns)) return eval("lambda x: %s" % expr) From richie at entrian.com Tue Oct 12 05:37:10 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 12 Oct 2004 10:37:10 +0100 Subject: Parallelization on muli-CPU hardware? In-Reply-To: <416b9eed$0$11828$afc38c87@news.easynet.fr> References: <6db3f637.0410042045.2171ad5f@posting.google.com> <9fc58c06.0410111225.5e6a1662@posting.google.com> <1pDad.22529$5O5.5713@news-server.bigpond.net.au> <416b9eed$0$11828$afc38c87@news.easynet.fr> Message-ID: <169nm0ll2d5kek5j2p2kcl5f3iep6or4th@4ax.com> [Nicolas, arguing for a free-threading Python] > compare IO intensive (especially network IO) programs, the multi-threaded > program wins. The GIL is released during network IO. Multithreaded network-bound Python programs can take full advantage of multiple CPUs already. (You may already know this and I'm missing a point somewhere, but it's worth repeating for the benefit of those that don't know.) -- Richie Hindle richie at entrian.com From abra9823 at mail.usyd.edu.au Tue Oct 12 20:36:50 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed, 13 Oct 2004 10:36:50 +1000 Subject: tkinter dialog box Message-ID: <1097627810.416c78a2d2caf@www-mail.usyd.edu.au> hi! i need to write a dialog box that asks a user for a username when the application starts up and another dialog box that asks the makes the user choose a file and build a user model. the way i want the dialog box is that the user should be unable to proceed with the application until they complete the operation in the dialog box, something like a JavaScript prompt. any ideas of how to go about designing something like that. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From jeff at ccvcorp.com Tue Oct 19 20:48:39 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 19 Oct 2004 17:48:39 -0700 Subject: popen and two-way communication In-Reply-To: <3b091a1c.0410190355.5543b3e1@posting.google.com> References: <3b091a1c.0410190355.5543b3e1@posting.google.com> Message-ID: <10nbdakhv1indf2@corp.supernews.com> cmkl wrote: >You may be interested in the new subprocess module: > >1) PEP: > http://www.python.org/dev/doc/devel/whatsnew/node8.html > >2) source code: > http://www.lysator.liu.se/~astrand/popen5/ > >3) Windows builds (pre Python-2.4): > http://effbot.org/downloads/#subprocess > This looks nice, but I suspect that it won't help the O.P. Admittedly, I haven't tested subprocess. But interacting with SSH or gpg or most other password-requesting programs doesn't work properly through pipes. These programs read directly from the controlling TTY, rather than from stdin. Pipes don't affect the controlling TTY, meaning that you'll *still* be prompted for the password. In short, some version of (or replacement for) Expect is probably still needed. It is indeed too bad that pexpect won't work on Windows, or more accurately that the pty which pexpect relies on doesn't work on Windows... (Fortunately for me, I need to run ssh on Linux, so pexpect should serve my purposes just fine.) Jeff Shannon Technician/Programmer Credit International From Sonny.Baillargeon at bmonb.com Tue Oct 12 17:27:29 2004 From: Sonny.Baillargeon at bmonb.com (Baillargeon, Sonny) Date: Tue, 12 Oct 2004 17:27:29 -0400 Subject: Reading struct with structs Message-ID: <453D335C35136F4B8163C281D58BBD882DCA6B@NBNUNYCEXCH1.nesbittburns.ca> I am trying to read in a C struct file that contains sub-structs as part as the data definition. For example: int a /* 4 bytes */ int_t b /* custom struct */ blah_t c /* custom struct */ bing_t d /* custom struct */ The custom structs are arbitrary. The struct module only allows me to have strict C datatypes. How can I read in a struct recursively given I have to feed the struct.unpack? Thanks, Sonny **************************************************************************** This e-mail and any attachments may contain confidential and privileged information. If you are not the intended recipient, please notify the sender immediately by return e-mail, delete this e-mail and destroy any copies. Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal. Unless otherwise stated, opinions expressed in this e-mail are those of the author and are not endorsed by the author's employer. From db3l at fitlinxx.com Sat Oct 9 18:11:04 2004 From: db3l at fitlinxx.com (David Bolen) Date: 09 Oct 2004 18:11:04 -0400 Subject: Why can't I xor strings? References: <41683653$0$411$a1866201@newsreader.visi.com> Message-ID: Grant Edwards writes: > On 2004-10-09, Jeremy Bowers wrote: > > > >> Regardless of whether this is the best implementation for > >> detecting if two strings are similar, I don't see why xor for > >> strings shouldn't be supported. Am I missing something? > > > > The basic problem is that there is no obvious "xor on string" operation > > Sure there is. Strings have a boolean value, and the xor > operation on boolean values is well-defined. That's an operation, but I'm not sure that's the obvious one. For my part, if I saw "string1 ^ string2" I'd probably expect a byte by byte xor with the result being a new string. It doesn't feel natural to me to have my strings suddenly interpreted as a new data type based on the operation at hand. Logical operators work that way but not numerics (it would be in the same vein as string + number interpreting the string as a number - that way lies Perl :-)) -- David From noone at here.com Sun Oct 3 19:39:17 2004 From: noone at here.com (M. Clift) Date: Mon, 4 Oct 2004 00:39:17 +0100 Subject: append to items depending on prior item References: Message-ID: Hi Peter, Any chance you could point me in the direction of that Alex Martelli's post? Can't seem to find it anywhere. Thanks, Malcolm From http Sat Oct 2 16:38:39 2004 From: http (Paul Rubin) Date: 02 Oct 2004 13:38:39 -0700 Subject: Reclaiming (lots of) memory References: <87lleo6hva.fsf@thomas.local> <7xr7ogeu4t.fsf@ruckus.brouhaha.com> Message-ID: <7xekkgetyo.fsf@ruckus.brouhaha.com> Paul Rubin writes: > apple pie > apple computer > apple pie > apple sauce That of course should have said > apple computer > apple pie > apple pie > apple sauce since the file is sorted. From MornIHATESPAMThdr at NOSPAMverizon.net Wed Oct 13 02:43:32 2004 From: MornIHATESPAMThdr at NOSPAMverizon.net (Wes S.) Date: Wed, 13 Oct 2004 06:43:32 GMT Subject: Intercept and Tag STDOUT values References: <59e9fd3a04101222204b7f90f6@mail.gmail.com> Message-ID: Many thanks for the first reply of help. On this second part, I don't fully understand what you mean...I am, as I have previously stated, pretty new to Python and have not yet learned anything about file operations. -Wes "Andrew Durdin" wrote in message news:mailman.4809.1097645400.5135.python-list at python.org... > Further to my last reply: perhaps a better solution overall would be > to create a class (let's call it TaggedFile) that supports the > appropriate methods for file-like behaviour, and wraps any file > (keeping a reference to it in the "wrapped_file" attribute) with the > tagging you want. Then to do the actual redirection: > > tagged_stdout = TaggedFile(sys.stdout) > sys.stdout = tagged_stdout > # other code here > sys.stdout = tagged_stdout.wrapped_file > > It will then be much clearer that the redirection is occurring. From jedp at ilm.com Mon Oct 18 19:00:17 2004 From: jedp at ilm.com (Jed Parsons) Date: 18 Oct 2004 16:00:17 -0700 Subject: Building email threads from unix mailboxes In-Reply-To: References: <1098138259.303424.280500@z14g2000cwz.googlegroups.com> Message-ID: <1098140417.646769.5240@z14g2000cwz.googlegroups.com> Thanks. Is the References header a running list of all the In-Reply-To headers so far in the thread? From macrocosm at fastmail.fm Thu Oct 7 13:50:34 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 07 Oct 2004 13:50:34 -0400 Subject: Python Audio Module Message-ID: <416581EA.6000508@fastmail.fm> I'm looking for a Python module that will let me input wavs and spit out mp3s or oggs. Thanks. From bearophileHUGS at lycos.com Thu Oct 21 18:16:31 2004 From: bearophileHUGS at lycos.com (bearophile) Date: 21 Oct 2004 15:16:31 -0700 Subject: Some more notes Message-ID: <5c882bb5.0410211416.5a4a3c66@posting.google.com> Ville Vainio: >It's highly typical for the newbies to suggest improvements to the >language. They will usually learn that they are wrong, but the >discussion that ensues can be fruitfull anyway :-). Few more notes on the language. I don't know if I can really suggest improvements to the language... but I hope to learn something :-) I think some things are better in Delphi/Pascal (like the := for assignments instead of = and = for equality, that I suggested in the my precedent notes): 1) The "print" and "printf" pair without automatically added spaces between arguments, and with or without automatic newline, instead of the current "print" command. Because adding lots of "+str()+" isn't good for me (there's sys.stdout.write, but it's not built-in). 2) Adding "case var of:" can be useful. 3) "do while" (or "repeat until") can also be added, it's useful. 4) Maybe really raw strings RR"" can be added to avoid problems with file paths on Win :-] 5) Inside function definitions, assignments of mutable types like this can be forbidden and seen as errors by the interpreter: def func(a=[1,2]): ... 6) Given: a = [1] a += [2] a = a + [3] The first assignment extends the list, and second creates a new list and rebinds it. Why such difference for operations that look the same? Isn't a kind of "error" to do different things with quite similar looking commands? 7) There's something that I don't understand. I'm not a OOP purist, but finding functions like this beside normal methods seems odd to me: len(s) length of s min(s) smallest item of s max(s) largest item of s For uniformity they can be: s.len() s.min() s.max() etc. Thank you, bear hugs, Bearophile From mefjr75 at hotmail.com Sat Oct 9 18:47:20 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 9 Oct 2004 15:47:20 -0700 Subject: My file browsing script References: Message-ID: <18282ecb.0410091447.51921453@posting.google.com> "Dfenestr8" wrote in message > Earlier I posted asking for a file browsing script, for a GUI app I'd > written. Basically, I was after a graphical tool with which I could search > for files on my disk, and would return the path of a file through the > command line. > I got no reply, either because I didn't describe the problem correctly, or > because nobody could point me to such a script. So I wrote my own. Well I am no tk expert(never used it) , but tkFileDialog() might be what you want. 'http://www.google.com/search?hl=en&lr=&q=tkinter++file+selection+dialog&btnG=Search' > Please have a look at it, and give me som tips on how to improve it. In > particular, I designed it specifically for my linux system (Mandrake 10). > If I could make it x-platform that would be good. I did check out your script, and it looks nice and works quite well on win2k Py2.2. I think that means it **is** x-platform :) Nice work. HTH, M.E.Farmer From PeterAbel at gmx.net Wed Oct 13 13:22:09 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 13 Oct 2004 10:22:09 -0700 Subject: windows References: Message-ID: <21064255.0410130922.8b8009c@posting.google.com> Ajay wrote in message news:... > hi! > > i have two tkinter windows on top of each other. i would like it so that > the user has to complete the fields in the top windows before they can > interact with the window below it. that is, i dont want the user to close > the top window or minimize it or send it into the background. > > how would i do it? > > thanks > > cheers > > > > > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. There are documentations which say that Tkinter.Toplevel has a methode .transient(root) which should make the Toplevel window transient to its root window. But I never managed to make it work.(W2K Python 2.2.2). But here is a hackaround: import Tkinter #---------------------- def deiconify(widget): #---------------------- widget.deiconify() widget.grab_set() #---------------------- def withdraw(widget): #---------------------- widget.grab_release() widget.withdraw() # The root window root=Tkinter.Tk() # The Toplevel window tl=Tkinter.Toplevel(root,width=400,height=200,bg='white') # Withdraw Toplevel, when destroyed tl.protocol("WM_DELETE_WINDOW",lambda w=tl:withdraw(w)) # Make Toplevel not resizable tl.resizable(width=False,height=False) # Default state of Toplevel is withdrawn tl.withdraw() # Give Toplevel window a title tl.title('Toplevel-Window') # A Button on the root window to make Toplevel window visible Tkinter.Button(root,text='Toplevel on',command=lambda w=tl:deiconify(w)).pack() # Start mainloop root.mainloop() Regards Peter From no at spam.net Sun Oct 10 04:27:32 2004 From: no at spam.net (Fadly Tabrani) Date: Sun, 10 Oct 2004 16:27:32 +0800 Subject: Creating a window from PyHandle? Possible? Message-ID: Hi guys, This is the first time I'm posting to the newsgroup, hope you can help out. I'm writing a module to interface with the task scheduler in windows using PyWin32. Everything has been great so far but I'm stuck on displaying the propertys page of a task. Here's the code: import pythoncom import win32api from win32com.taskscheduler import taskscheduler import win32ui task_scheduler = pythoncom.CoCreateInstance\ (taskscheduler.CLSID_CTaskScheduler, None, pythoncom.CLSCTX_INPROC_SERVER, taskscheduler.IID_ITaskScheduler) def show_schedule_page(task_name): TASKPAGE_TASK = 0, TASKPAGE_SCHEDULE = 1, TASKPAGE_SETTINGS = 2 try: task = task_scheduler.Activate(task_name) except pythoncom.com_error, e: print 'Task name not found...' return # ** This returns a PyHandle handle = task.QueryInterface(taskscheduler.IID_IProvideTaskPage).\ GetPage(1, True) # ** Can't create a window with it using win32ui, returns error try: win32ui.CreateWindowFromHandle(handle) except win32ui.error, e: print e # ** Can't add it to a property sheet, return an error property_sheet = win32ui.CreatePropertySheet('Task Schedule') try: property_sheet.AddPage(handle) except (win32ui.error, TypeError), e: print e show_schedule_page('task1') Any ideas on how to do it? The task schduler api reference is at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/taskschd/taskschd/task_scheduler_start_page.asp I'm pretty new at this, is there anything that I've missed out? Cheers, Fadly Tabrani python loves me loves python From carribeiro at gmail.com Fri Oct 15 14:10:08 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 15 Oct 2004 15:10:08 -0300 Subject: [Web-SIG] WSGI async API In-Reply-To: <20041015180602.4730.1637681532.divmod.quotient.123@ohm> References: <864d3709041015105131652057@mail.gmail.com> <20041015180602.4730.1637681532.divmod.quotient.123@ohm> Message-ID: <864d370904101511107d3f3a05@mail.gmail.com> On Fri, 15 Oct 2004 18:06:02 GMT, exarkun at divmod.com wrote: > On Fri, 15 Oct 2004 14:51:54 -0300, Carlos Ribeiro wrote: > >On Fri, 15 Oct 2004 13:24:19 -0400, Peter Hunt wrote: > > > Essentially, Twisted.Web gives you something like this: > > > > > > class MyResource(resource.Resource): > > > def render(self, request): > > > return "content here" # you could also do request.write("content here") > > > > > > If you do an async call, you have to use request.write() to write the > > > data, return server.NOT_DONE_YET from the render() method, and call > > > request.finish() to finish the request. > > > > Just curious, so forgive me from jumping into the middle of the > > discussion. Isn't this one of the scenarios where output generators > > are most useful? Assuming that Twisted supported it, you could yield > > lines until there were nothing else to write. Did I get it right? > > > > Only if you can also signal to the code which is iterating the generator that it should stop iterating it for a while, otherwise user code might be called upon for bytes before they are available. > > If I have understand the conversation on the matter then this caveat is a main stumbling block for the async wsgi api. Now I think I get it. Generators have only two "states" of sort: either they can return more lines, or they stop. But the async API wants to have a three-state signaling protocol: ready to provide more lines, no more lines, and a "please, wait a second while I prepare more lines". That's it? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From zanesdad at bellsouth.net Wed Oct 13 07:33:26 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 13 Oct 2004 07:33:26 -0400 Subject: locks In-Reply-To: <1097665551.416d0c0f7bef5@www-mail.usyd.edu.au> References: <1097665551.416d0c0f7bef5@www-mail.usyd.edu.au> Message-ID: <416D1286.5020802@bellsouth.net> Ajay wrote: >hi! > >what would happen if i try to access a variable locked by another thread? i >am not trying to obtain a lock on it, just trying to access it. > >cheers > > > > > >---------------------------------------------------------------- >This message was sent using IMP, the Internet Messaging Program. > > I may be wrong, but I'm not sure you can lock a variable. Actually, you probably could do something like "locking a variable" with __getattr__(), __setattr(), and __delattr__() and sprinkling gently with locks. The locking mechanisms in the thread and threading libraries (allocate_lock() and Lock() respectively) lock sections of code. When you hit a section of code you want locked, you do a .acquire() and when you want to unlock an acquired lock, you do a .release(). If you have a variable in a section of code that you have locked, you can still see/smell/taste/touch/modify it from another thread if you can access it. So, if you've passed an object to multiple threads and one has acquired a lock to a specific section of code, another thread can't enter that section of code until the first releases the lock. But, if you have the same object in a different section of code, you can execute that unlocked code that contains/points-to the object. HTH, Jeremy Jones From bradtilley at gmail.com Thu Oct 7 17:13:16 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Thu, 07 Oct 2004 17:13:16 -0400 Subject: _winreg problem Message-ID: The below function fails with this error: ValueError: Could not convert the data to the specified type. The problem appears to be the v variable. When I make v an int, I get: WindowsError: [Error 5] Access is denied. This makes sense to me as the _winreg docs says that value (v) in SetvalueEx should be a string, but I do not understand why it gives the "ValueError" error when I make it a string. Also, I can do one key (Log) at a time, but not iterate over all of them like I'd like to do. I've checked it with print statements... every thing looks right. Any suggestions? def log_limits(): ## 18 ## For winXP SP2 & Python 2.3.4 ## set log limits on EventLogs, keep guests out of logs and set them to overwrite as needed. logs = ['Application', 'Security', 'System'] vals = {'Retention':'0', 'MaxSize':'10223616', 'RestrictGuestAccess':'1'} for l in logs: x = r"SYSTEM\CurrentControlSet\Services\Eventlog\%s" % l ## This print shows I'm iterating of the logs correctly. print x key = OpenKey(HKEY_LOCAL_MACHINE, x) for n,v in vals.iteritems(): ## This print shows I'm associating the value pairs with each Log print n,v ## Here is where the failure occurs... the v at the end: SetValueEx(key,n,0,REG_DWORD,v) CloseKey(key) From just at xs4all.nl Tue Oct 5 06:52:43 2004 From: just at xs4all.nl (Just) Date: Tue, 05 Oct 2004 12:52:43 +0200 Subject: XML and UnicodeError References: <5339b60d.0410050013.6bbc673d@posting.google.com> Message-ID: In article , Pinke Panke wrote: > > 2. Convert any other text to Unicode as soon as possible. > > Ok, i.e. > > headline = structure[0] # is unicode > pagetext = structure[1] # is unicode > fill = "bar".encode('utf-8') # lets make it unicode That's not making it unicode; you mean fill = unicode("bar", "utf-8") (Or "bar".decode("utf-8"), which does the same; I prefer using the unicode builtin.) > foo = headline + fill + pagetext # foo is unicode, too > > ? > > > 3. Manipulate only Unicode values - don't mix them up with > > plain strings. > > It makes sense, but I need some string concatenations. E.g. I set > default values in the python script and try to concatenate them with > XML values. > > But now, I would think the safest way is to transfer all plain strings > in the python script into a second XML file and use them, because > after reading in they would be in Unicode. Right? Yes, but there's no need to. Are you perhaps using string literals containing non-ascii chars, yet don't use the 'u' prefix? u"\xff" as opposed to "\xff". > Or saving the python script in utf-8 would make the difference? Depends... > > 4. Serialise to your chosen encoding only when preparing > > output. > > Every string concatenation in my script is preparing output. Do _all_ manipulations using unicode, and convert to utf-8 as late as poosible, ie. when you're passing the result to code that expects non-unicode data. That's basically what he was saying. Just From dev at null.oo Tue Oct 5 05:46:21 2004 From: dev at null.oo (Pinke Panke) Date: 5 Oct 2004 09:46:21 GMT Subject: XML and UnicodeError References: <5339b60d.0410050013.6bbc673d@posting.google.com> Message-ID: Hello Paul, thanky you for your answer. > The solution is to use Unicode throughout. I thought so, but it seemed to me not easy enough. > 1. Let minidom provide you with Unicode values. Yes, I assume this is the default behaviour of the minidom parser. > 2. Convert any other text to Unicode as soon as possible. Ok, i.e. headline = structure[0] # is unicode pagetext = structure[1] # is unicode fill = "bar".encode('utf-8') # lets make it unicode foo = headline + fill + pagetext # foo is unicode, too ? > 3. Manipulate only Unicode values - don't mix them up with > plain strings. It makes sense, but I need some string concatenations. E.g. I set default values in the python script and try to concatenate them with XML values. But now, I would think the safest way is to transfer all plain strings in the python script into a second XML file and use them, because after reading in they would be in Unicode. Right? Or saving the python script in utf-8 would make the difference? > 4. Serialise to your chosen encoding only when preparing > output. Every string concatenation in my script is preparing output. I am looking forward to your answer. Martin From duncan.booth at invalid.invalid Wed Oct 13 09:13:07 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Oct 2004 13:13:07 GMT Subject: strange side effect with lists!? References: <1glllnv.9f2gdijdroqgN%aleaxit@yahoo.com> <416d22ac.152182767@news.oz.net> Message-ID: Bengt Richter wrote: > I got curious: > > >>> L = range(5) > >>> L > [0, 1, 2, 3, 4] > > I'm impressed ;-) > I find it impressive that recursive data structures involving builtin types manage to avoid printing out infinite regressions of themselves. >>> class C: def __init__(self, val): self.val = val def __repr__(self): return "" % self.val >>> l = range(5) >>> l [0, 1, 2, 3, 4] >>> c = C(l) >>> c >>> l[2] = c >>> l [0, 1, , 3, 4] >>> c , 3, 4]> From peter at engcorp.com Wed Oct 27 15:48:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Oct 2004 15:48:07 -0400 Subject: Open Source License Question In-Reply-To: <97-dnSRAYPEwPuLcRVn-rA@rogers.com> References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <97-dnSRAYPEwPuLcRVn-rA@rogers.com> Message-ID: Dan Perl wrote: > Michael, I have one comment in-line (see below), but other than that I can > only say that I chose GPL for my own project. It may discourage use of my > code for commercial purposes but it might even be pretentious to expect that > something like that would ever happen. On the other hand, I was more > interested in the advantages of open-source and I wanted to enforce that as > much as possible. I did some research of my own at the time (recently, > actually) but I didn't go much into details and I didn't study other > licenses in detail either, but I chose GPL in large part because it is the > most widely used. This seems like an appropriate post to which to attach a reference to a nice article contrasting the GPL and the Mozilla Public License (MPL): http://croftsoft.com/library/tutorials/gplmpl/ Summary of that essay, in the words of its author: "I state in this essay that MPL is more free and open than GPL." -Peter From pynode at centrum.cz Fri Oct 29 05:02:42 2004 From: pynode at centrum.cz (MJR) Date: 29 Oct 2004 02:02:42 -0700 Subject: Real-time graphs References: <3cccb1d8.0410280723.50ff8679@posting.google.com> <41811f1f$0$33063$a1866201@newsreader.visi.com> Message-ID: <3cccb1d8.0410290102.7f001ada@posting.google.com> Grant Edwards wrote in message news:<41811f1f$0$33063$a1866201 at newsreader.visi.com>... > On 2004-10-28, MJR wrote: > > > just wondering what options I would have if I wanted to use Python to > > produce real-time graphs. > > What do you mean by "real-time"? > > If you want to display a "live" waveform at 50fps, then I'm not > aware of anything. Need to display data read from telemetry systme. Data might change in order of 1000/s. Not every sample will be displayed, but still need something close to 100sps From cmedcoff at hotmail.com Wed Oct 6 21:15:37 2004 From: cmedcoff at hotmail.com (cmedcoff at hotmail.com) Date: Wed, 6 Oct 2004 21:15:37 -0400 Subject: logging question Message-ID: I going through my first attempt at using the new logging facilities. I would like to have log output go to both a file and std error and perhaps email as well. Is there a handler that allows this sort of multiple outputs capture or will a custom handler have to be written? From mickel at csc.fi Mon Oct 11 08:20:48 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Mon, 11 Oct 2004 15:20:48 +0300 (EEST) Subject: Regular expression for matching IPA characters in Unicode? Message-ID: Hi Pythoneers, Which is the best way of checking that a given unicode string only contains IPA characters, e.g. characters in the range \u0250-\u02AF? I guess a regular expression would do it, just can't figure out how to implement that expression. Code snippets are most welcome. Best regards, Mickel Gr?nroos -- Mickel Gr?nroos, application specialist, linguistics, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, CSC is the Finnish IT center for science, www.csc.fi From deetsNOSPAM at web.de Fri Oct 15 07:36:51 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 15 Oct 2004 13:36:51 +0200 Subject: How to python raw socket ???? References: Message-ID: Leon wrote: > have any relate module ?? > or write example ?? > > .>_<. > > Please help me http://www.catb.org/~esr/faqs/smart-questions.html http://docs.python.org/lib/module-socket.html http://www.google.com/ -- Regards, Diez B. Roggisch From jdhunter at ace.bsd.uchicago.edu Tue Oct 19 16:35:19 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 19 Oct 2004 15:35:19 -0500 Subject: Free hosting for Python open-source projects In-Reply-To: <864d370904101914067b7a1728@mail.gmail.com> (Carlos Ribeiro's message of "Tue, 19 Oct 2004 18:06:36 -0300") References: <864d370904101914067b7a1728@mail.gmail.com> Message-ID: >>>>> "Carlos" == Carlos Ribeiro writes: Carlos> I'm sure this question has been posted before, but the Carlos> answer will probably be out of date, so here it goes. How about an October 11th posting on the same topic with 4 reponses Google is your friend 1) http://groups.google.com 2) hosting group:*python* -> "Google Search" 3) Sort by date The 5th or so link, "Where to host an open source project? Sourceforge? " discusses hosting, with subversion information, etc.... JDH From bokr at oz.net Tue Oct 19 00:06:35 2004 From: bokr at oz.net (Bengt Richter) Date: Tue, 19 Oct 2004 04:06:35 GMT Subject: [Python-Dev] ConfigParser shootout, preliminary entry References: <20041018104036.0A2B.JCARLSON@uci.edu> <2EE12B0A-212F-11D9-9236-000A95BA5446@redivi.com> <20041018120633.0A3D.JCARLSON@uci.edu> <41743f3a.161450203@news.oz.net> Message-ID: <4174814f.178367739@news.oz.net> On Mon, 18 Oct 2004 21:22:47 -0300, Carlos Ribeiro wrote: >On Mon, 18 Oct 2004 22:43:16 GMT, Bengt Richter wrote: >> Has anyone discussed using the csv module as the basic file interface for config data? > >I believe that CSV files are better suited for regular, table-like >information, not for the type of data that is normally stored on INI >files. Why? [segment] sym=something sam=other maps trivially to seg,segment dat,sym,something dat,sam,other etc. E.g., >>> import csv, sys >>> for line in csv.reader(sys.stdin): print line ... seg,segment dat,sym,something dat,sam,other # a comment segname ,sym,something ,sam,somthing # might be an alternative ^Z ['seg', 'segment'] ['dat', 'sym', 'something'] ['dat', 'sam', 'other'] ['# a comment'] [] ['segname'] ['', 'sym', 'something'] ['', 'sam', 'somthing'] ['# might be an alternative'] Very easy to deal with. If you wanted an object with two-level attribute for access like conf.segment.sym, it would be easy to build, e.g., (admittedly not very robust in this little demo hack ;-) >>> import csv, sys >>> conf = type('ConfData',(),{})() >>> for line in csv.reader(sys.stdin): ... if not line: continue ... if line[0]: ... seg = type('SegData',(),{})() ... setattr(conf, line[0], seg) ... continue ... setattr(seg, line[1], line[2:]) ... segment ,sym,sym value ,sam,sam value seg2 ,a_float,f,1.0 ,an_int,i,123 seg3 ,msg1,how about this? ,msg2,pretty trivial ,msg3, ;-) ^Z ^Z >>> vars(conf).keys() ['segment', 'seg3', 'seg2'] >>> vars(conf.segment).keys() ['sam', 'sym'] >>> vars(conf.seg2).keys() ['a_float', 'an_int'] >>> vars(conf.seg3).keys() ['msg1', 'msg3', 'msg2'] So we have the hierarchy: >>> conf.segment.sam ['sam value'] >>> conf.seg2.an_int ['i', '123'] >>> conf.seg3.msg3 [' ;-)'] Obviously one could have recognized ['i', '123'] and made conf.seg2.an_int == 123 instead of a list. This is very expandable. E.g., it's not hard to imagine what ['img','url=http://www.python.org/pics/pythonHi.gif'] might mean as to how to get and convert such a data spec. Regards, Bengt Richter From just at xs4all.nl Thu Oct 21 12:45:22 2004 From: just at xs4all.nl (Just) Date: Thu, 21 Oct 2004 18:45:22 +0200 Subject: htmldata and python 2.2 References: Message-ID: In article , "Tim Arnold" wrote: > I'm trying to get htmldata.py (written with Python 2.3 in mind) to work with > Python 2.2. Thanks much to Paul Clinch for showing me how to convert > for i, text in enumerate(L) > to > for i, text in zip(range(len(L)),L) > > I have one more glitch in getting htmldata.py to work in Python2.2: > Can someone show me how to recode this without the finditer? > > L = list(re.finditer(r'url\s*\(([^\r\n\("]*?)\)|' + > r'url\s*\(\s*"([^\r\n]*?)"\s*\)', doc)) > > The doc says re.finditer is available in 2.2, but I'm guessing it must be > in a minor version update (e.g., 2.2.3). Anyway, I'm getting this error in > the Traceback: > > L = list(re.finditer(r'url\s*\(([^\r\n\("]*?)\)|' + > AttributeError: 'module' object has no attribute 'finditer' Seems you're hitting http://python.org/sf/585882, a bug that was fixed in 2.2.2. You could use re.findall() instead. Just From moexu13 at gmail.com Sat Oct 23 14:39:47 2004 From: moexu13 at gmail.com (M. Bitner) Date: Sat, 23 Oct 2004 11:39:47 -0700 Subject: Slow debugging with Komodo In-Reply-To: References: <417a8d3e$0$1161$db0fefd9@news.zen.co.uk> Message-ID: <57c312d3041023113963ddf453@mail.gmail.com> Are you running the Symantec corporate AV client? I have trouble with both Python and PHP in Komodo and there's at least one other unconfirmed reporting of a software conflict with Symantec. http://bugs.activestate.com/show_bug.cgi?id=27433 On Sat, 23 Oct 2004 18:32:17 +0000 (UTC), Jarek Zgoda wrote: > Will McGugan pisze: > > > On my dev machine (P4 1.7Ghz Win2K) debugging with Komodo is painfuly > > slow. There is a delay of several seconds when stepping over a single > > line of code. Debugging the same code with Pythonwin is very quick. Does > > anyone else experience slow debugging, and is there anyway to speed it up? > > Didn't notice such weirdness, but Komodo is rather RAM-hungry so better > close as many other programs as you can, turn off all IDE features that > you don't need. Oh, and BTW, 512MB RAM is "reasonable minimum"... > > -- > Jarek Zgoda > http://jpa.berlios.de/ | http://www.zgodowie.org/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > From Scott.Daniels at Acm.Org Sat Oct 16 21:17:54 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 16 Oct 2004 18:17:54 -0700 Subject: Message from exception raised in generator disappears In-Reply-To: References: Message-ID: <4171cd3d$1@nntp0.pdx.net> Mike Brown wrote: > I thought I was being pretty clever with my first attempt at using generators, > but I seem to be missing some crucial concept, for even though this seems to > work as intended, the text of the exception message does not bubble up with > either of the ValueErrors when one of them is raised. > > > # This helps iterate over a unicode string. When python is built with > # 16-bit chars (as is the default on Windows), it returns surrogate > # pairs together (unlike 'for c in s'), and detects illegal surrogate > # pairs. Byte strings are unaffected. > def chars(s): > surrogate = None > for c in s: > cp = ord(c) > if surrogate is not None: > if cp > 56319 and cp < 57344: > pair = surrogate + c > surrogate = None > yield pair > else: > raise ValueError("Bad surrogate pair in %s" % s) > else: > if cp > 55295 and cp < 57344: > if cp < 56320: > surrogate = c > else: > raise ValueError("Bad surrogate pair in %s" %s) > else: > surrogate = None > yield c > if surrogate is not None: > raise ValueError("Bad surrogate pair at end of %s" % s) > > > # as expected, returns u'example \xe9...\u2022...\U00010000...\U0010fffd' > ''.join([c for c in chars(u'example \xe9...\u2022...\ud800\udc00...\U0010fffd')]) > > # now test the 3 exception conditions. Each produces a ValueError > ''.join([c for c in chars(u'2nd half bad: \ud800bogus')]) > ''.join([c for c in chars(u'no 1st half: \udc00')]) > ''.join([c for c in chars(u'no 2nd half: \ud800')]) > > > All 3 result of the exception tests result in a bare ValueError; there's no > "Bad surrogate pair in" message shown. Why is thta? What am I doing wrong? The problem is that type('abc%s' % u'\udc00') is unicode, not str. Change your raises to something like: raise ValueError("Bad surrogate pair at end of %r" % s) and the you can relax. -Scott David Daniels Scott.Daniels at Acm.Org From alan.gauld at btinternet.com Sat Oct 23 12:31:56 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Oct 2004 16:31:56 +0000 (UTC) Subject: Is there a "Large Scale Python Software Design" ? References: <7n78n09cv11bedrvsnjfb6aa0jk981s4dq@4ax.com> <1098195361.960550.257070@z14g2000cwz.googlegroups.com> <1098414642.736428.8940@f14g2000cwb.googlegroups.com> Message-ID: On 22 Oct 2004 19:03:02 -0400, aahz at pythoncraft.com (Aahz) wrote: > >solves all my problem" people I have seen haven't worked on anything > >"large" -- and my definition of large agrees with Alex's; over 100 > >kloc, more than a handful of developers. > > So you're saying that both attributes are necessary? I think they are because both people and code issues arise on 'large' projects (see the Mythoinal Man Month for examples of each type), although all things are relative. Our local definition of project size is: < 100Kloc = small 100K-1Mloc = Medium > 1Mloc = large We try to keep the large projects to less than 10 at any one time... Staffing sizes are 1-6 on small projects 4-30 on medium and typically 30-500 on large ones (I'd guess most large projects are actually around 2-3 MLoc and have about 60-100 developers (inc dedicated testers). Our most common project size is 200-300K with about 10-20 developers. (and the preferred methodology is DSDM) We probably have about 30-50 such projects running at any one time. On that scale I use Python for prototyping "components" on the medium-large stuff but it all gets built in C++ or Java. The small projects could be in Perl, VB/ASP, PL/SQL or Java. (Sadly Python is not an approved language for production - yet...I'm working on it :-) Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From rnd at onego.ru Fri Oct 22 01:25:49 2004 From: rnd at onego.ru (Roman Suzi) Date: Fri, 22 Oct 2004 09:25:49 +0400 (MSD) Subject: Python and generic programming In-Reply-To: <20041021121451.0AC2.JCARLSON@uci.edu> References: <20041021121451.0AC2.JCARLSON@uci.edu> Message-ID: Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - On Thu, 21 Oct 2004, Josiah Carlson wrote: > > > I wonder, does Python support generic programming paradigm, and to > > what extent (I guess, it doesn't do it in full)? And (or) does it move > > in that direction? Will we ever see > > > > concept WellAlright: > > ... > > > > constructs in Python? > > Isn't it right time to reserve "concept" as a keyword ;-) > > > Perhaps you meant something different, but C++ style generic (template) > programming is not necessary in Python. Most Python programs are already kinda generic, yes. But generic programming adds multi-sorted types control and constraints to ensure type safety... > With decorators, there is an easy method for generating per-argument > type checking and dispatch for functions and methods. > > As Python does runtime type checking, if you care to support different > types of arguments even without decorators, one is able. > > - Josiah > From richardblackwood at cloudthunder.com Tue Oct 5 11:07:51 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Tue, 05 Oct 2004 11:07:51 -0400 Subject: New to Python: Features In-Reply-To: <1gl6dmb.1jpp8u61a9ojk1N%aleaxit@yahoo.com> References: <416210AF.5060908@cloudthunder.com> <1gl6dmb.1jpp8u61a9ojk1N%aleaxit@yahoo.com> Message-ID: <4162B8C7.2090903@cloudthunder.com> Alex Martelli wrote: >Cameron Laird wrote: > ... > > >>>>31. Concepts of Protocols (whereby one may organize related methods into >>>> >>>> > ... > > >>>No. Test-driven development is the norm in Python. >>> >>> >> . >>... but see >>for one among several DbC initiatives. >> >> > >...and PEP 246 for Protocols (and more relevantly, pluggable >adaptation). Eby's PyProtocols implements these ideas (and more); my >talk given earlier this year at OSCON (on masquerading and adaptation >design patterns in Python) has a short section on PEP 246, you should >find the PDF at www.strakt.com. > > >Alex > > Oh great, Python has nearly everything, you just have to add on modules. Not bad, pretty cool actually. If use this PyProtocols will my program be slower than if protocols were built-into the language? From dgargan at sbcglobal.net Mon Oct 18 00:29:29 2004 From: dgargan at sbcglobal.net (digidalmation) Date: Mon, 18 Oct 2004 04:29:29 GMT Subject: mod_python apache configuration issues Message-ID: Hello all. I've been trying to get my linux server to run mod_python. It's a Mandrake 10 linux box, and apache/mod_python are installed from rpms. apache2-mod_python-2.0.48_3.1.3-1mdk apache2-2.0.48-6mdk The rpm installed the python module as: /usr/lib/apache2-extramodules/mod_python.so And added a config file for apache: /etc/httpd/conf.d/16_mod_python.conf The apache config files contained the following before my modifications: LoadModule python_module extramodules/mod_python.so Now after reading the docs installed into /usr/share/doc for mod_python and going through the directions at python.org, I've also changed the config file to add a few lines to one of the directives: Options -Indexes FollowSymLinks MultiViews AllowOverride All AddHandler mod_python .py PythonHandler mptest PythonDebug On Now when I put the url into a browser: http://myserver.mydomain.com/mptest.py I get a popup from the browser because it doesn't know how to handle mptest.py, and it asks what you want to do with the file (open it with an application, save it to disk, etc). I can choose to open the file with a text editor, and all it shows is the text "hello world". That's the output of the mptest.py script.... apache isn't feeding the browser the code from the mptest.py, only the output. (Otherwise when I open it in a text editor I'd see the entire mptest.py script. Contents of the mptest.py script: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK I'm not a python developer, but have been working with Linux and Apache for a number of years. I'm not sure where to go from here. It appears that the script gets compiled - there is a mptest.pyc file in the directory now. Why is it sending my browser the mptest.py file with the stdout of the script? Thanks in advance. Any help on this is appreciated. Dave From eric_brunel at despammed.com Tue Oct 19 08:18:49 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 19 Oct 2004 14:18:49 +0200 Subject: execvp() on Solaris In-Reply-To: References: Message-ID: <41750465$0$4029$8fcfb975@news.wanadoo.fr> mikeSpindler wrote: > I've seen it addressed in searching, but not specifically what is > recommended to get around it. On Linux where I did my development all > was fine. But then going to Solaris for the target I found I couldn't > resolve the errors wrt execvp(). It's apparently not syntax, but I > could be wrong. Any other thoughts on how to get execvp() working > and/or how to cat a file in a new window without bringing tkinter into > the discussion? > > My example: > os.system("xterm -geometry 120x20 -e \"tail -f ./logs/DATAFILE\"&") > > Thank you! > Mike Stupid question first: does the command work in a shell? Because AFAIK, there is no xterm installed by default under Solaris. The terminal is called dtterm and is located in /usr/dt/bin. I tried the exact same thing you're doing on Solaris 2.7 with Python 2.1 and got no error at all: Python 2.1.1 (#13, Dec 10 2003, 10:31:34) [GCC 3.2.2] on sunos5 Type "copyright", "credits" or "license" for more information. >>> import os >>> os.system('/usr/dt/bin/dtterm -geometry 120x20 -e ' 'tail -f /var/log/samba/log.smb &') 0 So I can only repeat what others already told you: please send the exact error messages you get, or we won't be able to help you much... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fumanchu at amor.org Mon Oct 11 11:34:55 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 11 Oct 2004 08:34:55 -0700 Subject: Help needed: try/except -idiom vs. C-style coding Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F5F@exchange.hqamor.amorhq.net> pekka niiranen wrote: > I have defined function that calls another functions like this > (modified for this mail): > > def main_function(): > if not function1(): > m = "main_function: function1 failed" > print_error(m) > return False > if not function2(): > m = "main_function: function2 failed" > print_error(m) > return False > if not function3(): > m = "main_function: function3 failed" > print_error(m) > return False > return True > > In book "Learning Python 1st edition" is was said > that this C-style programming is bad practice > and should be replaced with structure: > > def main_function(): > try: > function1(): > function2(): > function3(): > except: > what_ever() > return False (?) > else: > return True (?) > > How can I use try/except -style if I want to know WHICH > of functions 1-3 failed in try: -section and print > that information? What should functions return in order to > a) raise an exception and > b) tell main_function "it was me who failed for this reason" > This message should be user specific. If you care which function failed, you should narrow the exceptions: def main_function(a, b, c): try: function1(a) except IndexError: print "function1 failed" return False try: function2(b) except IOError: print "function2 failed" return False try: function3(c) except (TypeError, ValueError): print "function3 failed" return False return True It's also good practice to specify which errors you expect as above; bare "except:" has its place, but it's a rare one. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ed18hg at brllsouth.net Sun Oct 24 09:59:53 2004 From: ed18hg at brllsouth.net (ed18hg) Date: Sun, 24 Oct 2004 09:59:53 -0400 Subject: Is this group for newbies? References: Message-ID: <5yOed.193303$as2.58841@bignews3.bellsouth.net> Thanks. I'll go there. "andrea valle" wrote in message news:mailman.5387.1098623691.5135.python-list at python.org... Tutor list is exactly what you need. You can find the address on python.org --> mailing list Best -a- On 24 Oct 2004, at 15:02, ed18hg wrote: > I'm looking for a Python newbie group. I don't want to get flamed by > asking > in the wrong place. > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From listserver at tdw.net Wed Oct 20 12:53:44 2004 From: listserver at tdw.net (Tim Williams) Date: Wed, 20 Oct 2004 17:53:44 +0100 Subject: POP text/plain References: <00a301c4b696$5f325420$ccbefea9@twilliams> Message-ID: <016601c4b6c5$5c881050$ccbefea9@twilliams> ----- Original Message ----- From: "Tim Williams" > > "LutherRevisited" wrote in message > news:20041020010134.07554.00002191 at mb-m18.aol.com... > > Ok, what I do for most email messages is get the content that is type > > 'text/html', which is 99% of my messages, and with string functions I can > get a > > string from that which is only html code. But, for plain text messages, > the > > part which is text/plain doesn't really leave me with anything I can think > of > > to get a substring from that which is only the body of the message. I > always > > end up with header and all when I display a plaintext message. Any > thoughts? > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > Use the email module to split any email into its "parts", then work with > the parts individually [snip bad code] After further thoughts on this, and time to wake-up properly (its still untested, but better than the last example and should give you something to build on) import email as e import mimetypes from email.MIMEText import MIMEText msg = e.message_from_string(whole_msg) new_payload = [] if not msg.get_content_type() == 'text/plain': for part in msg.walk(): if part.get_content_maintype() == 'multipart': continue if part.get_content_type() == 'text/plain': new_payload.append(part) # keep this part if not new_payload: new_payload = [MIMEText('\t\tText-only filter was applied\r\n')] msg.epilogue = '' msg.set_payload(new_payload) print msg From kartick_vaddadi at yahoo.com Mon Oct 25 23:12:07 2004 From: kartick_vaddadi at yahoo.com (kartik) Date: 25 Oct 2004 20:12:07 -0700 Subject: python file versioning References: <940ee3e8.0410250506.1d679430@posting.google.com> Message-ID: <940ee3e8.0410251912.3baaaaf3@posting.google.com> "Diez B. Roggisch" wrote in message news:... > file mod_22: > from __future__ import nifty_feature > import bar > > file mod_23: > import bar > > > app.py: > > import sys > > if sys.version_info[:2] == (2,2): > import mod_22 as mod > else: > import mod_23 as mod > > > So I think I showed the OP a way to deal with version-dependencies. that's a quite a bit of work. i'm talking about automating this From joshway_without_spam at myway.com Mon Oct 18 12:30:57 2004 From: joshway_without_spam at myway.com (JCM) Date: Mon, 18 Oct 2004 16:30:57 +0000 (UTC) Subject: By value or by reference? References: Message-ID: Jorge Godoy wrote: > "Riccardo Rossi" writes: >> Hi all! >> >> How does Python pass arguments to a function? By value or by reference? > IIRC, by reference. It uses a copy on write algorithm. Copy-on-write is an optimization. It doesn't affect the semantics of the laguage. From . Fri Oct 8 14:11:50 2004 From: . (pythonnewbie) Date: Fri, 8 Oct 2004 19:11:50 +0100 Subject: Python Newbie. Python on PPC, please assist. Message-ID: <2qudnV1KKuD7RfvcRVnyhg@pipex.net> Hi All. I'm just starting to learn programming using Python. I am new to programming so please be patient with me! I found this for Pocket PC: http://www.murkworks.com/Research/Python/PocketPCPython/PPCPythonR2Notes I tried installing it and for some reason it would not work. Having installed it, clicking on the program gives the error "PocketPCPython.exe or one of it's components cannot be found", even though I am directly clicking on the exe, and even after much fiddling making sure all the files are there. I'm not a newbie as far as pda's go, so I'm a little confused as to why it's not working. What I really want to know though, is what it actually, does before I go about spending time getting it working. I mean, is it a development environment, like IDLE, or does it just install the Python libraries so you can run Python programs on a PPC, or what? As I said, I am a complete programming newbie so sorry if I'm talking rubbish. I'd be really greatful if someone could tell me what the Python PPC program is/does. Also if there are any other (better) programs for Python on PPC. And if anyone has any ideas why the install didn't work on the PPC, I'd be greatful for advice on that too. Many thanks in advance. From waldbie at verizon.net Mon Oct 18 19:52:55 2004 From: waldbie at verizon.net (Carl Waldbieser) Date: Mon, 18 Oct 2004 19:52:55 -0400 Subject: How to disable urllib2 HTTP proxy on Windows? Message-ID: <4174577a@post.usenet.com> **** Post for FREE via your newsreader at post.usenet.com **** When using urllib2.urlopen() on my Windows 2000 machine at work, I was puzzled that I kept getting back authentication errors from our Internet proxy server (I was trying to contact an internal machine). Upon digging into the code a little, I found that urllib2 was pulling the proxy information out of the Windows registry (Internet Explorer uses these settings). However, the browser also had settings to disable use of the proxy for local addresses, and any specific addresses or wildcards I gave it. urllib2 seemed to be ignoring those. In the Python library reference, I read that setting the HTTP_PROXY environment variable could set a proxy, as could installing a new opener. However, I tried to turn off proxy support by setting HTTP_PROXY="", and I got an error for my trouble (don't recall exact error right now-- am at home on my GNU/Linux system). Is it possible to turn off proxy support in Python while leaving the browser settings untouched? I was really quite surprised when I found out that Python was using the browser's proxy settings on my behalf. Thanks, Carl Waldbieser -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From anna at aleax.it Fri Oct 1 11:41:40 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Fri, 01 Oct 2004 15:41:40 GMT Subject: __author__ In-Reply-To: <6e04113a.0410010627.559842f6@posting.google.com> References: <6e04113a.0410010627.559842f6@posting.google.com> Message-ID: David Keeney wrote: > I see this set (or similar) of variables in various modules I read. > They are found near the top of each module file, outside of any class > or function definitions. > > " > __author__ = "Software Authors Name" > __copyright__ = "Copyright (C) 2004 Author Name" > __license__ = "Public Domain" > __version__ = "1.0" > " > > What is the function of this set of variables? I assume there are > software products that use these, (Python itself, perhaps), that > expect to find certain variables explained. > > What are the expected variables, other than the ones listed above, and > what software would I expect to use them? > > David You may be seeing those in modules that were packaged up with distutils. The setup.py expects certain metadata about the distribution,including those you've listed above. A list of the expected values is available on page 562 of _Python in a Nutshell_, or in _Distributing Python Modules_ section 3, accessible at thttp://docs.python.org/dist/dist.html HTH, Anna From da_mueller at gmx.net Thu Oct 21 09:59:19 2004 From: da_mueller at gmx.net (Daniel Mueller) Date: Thu, 21 Oct 2004 15:59:19 +0200 Subject: File Polling (Rereading) In-Reply-To: <2tpq8vF20rf1rU1@uni-berlin.de> References: <2tpq8vF20rf1rU1@uni-berlin.de> Message-ID: Oliver Fromme wrote: > The portable way is to stat the file (see os.stat) every > 10 seconds, look at the mtime (modification time), and > if it did change, then open/read/close. hmm i'll have to rephrase my question... i KNOW that the file changes every 10 seconds... easiest would be i just give you the source code ;) the program is a nice little windows which displays ACPI information about battery status and stuff like that. the program is working just fine. but i want the performance tweak it... here is the link to the source code: http://sourceforge.net/project/showfiles.php?group_id=108369&package_id=117073 help would be greatly appreciated! > If you're lucky enough to work on a FreeBSD UNIX system > (and don't need a portable solution) Linux Platform... and no i dont need a portable solution -- Please use my GnuPG (PGP) Public-Key for secure message exchange. (http://157.161.155.222/damueller-pubkey.txt) From jfdutcher1958 at yahoo.com Tue Oct 19 14:35:39 2004 From: jfdutcher1958 at yahoo.com (jfdutcher1958) Date: Tue, 19 Oct 2004 18:35:39 -0000 Subject: Invalid port number in request for secure site web page Message-ID: Python returns this message: InvalidURL: nonnumeric port: '//www.a2webhosting.com:2083/frontend/x2' in reponse to the call below ....but the port number looks numeric ??? *************************************************************** import sys, httplib showlines = 56 try: servername, filename = sys.argv[1:] # cmdline args? except: servername, filename = 'https://www.a2webhosting.com:2083/frontend/x2', '/index.html' print servername, filename From lutherrevisited at aol.com Mon Oct 18 15:12:27 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 18 Oct 2004 19:12:27 GMT Subject: Yahoo SMTP References: <2tgn1sF1vnm4fU1@uni-berlin.de> Message-ID: <20041018151227.11669.00002008@mb-m15.aol.com> Thanks for the reply, recently I have tightened up my code to now reach the point where my ISP can reject me on port 25...LOL I am curioius about AUTH, I have no idea how this is done and have seen no mention of it in the module index under smtplib. If anyone could point me to where I should look for info on that I'd be grateful. From bokr at oz.net Tue Oct 19 16:03:39 2004 From: bokr at oz.net (Bengt Richter) Date: Tue, 19 Oct 2004 20:03:39 GMT Subject: By value or by reference? References: <1sRcd.157683$35.7727090@news4.tin.it> <1098114929.397931.92290@f14g2000cwb.googlegroups.com> <1glvhih.mackqd12vhs62N%aleaxit@yahoo.com> <20041018133211.0A4B.JCARLSON@uci.edu> <8C8685E8-2199-11D9-8317-000A95EFAE9E@yahoo.com> <1glx9lf.1yxrkv519qs7tkN%aleaxit@yahoo.com> Message-ID: <41757057.239559708@news.oz.net> On Tue, 19 Oct 2004 21:15:21 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Josiah Carlson wrote: > >> > > I agree with most everything you have said, though consider the pointer >> > > vs. value of C to define the semantics of the passing. That is, if you >> > > get a pointer in C, it is by reference. If you don't get a pointer, it >> > > is by value. >> > >> > I disagree: you get the value of the pointer. If you assign to the >> > barename of the pointer, this has no effect on the caller. >> >> [snip the remainder of the email] >> >> Sounds good. Now with the semantic arguments out of the way, is there a >> link where the equivalent of what was just said is available in the >> documentation? >> >> If yes, great. If not, perhaps what has been discussed should be >> slimmed down and inserted into the FAQ so that future generations don't >> need to rehash this conversation. > >Sure, but it's a vain hope -- 2 out of 3 questions asked here ARE about >stuff well covered in the FAQ, anyway. > I keep thinking there should be a tech fix for part of this problem. E.g., if interactive python help supported help(faqtopic='whatever') and that automatically used urllib to search the latest faq (caching stuff perhaps) and produced a topic-oriented HTML page with links to likely faq items, and started a browser to display it ... Hm, sounds like google with a site restriction. Maybe faq should live on faq.python.org and help(faqtopic='...') could leverage that? Anyway, the other part is feeding good stuff like your posted explanations into the faq. I keep thinking a little posting markup of some sort could make automated harvesting of c.l.py archives for faq snippets possible. Regards, Bengt Richter From aahz at pythoncraft.com Thu Oct 14 14:46:37 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Oct 2004 14:46:37 -0400 Subject: Quixote vs mod_python References: Message-ID: In article , flab ba wrote: > >Can somebody sway me one way or the other ? What would Quixote give me >that mod_python + Cheetah doesn't? Quixote is "inside-out" compared to most templating approaches: you write Python code that emits strings to create web pages. Cheetah is no different from PHP in that you start by writing a web page as your framework and then add code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From jcarlson at uci.edu Tue Oct 5 00:14:20 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 04 Oct 2004 21:14:20 -0700 Subject: New to Python: Features In-Reply-To: <20041004203353.ECBC.JCARLSON@uci.edu> References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> Message-ID: <20041004211329.ECBF.JCARLSON@uci.edu> I should have waited with my reply. If I could take the message back, I would. - Josiah From carribeiro at gmail.com Fri Oct 22 10:15:22 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 22 Oct 2004 11:15:22 -0300 Subject: Example of how to use logging for both screen and file In-Reply-To: References: Message-ID: <864d37090410220715423af1d7@mail.gmail.com> On 22 Oct 2004 15:26:18 +0300, Ville Vainio wrote: > Just posting this for the sake of google: > > Like everyone else, I figured it's time to start using the 'logging' > module. > > I typically want to dump "info" level (and up) log information to > screen, and "debug" level (and up) to a log file for in-depth > analysis. This is for scripts, so date/time/severity information is > not wanted. I assumed such a simple use case would have an example in > the docs (py 2.4), but no luck. > > Here's what worked for me: > > import logging > > def setupLogging(): > global log > log = logging.getLogger("myapp") > log.setLevel(logging.DEBUG) > sth = logging.StreamHandler() > sth.setLevel(logging.INFO) > log.addHandler(sth) > fhnd = logging.FileHandler('/tmp/myapp.log') > fhnd.setLevel(logging.DEBUG) > log.addHandler(fhnd) > > setupLogging() > > log.info("foo") # appears on screen and file > log.debug("bar") # appears in the file only > > The example might not be ideal, but something like this should really > be in the module documentation. The example config file mostly serves > to intimidate would-be users ("I need to do *that*?!?), and many of > them probably wouldn't want to introduce a third-party wrapper module > either (I think that should be the point of the standard logging > module after all). I'm also beginning to get to grips with the logging module. My first attempt was confusing, and I ended up removing it from the code. Now I just have a simple log method that still calls print . Not exactly what I wanted to do :-P My idea now is to write a clean and simple wrapper for the logging module, using sensible defaults, and exposing simple methods. Something like (still pseudo-code): from simplelog import Logger log = Logger() ... log.info() log.debug() log.warning() log.error(, exception=) It's a simple implementation that hides a lot of the options of the standard logging module. Messages would be automatically written to the most appropriate output channels, using sensible defaults. That is more than enough for most of my logging needs. It's still in the drawing board, though. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From clifford.wells at comcast.net Thu Oct 21 20:59:41 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Thu, 21 Oct 2004 17:59:41 -0700 Subject: Some more notes In-Reply-To: <5c882bb5.0410211416.5a4a3c66@posting.google.com> References: <5c882bb5.0410211416.5a4a3c66@posting.google.com> Message-ID: <1098406782.6627.78.camel@devilbox.devilnet.internal> On Thu, 2004-10-21 at 15:16 -0700, bearophile wrote: > I think some things are better in Delphi/Pascal (like the := for > assignments instead of = and = for equality, that I suggested in the > my precedent notes): Actually, since the assignment operator is used far more often than the equality operator, making it require three keystroke rather than just one is a bad idea. > 1) The "print" and "printf" pair without automatically added spaces > between arguments, and with or without automatic newline, instead of > the current "print" command. Because adding lots of "+str()+" isn't > good for me (there's sys.stdout.write, but it's not built-in). Use string interpolation. However, I agree having print as a statement rather than a function is a (very small) wart. Luckily it's easily circumvented (and I've heard rumor that this is, in fact, slated to be changed in Python 3000). > 2) Adding "case var of:" can be useful. Not familiar with this construct. If you mean "switch/case" as in C (or some variation of same), then I absolutely agree. > 3) "do while" (or "repeat until") can also be added, it's useful. Occasionally useful. Not enough to put it high on my list of things I'd like to see in Python, but I can see its utility for making *slightly* more logical code (versus the "while True: if x: break" idiom). > 4) Maybe really raw strings RR"" can be added to avoid problems with > file paths on Win :-] Not sure what problems you are referring to since I rarely use that platform and the times I have used it I haven't had any issues. Do you mean issues with "\"? Why not just use "/"? > 5) Inside function definitions, assignments of mutable types like this > can be forbidden and seen as errors by the interpreter: > def func(a=[1,2]): I don't see why valid Python syntax should be an error. Admittedly this quite often bites new users of Python, but there are plenty of things to confuse newbies, so I don't know why this particular construct should be singled out, especially when there is a perfectly valid explanation of the resulting behavior. > 6) Given: > a = [1] > a += [2] > a = a + [3] > The first assignment extends the list, and second creates a new list > and rebinds it. Why such difference for operations that look the same? > Isn't a kind of "error" to do different things with quite similar > looking commands? I'd agree this can be confusing. However, like the mutable arguments you mention previously, there is a logical explanation that suffices in place of breaking tons of Python code. > 7) There's something that I don't understand. I'm not a OOP purist, > but finding functions like this beside normal methods seems odd to me: > len(s) length of s > min(s) smallest item of s > max(s) largest item of s > For uniformity they can be: > s.len() > s.min() > s.max() > etc. I don't have a good answer for this. At least some of this is probably pure history (len() worked on both strings and lists, and strings didn't used to support methods, so I'm guessing it was a consistency issue back then and it's a compatibility issue now, why it wasn't added as a method is a good question). As far as min() and max() . Perhaps to avoid a plethora of methods on such commonly used constructs? At what point do you stop adding new methods to classes? Perhaps the decision was as simple as that. > Thank you, > bear hugs, > Bearophile That disturbs me every time I see it. Regards, Cliff -- Cliff Wells From jbellis at gmail.com Thu Oct 21 22:47:32 2004 From: jbellis at gmail.com (Jonathan Ellis) Date: 21 Oct 2004 19:47:32 -0700 Subject: Is there a "Large Scale Python Software Design" ? In-Reply-To: References: <7n78n09cv11bedrvsnjfb6aa0jk981s4dq@4ax.com> <1098143368.985682.72000@z14g2000cwz.googlegroups.com> <1098195361.960550.257070@z14g2000cwz.googlegroups.com> Message-ID: <1098413252.045374.294760@f14g2000cwb.googlegroups.com> Stephen Waterbury wrote: > Jonathan Ellis wrote: > > > ... A more-experienced co-worker pointed me in the right > > direction, and the IDE did the rest. ("Find definition," "Find > > references.") Grep can do much the same thing, but painfully slowly -- > > and inaccurately, when you have a bunch of interfaces implementing the > > same method names. ... > > Try "glimpse" (http://webglimpse.net) -- it uses a superset of > grep's arguments and can search large collections of files at > a single bound! Re-indexing takes a few seconds, but doesn't > need to be done unless there are major changes. glimpse addresses grep's speed problem, but unfortunately has no more semantic understanding beyond "it's just text." Etags is a little better but not much, and also suffers from the have-to-remember-to-reindex-if-you-want-accurate-results "feature." -Jonathan From steven.bethard at gmail.com Tue Oct 12 16:15:57 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Oct 2004 20:15:57 +0000 (UTC) Subject: Using os.system() and string concatenation References: <7a2229ee041012114353157c1d@mail.gmail.com> <7a2229ee04101212215fadcb18@mail.gmail.com> Message-ID: Wayne Witzel III gmail.com> writes: > No, I was properly inserting the spaces. When I changed it to a print > statement and executed the resulting output, it worked just fine. Not sure if I understand exactly what you said here, but just to be clear, the print statement inserts spaces: >>> x, y, z = 'x', 'y', 'z' >>> print x, y, z x y z >>> x + y + z 'xyz' >>> print x + y + z xyz >>> import sys >>> sys.stdout.write(x + y + z) xyz So if you're saying the output of a print statement works, but the string concatenation doesn't then yes, it does sound like you're not inserting spaces. Could you put print cmd + list1[0] + list1[1] + list2[0] + list3[0] at the end of your script and tell us what it outputs? Steve From adalke at mindspring.com Wed Oct 27 02:45:16 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 27 Oct 2004 06:45:16 GMT Subject: int/long unification hides bugs In-Reply-To: <417ef4b9.863273391@news.oz.net> References: <940ee3e8.0410250456.65445bbd@posting.google.com> <940ee3e8.0410252005.25a94170@posting.google.com> <417ef4b9.863273391@news.oz.net> Message-ID: <0uHfd.3722$kM.2804@newsread3.news.pas.earthlink.net> Bengt Richter wrote: > If you are willing to make your variables exist in an object's attribute > name space, you can define almost any behavior you want. Or, here's another solution -- make a number-like object which handles range checking for every operation. The big problem here is that unlike Ada, C++, or other languages that let you declare variable types, I have to figure out how to merge the allowed ranges of the two values during a binary op. I decided to use the intersection. Unlike Pythons ranges, I choose low <= val <= high (as compared to low <= val < high). import sys class RangedNumber: def __init__(self, val, low = -sys.maxint-1, high = sys.maxint): if not (low <= high): raise ValueError("low(= %r) > high(= %r)" % (low, high)) if not (low <= val <= high): raise ValueError("value %r not in range %r to %r" % (val, low, high)) self.val = val self.low = low self.high = high def __str__(self): return str(self.val) def __repr__(self): return "RangedNumber(%r, %r, %r)" % (self.val, self.low, self.high) def __int__(self): return self.val def __float__(self): return self.val def _get_range(self, other): if isinstance(other, RangedNumber): low = max(self.low, other.low) high = min(self.high, other.high) other_val = other.val else: low = self.low high = self.high other_val = other return other_val, low, high def __add__(self, other): other_val, low, high = self._get_range(other) x = self.val + other_val return RangedNumber(x, low, high) def __radd__(self, other): other_val, low, high = self._get_range(other) x = other_val + self.val return RangedNumber(x, low, high) def __sub__(self, other): other_val, low, high = self._get_range(other) x = self.val - other_val return RangedNumber(x, low, high) def __rsub__(self, other): other_val, low, high = self._get_range(other) x = other_val - self.val return RangedNumber(x, low, high) def __abs__(self): return RangedNumber(abs(self.val), self.low, self.high) def __mul__(self, other): other_val, low, high = self._get_range(other) x = self.val * other_val return RangedNumber(x, low, high) def __rmul__(self, other): other_val, low, high = self._get_range(other) x = other_val * self.val return RangedNumber(x, low, high) # ... and many, many more ... Here's some code using it >>> a = RangedNumber(10, 0, 100) >>> >>> a RangedNumber(10, 0, 100) >>> print a 10 >>> a+90 RangedNumber(100, 0, 100) >>> a+91 Traceback (most recent call last): File "", line 1, in ? File "spam.py", line 39, in __add__ return RangedNumber(x, low, high) File "spam.py", line 8, in __init__ raise ValueError("value %r not in range %r to %r" % ValueError: value 101 not in range 0 to 100 >>> a*5 RangedNumber(50, 0, 100) >>> 10*a RangedNumber(100, 0, 100) >>> 11*a Traceback (most recent call last): File "", line 1, in ? File "spam.py", line 67, in __rmul__ return RangedNumber(x, low, high) File "spam.py", line 8, in __init__ raise ValueError("value %r not in range %r to %r" % ValueError: value 110 not in range 0 to 100 >>> 0-a Traceback (most recent call last): File "", line 1, in ? File "spam.py", line 54, in __rsub__ return RangedNumber(x, low, high) File "spam.py", line 8, in __init__ raise ValueError("value %r not in range %r to %r" % ValueError: value -10 not in range 0 to 100 >>> a-0 RangedNumber(10, 0, 100) >>> b = RangedNumber(18, 5, 20) >>> b = RangedNumber(18, 5, 30) >>> a+b RangedNumber(28, 5, 30) >>> Andrew dalke at dalkescientific.com From bdp003 at hotmail.com Fri Oct 29 08:20:04 2004 From: bdp003 at hotmail.com (Bengt dePaulis) Date: Fri, 29 Oct 2004 12:20:04 GMT Subject: saving local dir Message-ID: I just started on python. I have c:\python23\examples\py and want to include that in my sys.path How to do it permanently? /Bengt Helsinki From rtilley at vt.edu Sun Oct 17 10:23:09 2004 From: rtilley at vt.edu (Brad Tilley) Date: Sun, 17 Oct 2004 10:23:09 -0400 Subject: See when process exits in Windows XP In-Reply-To: <2tevsnF1v2svmU1@uni-berlin.de> References: <2tevsnF1v2svmU1@uni-berlin.de> Message-ID: <4172804D.20904@vt.edu> Tobias Pfeiffer wrote: > Hi! > > On 17 Okt 2004, Brad Tilley wrote: > > >>def wait_for_ntbackup_to_exit(procname): >> while True: >> try: >> pids = \ >> win32pdhutil.FindPerformanceAttributesByName(procname) >> if len(pids) > 0: >> ## If ntbackup is running, loop until it closes. >> print pids >> print len(pids) >> print "ntbackup is running... waiting for it to >> exit." continue >> else: >> ## ntbackup is not running. >> break >> except: >> return > > > I have no clue about that win32pdhutil thingy but if it returns a list > with pids, then why do you need the except statement? From trial and error, I found that if this function runs when ntbackup isn't running that it would produce an error... that's the reason for the except. I can reproduce it if you want the exact error message. And it seems to me > that this loops as fast as the CPU is able to, so it actually steals away > other processe's CPU time. If you insert a time.sleep(0.5) statement (or > something similar), you can decrease the CPU usage to a minimum. You're right, I did this and it helps. From macrocosm at fastmail.fm Mon Oct 4 14:04:46 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Mon, 04 Oct 2004 14:04:46 -0400 Subject: Python Macros In-Reply-To: <41618797$0$69737$ed2619ec@ptn-nntp-reader01.plus.net> References: <41618797$0$69737$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <416190BE.6080802@fastmail.fm> Michael Sparks wrote: >Arich Chanachai wrote: > > > >>How hard/easy is it to extend the Python syntax? >> >> > >It's not that hard to do, but involves changing the compiler and if done >properly a whole slew of other things. If you want non-functional syntax >changes it's fairly trivial - just change the Grammar file and rebuild. >If you want a checklist of things you might want to look at when changing >the syntax you could look at this patch : http://www.python.org/sf/1013835 > > > Are there tutorials on this? >It's worth noting that this would probably result in a local overhead for >yourself in maintaining a private branch of python however - since this >changes your python in a fairly fundamental manner. I don't know what your >use case is though - if it's experimentation then I suspect that you'd be >happy with that :) > > > :Local overhead??? Private branch??? How come? I'm extending the language not adding another Python interpreter. >>Perhaps there are macro facilities for this? >> >> > >Not that I'm aware of. (At least not as far as I know in the lisp or C >meanings of the term) > > > I was thinking Scheme. >>I'd like to add messages and message passing, for example. >> >> > >Why do you feel you need to extend the language for this? Why not (for >example) overload <<, >> and similar operators? __lshift__, __rshift__ etc. >I'd really recommend not extending the language unless you really don't have >any option - unless that's what you're specifically interested in :) > > > > Not sure I understand you here. I want to implement messages like in ObjC where if you send a msg to an object and that object does know what to do with it, it can send the obj automatically to another object which might know what to do with it. Anyhow, there are other reasons as well. From carribeiro at gmail.com Tue Oct 5 18:26:04 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 5 Oct 2004 19:26:04 -0300 Subject: metaclass and customization with parameters In-Reply-To: <20041005215749.GA5891@burma.localdomain> References: <3b59a80.0410021910.17b31c29@posting.google.com> <864d3709041003152471cf26fc@mail.gmail.com> <20041005215749.GA5891@burma.localdomain> Message-ID: <864d3709041005152610162497@mail.gmail.com> On Tue, 5 Oct 2004 18:57:49 -0300, Gustavo Niemeyer wrote: > > 2) the signature of "def newmethod(self,i=i)" shows another > > interesting side effect. The value if (defined in the for loop) is > > passed as a keyword paramenter, and is evaluated whenever the 'def' > > statement is found. Because it changes, the def is re-run at every > > loop. In the lack of this hack, the def would run only at the first > > time, and all methods would in fact be the same. > > That's not true. The def statement is rerun every loop, no matter > what parameters are used. One can check that by issuing: > > print MyClass.method0.im_func > print MyClass.method1.im_func :-P You *right*. For some reason I was under the impression that the code was not re-executed everytime -- a kind of optimization, indeed, if the code does not have any external dependency. But you're right. Anyway, this is a horrible hack :-) I just wrote it to point out that classes are much more dynamic in their workings than most people realize, *specially* if you come from a C++/Java/Delphi background. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From jcarlson at uci.edu Wed Oct 13 03:47:42 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 13 Oct 2004 00:47:42 -0700 Subject: Secure Python code - volunteers for code review? In-Reply-To: <1097645158.10090.3.camel@devilbox.devilnet.internal> References: <20041012205021.091B.JCARLSON@uci.edu> <1097645158.10090.3.camel@devilbox.devilnet.internal> Message-ID: <20041013004207.0921.JCARLSON@uci.edu> > > You can save yourself many concerns by encoding your data in some > > fashion that cannot be understood by the database to mean anything. Hex > > works well for that. > > A more straightforward way is to simply use prepare() religiously. This > also avoids the headache of having to decode your data if you use a > different program to access it (such as psql or mysql). Thankfully, other languages are able to translate to/from hex *wink*. Either way, unencoded/unprepared data may bork you. - Josiah From paul at subsignal.org Sat Oct 9 11:24:03 2004 From: paul at subsignal.org (paul koelle) Date: Sat, 09 Oct 2004 17:24:03 +0200 Subject: still not happy with unittest.failUnlessRaises Message-ID: <2sqe4iF1o3pstU1@uni-berlin.de> hi folks, while I got my own errors kind of sorted out now (I think), unittest still not behaves like it should. code: print 'this is expected to fail. The "Type" column is unique in the DB' self.failUnlessRaises(IntegrityError, self.failhelper(certs.Subcacert, self.ca_client_tmpl)) traceback: File "/usr/lib/python2.2/site-packages/SQLObject/DBConnection.py", line 767, in _queryInsertID c.execute(q) File "/usr/lib/python2.2/site-packages/sqlite/main.py", line 243, in execute self.rs = self.con.db.execute(SQL) IntegrityError: column type is not unique ---------------------------------------------------------------------- Ran 1 test in 56.245s FAILED (errors=1) the docu (2.2) says: failUnlessRaises( exception, callable, ...) ...The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. and: issubclass(sqlite.IntegrityError, Exception) True IMO the test should pass. Any ideas what could be wrong here? thanks Paul From sholden at flexal.cs.usyd.edu.au Tue Oct 5 00:56:38 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 5 Oct 2004 04:56:38 GMT Subject: New to Python: Features References: <4162200b$0$59533$a1866201@newsreader.visi.com> Message-ID: On Tue, 05 Oct 2004 00:36:46 -0400, Richard Blackwood wrote: > Grant Edwards wrote: > >>On 2004-10-05, Richard Blackwood wrote: >> >> >> >>>When I said "harsh", I meant being accused of trolling, >>>attempting to annoy, stir trouble, etc. None which was my >>>intent nor did I think that my post would be interpreted as >>>such (otherwise I wouldn't have posted it). >>> >>> >> >>If you honestly didn't think you were being rude and weren't >>going to annoy anybody, you really, really do need to read how >>to ask questions the smart way. c.l.p is a very kind place, >>but should somebody as naive as you wander into the rest of >>Usenet... well, I just don't like to think of what might >>happen. >> >> >> > Apparently it is not a matter of "smartly" but don't ask at all. Part of asking smartly is not asking thousands of people to each spend time reading an possibly answering a question that you could find the answer to yourself with a minute of looking. -- Sam Holden From xnews2 at fredp.lautre.net Tue Oct 26 10:37:07 2004 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 26 Oct 2004 14:37:07 GMT Subject: [warning: 99% OT] does anything like this exist ?... References: Message-ID: Cliff Wells said : > Rather that doing that, you might consider simply setting up a local > IMAP server on your Linux box. Have a program (such as fetchmail) > pull down your POP3 email, filter it using procmail and feed it into > the IMAP server so that you can then access it from anywhere. Thanks, Cliff. I realize this would be the "standard" way of going about such things (didn't want to bloat the original post :-). However I tend to think of it as a fallback solution if nothing else comes up, if only for the following reasons : * a lot of upfront work : several major packages (fetchmail, procmail, imapd) I have no hands-on experience with, a lot of reading/learning and a lot of little things to get just right in each... In my mind the solution I'm after could be a much simpler affair, but then maybe I'm daydreaming :) * one more potential security hole on my home machine : I tend to limit open ports on that one to a bare minimum, my admin skills & available time being quite limited... * availability : my ISP doesn't filter spam but otherwise does a good job of keeping its server up. Depending on my own setup means I could get shut out when away from home because of a power failure, DSL downtime, a full disk, or any of a myriad other domestic problems... I've been paged about so many similar setups in the workplace that I'll avoid them at home if I can... But then, sometimes you _do_ have to turn to plan B :-) -- YAFAP : http://www.multimania.com/fredp/ From anna at aleax.it Fri Oct 1 11:46:36 2004 From: anna at aleax.it (Anna Martelli Ravenscroft) Date: Fri, 01 Oct 2004 15:46:36 GMT Subject: python vs c# In-Reply-To: <0hhql0pqlpjam9dopbare3bo62d59fi1s0@4ax.com> References: <1gkgxts.1fq0rwq10mycqiN%aleaxit@yahoo.com> <41513aac$0$285$edfadb0f@dread12.news.tele.dk> <1gkih9r.pfgqukvpt1rcN%aleaxit@yahoo.com> <37tjl09an200u6tejkrtklc8ib86uk7rm1@4ax.com> <7E_6d.33917$35.1643590@news4.tin.it> <0hhql0pqlpjam9dopbare3bo62d59fi1s0@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On Thu, 30 Sep 2004 21:11:31 GMT, rumours say that Anna Martelli > Ravenscroft might have written: > > >>>Alex, you are 99% correct. Leave a 1% chance that Max referred to >>>"julio" as "it"... :) Trolls are genderless! >> >> >>Sorry, Christos. Alex was correct: "its" is the appropriate usage here. >>"it's" is a contraction of "it is", and NOT the possessive form of it. >>Furthermore, Alex was quite kind in *not* correcting the mismatch >>between the singular form of the verb "is" and the plural noun "points". >> I, otoh, am not so generous. >> >>The sentence *should* have read: >>"Well, not to feed the troll, but there are a few relevant points in its >>posting." > > > I see marriage has *its* advantages... :) LOL Actually, Alex and I first met over my correcting a subtle error in a posting he had made (playing the "more pedantic than thou" game). ;-) > Actually, my post was a rather silly pun (think "It" by Stephen King), Ah. Didn't catch the reference. One of (the few) Stephen King books I haven't read. > and that is the reason I inserted a smiley. I know that Alex was > correct. It's my fault that I didn't make myself absolutely clear I was > joking Actually, that you were being jocular was pretty clear... (I firmly believe that the speaker/writer has the responsibility > to make themselves understood assuming good intentions from the side of > the audience --and good intentions are the norm here on clpy :). Yep. Agreed - it's a great community. Anna From jepler at unpythonic.net Mon Oct 25 16:57:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 25 Oct 2004 15:57:13 -0500 Subject: Unqualified global vars, how? In-Reply-To: References: Message-ID: <20041025205711.GC26896@unpythonic.net> Python won't do what you're asking for. In your example code, "gv" is a local in A's __init__ function. If you write from Globals import gv class A: def __init__(self): global gv print gv gv += 1 the code will execute, but the line gv += 1 only re-binds gv in A, it doesn't change Globals.gv or the value bound to gv in any other module that executed the code 'from Globals import gv'. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rakis at gmpexpress.net Thu Oct 7 14:12:18 2004 From: rakis at gmpexpress.net (Tom Cocagne) Date: Thu, 07 Oct 2004 14:12:18 -0400 Subject: Embedded Python. References: <74b8e0de.0410070353.17ab0890@posting.google.com> Message-ID: <10mbg5dianq89e@corp.supernews.com> The py2exe site and associated wiki may have some useful information for you. http://starship.python.net/crew/theller/py2exe/ http://starship.python.net/crew/theller/moin.cgi/Py2Exe winlinchu at yahoo.it wrote: > I would want to embed Python interpreter in an application, but only > the > interpreter without the modules of the standard library (unless sys, > builtin or some others, that are indispensables). In "setup.py" of the > source tree, there is a variable that must contain the list of modules > to not install. I have added some modules, but does not work. > > How can I do? Thanks. From rff_rff at remove-yahoo.it Mon Oct 11 17:17:03 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Mon, 11 Oct 2004 21:17:03 GMT Subject: [ANN] Boo 0.4.3 - python-like language for .NET/Mono In-Reply-To: References: <8PGdnS7wN_uwg_rcRVn-qw@comcast.com> Message-ID: Istvan Albert ha scritto: > > A "hey, it looks like python but it is not really python" > approach has little chance of capturing a python programmer's > imagination. It just muddies the water and sows confusion among > potential adopters. well, but sometimes muddling water is a good thing. I see this languages as nice 'testbeds' for pythonic alternative worlds, just think of the optional typing thing > this is just an opinion, and I've been wrong many times before... so it's mine, and mine is even little valuable cause I'm dumb :) From aleaxit at yahoo.com Tue Oct 5 18:24:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 6 Oct 2004 00:24:43 +0200 Subject: New to Python: Features References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> <1gl6e9j.1cn88p21wfi6s0N%aleaxit@yahoo.com> <1gl6qcq.kcu4qi1qojaksN%aleaxit@yahoo.com> <_sB8d.3545$M05.1351@newsread3.news.pas.earthlink.net> Message-ID: <1gl7k7p.1a37gv1o1klclN%aleaxit@yahoo.com> Andrew Dalke wrote: ... > By "independent source" I meant to distinguish between > a external package that I installed and code the I wrote myself. > My thought, unbacked by practical experience, is that > on upgrades I would need to find all my own personalized > functions, export them, and import them into the new system. And that was basically what an APL (or APL2?) workspace let me do (except it was more often to get to another machine, not to upgrade versions of the system, but, no big difference). Whether the "personalized version" is one you've written yourself or got on a pack of cards from your friend Mario is no big deal here, they're both additions you'll likely want in your new workspace anyway. APL didn't let me hack internals any more than Python does -- and Ruby doesn't have workspaces any more than Python does... the idea of having workspaces (restorable saves of your interactive sessions &c) and that of hacking internals are surely orthogonal, I'm not sure why you're conflating the two. > To my understanding it either saves the full image, > or it saves code you've selected. How does it help > identifing all of the code that's relevant for this > sort of upgrade? It doesn't distinguish whether code X you wrote yourself or got from Mario, but... why would you care? If you did, surely a workspace concept could be built on top of some modern versioning system such as SVN to let you do the equivalent of a 'svn blame' -- but, again, this feels to me as a conflating of orthogonal concerns. > >>Personally I think the ability to do this is a horror, > >>precisely because it leads to the horrors you talk about. > > > > I wouldn't go so far as to call it a horror. I do consider it an excess > > of power/dynamism, which I'd rather not have in a language intended for > > production use. > > I'm having a difficult time understanding when you would > use the word horror vs. when not. Wouldn't it be okay to > have " 4 + '5' " produce 9 in a language not intended for > production use? It seems there is a sensitive threshold > between your 'good language' and one with 'horror'. After In Python, you can pretty easily define a type X such that instantiating X with an argument of 23 (only) results in a reload of all your currently reloaded modules plus an email to foo at aleax.it giving your system's uptime. I would consider taking advantage of such possibility a horror on the part of the programmer thus miscoding. I do not consider it a horror on Python's part to allow it, as the checks and prohibitions needed to forbid such silliness would be cumbersome and unwarranted. And I don't think the distinction is all that subtle, either. > all my language "Al2O3", which is Ruby plus that dozen > or so line patch for string coercion, seems to fit into > your horror category. So would Python plus a rebinding of __builtins__.hex to the above class X. So? What's your point? > Ahh, but then you're one who used 'horror' when describing > the "print >>" syntax so "horror", "production use", and > "good language" are not independent terms. ;) print>>bah,'eek' is a bletch whether in production or just horsing around -- that's different!-) > Ruby has a way to freeze objects, so they cannot be changed. Yeah, looks like a cool idea, but Ruby experts tell me it's never really practically useful... much like, say, double-leading-underscores names in Python classes -- neat idea, but not used in best practice anyway. > In my view of things I would have had the system objects > frozen so that they cannot be changed, so that like in > Python system class behavior only 'modifiable' through > subclassing. > > That would have left the power/dynamism available, but in > such a way as to moderate its impact. easy enough to un-freeze frozen objects. Having them start frozen might avoid some accident but I don't think such accidents are really that much of a concern in this context. > Sadly my unassisted memory grows rusted. I was confusing Mine too (just started my 50th year -- it's 23 minutes after the end of my 49th b'day, local time), that's part of why google's SO useful;-). > that with another part of the same thread where I pointed out > to you > > >> proxy = Proxy(...) > >> sys.modules[module_name] = proxy > >> > >> In other words, what you import doesn't need to be a module. > >> It can be a class instance instead - or any other data type. > > and you replied > > Now THAT is interesting! I would never have guessed that the > > items in sys.modules need not be module objects. Is this Yep, a completely different issue from what goes on the right of a %. Similar in being about Python not forbidding something though it isn't to be used 99.9% of the time, much like modifying built-ins;-). Alex From theller at python.net Fri Oct 29 03:45:07 2004 From: theller at python.net (Thomas Heller) Date: Fri, 29 Oct 2004 09:45:07 +0200 Subject: py2exe and CD-ROM ISO Level 1 References: <654v3r4f.fsf@python.net> Message-ID: Werner Merkl writes: > Hi, > > I recompiled my application as a console program and got following > error message: > > ----------------------------------------------------------------------- > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\>e:\AUTORUN.EXE > Traceback (most recent call last): > File "D:\PROGS\Python23\lib\site-packages\py2exe\boot_common.py", > line 69, in ? > import linecache > zipimport.ZipImportError: can't decompress data; zlib not available > Traceback (most recent call last): > File "AutoRun.py", line 54, in ? > zipimport.ZipImportError: can't decompress data; zlib not available > ----------------------------------------------------------------------- > > so I removed "compressed": 1, from setup.py and it WORKS!!! Great! > This seems to be a bug in py2exe ???? The zlib module is the only one that is imported with the standard mechanism, since it is imported when a zipfile is added to sys.path. So, when it's filename has the wrong case the import will fail, and the only solution would be to set PYTHONCASEOK=1 before. Unfortunately, this cannot be done somewhere in your Pythoncode, because it's too late then. So, if you insist on 'compressed': 1 (but why would you?) the only solution that I see is to add _putenv("PYTHONCASEOK=1"); to the source file start.c, somewhere in the init_with_instance function, near line 135, and rebuild py2exe. Thomas From bokr at oz.net Sat Oct 30 05:02:14 2004 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Oct 2004 09:02:14 GMT Subject: "number-in-base" ``oneliner'' References: <1gmfz0k.a3xefz1xzms61N%aleaxit@yahoo.com> <41832f8b.1140475326@news.oz.net> <41834032.1144738587@news.oz.net> Message-ID: <418357db.1150795766@news.oz.net> On Sat, 30 Oct 2004 07:48:34 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sat, 30 Oct 2004 06:07:23 GMT, bokr at oz.net (Bengt Richter) wrote: >[...] >>Maybe something useful in this? Not very tested (and not terribly clear either ;-) >> >> >>> def number_in_base(x, N, digits): >> ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter( >> ... lambda qr=[abs(x),0]:qr[0] and ( >> ... qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]) >> ... , 0)][::-1]) >> ... > >Alternatively, a little more compactly (though I feel guilty about the -1 ;-): > > >>> def number_in_base(x, N=10, digits='0123456789ABCDEF'): > ... return '-'[:x<0] + ''.join(list(iter(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0) and ( > ... qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]), False))[::-1]) > ... Yet another, prefixing digits instead of joining reversed list: >>> def number_in_base(x, N=10, digits='0123456789ABCDEF'): ... return '-'[:x<0]+reduce(lambda s,c:c+s, iter(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0) ... and (qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]), False)) ... >>> number_in_base( 0 , 2, '01') '0' >>> number_in_base( 1 , 2, '01') '1' >>> number_in_base(126, 2, '01') '1111110' >>> number_in_base(-126, 2, '01') '-1111110' Regards, Bengt Richter From sxanth at ceid.upatras.gr Sat Oct 9 15:57:54 2004 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Sat, 09 Oct 2004 12:57:54 -0700 Subject: ANN: GUI wrapper for pygtk, pyqt and wxpython In-Reply-To: References: Message-ID: Bats wrote: > > Traceback (most recent call last): > File "run2.py", line 40, in ? > GUI=wrap_pygtk > NameError: name 'wrap_pygtk' is not defined > I don't know. Sounds like a python bug. Can't we say: import foo bar = foo anymore? Maybe copy the wrap_*.py files into examples/ and ./run2.py from in there? Regards, Stelios From aahz at pythoncraft.com Mon Oct 4 10:12:46 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Oct 2004 10:12:46 -0400 Subject: OT: Grammatical nitpicks (was Re: python vs c#) References: <0l7ul05ker0i9n039c0ut4pna3hh54dfou@4ax.com> <415F67E0.8040200@holdenweb.com> Message-ID: In article <415F67E0.8040200 at holdenweb.com>, Steve Holden wrote: >Tim Roberts wrote: >> >> Second, "their" is allowed as a singular pronoun only in those cases >> where a gender-specific pronoun is called for, but the gender is >> unclear or would be sexist. Instead of "Everyone brought his Python >> manual," we are now allowed to say "Everyone brought their Python >> manual." >> >> However, in the example that started this, "village" has no gender. >> Thus, I don't see that "their" is an acceptable alternative to "its" >> in this case. > >Well, as far as I can see (since you've admitted you're in this for >fun), I agree that the stated use of "their" you mention was primarily >for reasons of political correctness, to avoid arguments about whether >"his or her" or "her or his" should be used. "Their" was in common use as a singular pronoun long before political correctness existed as a phrase. Of course, we can also have a long debate about the misuse of "political correctness"... >Of course Aahz would doubtless be able to quote the specific genitive >form of "zhie", a word I have never been able to like, invented for >much the same reason (and I've probably got the word wrong, since I'm >definitely not a regular user). I'm not much of a grammatical analyst, so I don't know what you mean by "genitive form". The standard forms that I use are zie, zir, zirs, and zirself. >I must admit I didn't find the Cambridge quote at all convincing. And I >don't mind irritating people ... now there's a nice ambiguity for you! What meaning are you using for "nice"? ;-) PS: I really wish people would change the Subject: line more often; I almost skipped this thread because I have no interest in C#. I only poked my nose in 'cause Alex was posting. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines." --Ralph Waldo Emerson From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sun Oct 10 04:22:55 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sun, 10 Oct 2004 09:22:55 +0100 Subject: Init a table of functions In-Reply-To: References: <1097371939.905273@mystique.esoterica.pt> <4168A727.6050606@cloudthunder.com> Message-ID: Richard Blackwood wrote: > Now that I think of it some more, why did you add that object arg? > That's not necessary. It gets you a new-style class instead of an old-style class, and it is a good habit to have. http://www.python.org/2.2.3/descrintro.html -- Michael Hoffman From loritsch at gmail.com Sun Oct 17 15:19:34 2004 From: loritsch at gmail.com (Michael Loritsch) Date: 17 Oct 2004 12:19:34 -0700 Subject: detecting enabled network interfaces in win32 References: Message-ID: matt.torment at gmail.com (Matthew K Jensen) wrote in message news:... > In one of my "because I can" projects, I want to be able to see the > enabled network interfaces on a machine. I have no clue as to how to > do this. Any suggestions? Use the WSAIoctl function of Winsock2 with the command (2nd parameter) dwIoControlCode = SIO_GET_INTERFACE_LIST. The other key important tidbit of information would be that you will need to pass the address of an array of INTERFACE_INFO structures to the output buffer (5th parameter - lpvOutBuffer) to obtain structures containing the information you desire. Below are links to the MSDN documentation of both the WSAIoctl function and the INTERFACE_INFO structure. Documentation for WSAIoctl: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/wsaioctl_2.asp Documentation for INTERFACE_INFO: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/interface_info_2.asp I don't that this function is exposed through any of the win32 python extensions, although I have not had time to research this in order to be sure. For that reason, you would likely have to access this method using ctypes. Enjoy, and please let me know when you've written such a script because I'd love to use it. =) Michael Loritsch From guettli at thomas-guettler.de Mon Oct 11 07:55:13 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 11 Oct 2004 13:55:13 +0200 Subject: Linenumbers: inspect.getinnerframes vs. traceback.format_exception References: Message-ID: Am Mon, 11 Oct 2004 13:29:30 +0200 schrieb Thomas Guettler: > Hi, > > the line numbers of inspect.getinnerframes are > different from traceback.format_exception. Found the fix in the CVS: Revision 1.47.8.1 - (view) (download) (as text) (annotate) - [select for diffs] Sat Jun 5 14:14:48 2004 UTC (4 months ago) by akuchling Branch: release23-maint Changes since 1.47: +3 -1 lines Diff to previous 1.47 [Bug #954364] inspect.getframeinfo() sometimes produces incorrect traceback line #s; fix is to look at tb.tb_lineno, not tb.frame.f_lineno. Patch from Robin Becker and me. Thomas From bowman at montana.com Tue Oct 26 00:33:52 2004 From: bowman at montana.com (bowman) Date: Mon, 25 Oct 2004 22:33:52 -0600 Subject: Reading XML like Python! References: Message-ID: <2u61uaF2712ksU1@uni-berlin.de> John wrote: > I have to read a lot of XML for my upcoming project. > XML is hard on my eyes. > Is there some sort of converter that converts XML to something more > eye friendly? I don't know what your XML data is, but an XSLT stylesheet and xsltproc will turn it into about anything you want. From zathras at thwackety.com Tue Oct 5 17:10:38 2004 From: zathras at thwackety.com (Michael Sparks) Date: Tue, 05 Oct 2004 22:10:38 +0100 Subject: Mandis Quotes (aka retiring """ and ''') References: <20041004215641.266008304.whereU@now.com> <10m5r2gd2u38898@corp.supernews.com> <4162f2c1$0$202$edfadb0f@dread12.news.tele.dk> Message-ID: <41630de6$0$44835$ed2619ec@ptn-nntp-reader02.plus.net> Max M wrote: > Jeff Shannon wrote: >> Russell Nelson wrote: > >> ISTM that these >> elaborate Mandis-quote schemes may significantly reduce the odds of >> needing to escape a string literal, but the cost (in clarity, >> transparency, and most importantly, ability to manipulate your code in >> anything other than an advanced, complying editor) is pretty high. I >> find '''triple quotes''' a lot easier to understand/explain than this >> scheme of defining arbitrary delimiters. > > In fact, the triple quotes are just special cases of the Mandis quotes, > and would still be legal. No? > > > '''Hello world''' > > 'x'Hello world'x' > > '4242424242'Hello world'4242424242' > > same difference Not really, no. " is essentially just '' as a single character. Indeed if you look at some forms of documentation (tends to be older docs), you'll often find things like ``this'' or ''this'' where these days people would write "this". (Some ancient keyboards didn't have " characters, which forced this approach) As a result you have: * 'this' * "this" * '''this''' Which is logically the same as the following, and can be viewed as the same, with an optimised second case. * 'this' * ''this'' * '''this''' Likewise when writing, many people will interchange ' with ", hence ''' whilst odd isn't suprising to see - it's a logical extension, and still looks like a form of quote. I've taken to using this incidentally in block quotes in emails and interestingly I've not had any comments as to what I mean by it. However ... > 'x'Hello world'x' > '4242424242'Hello world'4242424242' ... are completely different kettles of fish. to me I can't help reading those as mistypings of > 'x', Hello world, 'x' > '4242424242', Hello world, '4242424242' Which in turn look like mistypings. Far from being clearer you end up with something that looks like typoes even when you know the rules. Indeed how could you tell what the intent here was if you were presented with it and knew there was a bug, and that there was an issue in the code? foo = 'this'the'other'andnot'this' ? Is that legal ? Does that mean: * '''this'the'other'andnot'this''' or was it a rushed and they meant: foo = 'this',the,'other',andnot,'this' ? Python often tends to do things which even if suprising are fairly obvious what they mean to the casual observer. 'this' isn't like any other mainstream programing language and as a result would confused people much more than a simple 'this'. (Is that a mandis quote or is it a sentance that makes no sense? :) In many respects it's much like various tagging formats, but misses some advantages eg xml: isn't like any other mainstream programing language and as a result would confused people much more than a simple Unlike mandis quotes here we have a clear indication that the thing the "this"s are distinct from the data. Also it's clear that the following is a mistake: isn't like any other mainstream programing language and as a result would confused people like much more than a simple Whereas is the following a mistake? 'this' isn't like any other mainstream programing language and as a result would confused people like 'this' much more than a simple 'this' Personally I would say that if someone was _really_ interested in discarding quoting schemes, there's one easy way of doing so - only ever use ''' and """. It's trivial, it's implemented and is as you say very similar to Mandis quotes, but doesn't allow for uses that make maintenance harder. However personally I see a benefit between having """, ", ''', and ' - the single quote form makes it explicit that the string should terminate on that line, and makes it *a lot* simpler to find out if a quote is missing: foo = 'th,is',the,'oth,er',a'n,'dn',ot,'this' ? Whereas """ makes it clear the string *doesn't* terminate on the same line. Mandis quotes don't really help with conveying _either_ intent. Regards, Michael. From irmen at -nospam-remove-this-xs4all.nl Sun Oct 24 05:31:48 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 24 Oct 2004 11:31:48 +0200 Subject: ANN: Frog 1.0 beta (Python 'blog' system) In-Reply-To: <417adbe1$0$43451$e4fe514c@news.xs4all.nl> References: <417adbe1$0$43451$e4fe514c@news.xs4all.nl> Message-ID: <417b7684$0$78772$e4fe514c@news.xs4all.nl> Irmen de Jong wrote: > If you don't want to install it yet, you can first try it out here: > http://www.razorvine.net/snake/frog/ > (the passwords of each user is the same as the username). I forgot to mention that the 'test1' and 'test2' users can be used to post new articles. You'll have to login first, to be able to do that. --Irmen From gohadbhai at rediffmail.com Wed Oct 20 03:30:24 2004 From: gohadbhai at rediffmail.com (Sandeep Avinash Gohad) Date: 20 Oct 2004 07:30:24 -0000 Subject: reading a file... Message-ID: <20041020073024.26268.qmail@mailweb34.rediffmail.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- ? Hello I opened a file in a read mode a=open('c:/a.bd4', 'r') print a a.read() (This .bd4 format is not known for me.) This gives the following output : '\x08\x00BDF\x00\xef\xcb\x830\x8d\xa1\x07\x00\xf5\x00B1\x00\x003B\xf4\x01\x00\x00U\x0f\x04\x00SUF\x00\xef\xcb\x830\xf6\xa2\x07\x00!\x00B1\xcd\xac\x8eC\x9d\x1c\x00\x00\x8c\x00&\x00SDF\x00\xef\xcb\x830\xfd\xa2\x07\x00@\x00B133\x97A\x16\r\x00\x00[]\x07\x00SUF\x00\xef\xcb\x830\n\xa3\x07\x00A\x00B1\xcd\xccvD\x8c\x00\x00\x009\xec\x00\x00SDF\x00\xef\xcb\x830\x0f\xa3\x07\x00J\x00B1\xcd\xcc\x83B\xf4\x01\x00\x00\xe6h\x01\x00BUF\x00\xf0\xcb\x830\x14\xa3\x07\x00\x9e\x01B1\x9a\x99IA>\x05\x00\x00\xf5\'\t\x00SDF\x00\xf0\xcb\x830(\xa3\x07\x00\x18\x00B1f\xa6\xd5Cx\x00\x00\x00\xd1@\x03\x00SDF\x00\xf0\xcb\x830C\xa3\x07\x00L\x00B1\xcdL\xb1C0\x01\x00\x00\xa6\xd2\x02\x00SDF\x00\xf0\xcb\x830\x8c\xa3\x07\x00t\x00B1\x00\x00(C?\x07\x00\x00\xd0B\x04\x00BDF\x00\xf0\xcb\x830\x96\xa3\x07\x00G\x01B1\x00\x00\xc8A\xb6\x03\x00\x00\xce\xa1\x0b\x00BUF\x00\xf0\xcb\x830\x94\xa1\x07\x00K\x00B1f\xe so i can not read that file,according to me the data is in the hexadecimal format please tell me how to read this data and convert it into long datatype and then copy the data and save it into .csv file. please guide me... Regards sandeep In this program From ksenia at ksenia.nl Sat Oct 2 04:33:39 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sat, 02 Oct 2004 10:33:39 +0200 Subject: locale.setlocale problems Message-ID: Hi, I have some problems with locale module. On my workstation, changing locale doesn't have effect: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, 'nl_NL') 'nl_NL' >>> locale.format('%0.2f', 0.123) '0.12' (It should return: 0,12) On the server, it doesn't work at all: Python 2.3 (#1, Jan 4 2004, 14:30:19) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, 'nl_NL') Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/locale.py", line 381, in setlocale return _setlocale(category, locale) locale.Error: locale setting not supported All I want to do, is format numbers with comma as decimal separator in a web application. Is there some system libraries I have to install, to make locale work? And the last question: when I change locale in a Python application, it affects only the current namespace, right? I hope so... :) Thanks! Ksenia. From edwin at bathysphere.org Thu Oct 7 09:53:06 2004 From: edwin at bathysphere.org (Edwin Young) Date: 07 Oct 2004 06:53:06 -0700 Subject: Calling a constructor by reference Message-ID: Hi, I know there must be a way to do this but the correct syntax eludes me. I want to write a method which I can pass different types to and have it construct them. I tried this: >>> class X: def __init__(self): pass def make_thing(type,*args): return type(args) x = X() y = make_thing(X) print x, y >>> But get 'TypeError: __init__() takes exactly 1 argument (2 given)'. Presumably X is treated as an unbound instance method? Also, the types I want to create inherit from an old-style class in a package, so I don't think I can make X a new-style class (if that's relevant). How should I go about this? Thanks, -- Edwin From belred1 at yahoo.com Sat Oct 16 11:07:17 2004 From: belred1 at yahoo.com (Bryan) Date: Sat, 16 Oct 2004 15:07:17 GMT Subject: reloading updated modules in long running server? In-Reply-To: <4170E72B.7040509@wanadoo.fr> References: <4170E72B.7040509@wanadoo.fr> Message-ID: Pierre Quentel wrote: > I don't know if there is a way to catch the event "a file has been > modified in the file system" but you can always check if something has > changed in sys.modules every time a request is processed by the server, > or every n second > > Something like this should work : > > updateTime={} > for m in sys.modules.values(): > if m and hasattr(m,"__file__"): > modTime=os.path.getmtime(m.__file__) > if updateTime.has_key(m): > if modTime != updateTime[m]: > reload(m) > updateTime[m]=modTime > else: > updateTime[m]=modTime > > Pierre > if you have class A in module a.py and class B(A) in module b.py, and in module c.py you instantiale b = B(). will there be a problem if you reload module b, then c, then a? in the previous example, m in sys.modules.values() doesn't take this into account. bryan From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Oct 1 04:32:31 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 01 Oct 2004 09:32:31 +0100 Subject: Unexpected Python Behavior In-Reply-To: <41upl0p84hua97r8bjd6oobqvmd7886f5m@4ax.com> References: <4e4a11f8.0409232355.6ba0468d@posting.google.com> <2srcl0poenac7hl39gmbmgvj4e0sp6fp38@4ax.com> <1gkpsyw.16zk21c1hoc4taN%aleaxit@yahoo.com> <2s1cetF1emgg9U1@uni-berlin.de> <41upl0p84hua97r8bjd6oobqvmd7886f5m@4ax.com> Message-ID: [Andrea Griffini] >[Greg Ewing] >>[Alex Martelli] >>>I think it's in fact very nice syntax: >>This is a hack. Don't do it. > Who are you to question what Him, the Great Alex, says about it ? Who are you to question what Greg Ewing says? I'm having trouble figuring out whether the rest of this message is supposed to be ironic or sarcastic or something. I can say with certainty that it is pretty silly. -- Michael Hoffman From lutherrevisited at aol.com Sun Oct 10 13:59:48 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 10 Oct 2004 17:59:48 GMT Subject: Python email Message-ID: <20041010135948.07384.00002435@mb-m29.aol.com> I'm attempting to write an email client, and I've run into a snag. I've seen several docs on email, but they're not dumbed down enough for me. Basically I'm downloading my messages like this: M = poplib.POP3('pop.mail.yahoo.com') M.user('username') M.pass_('password') inMail = str(M.retr(i)) and I get the message just fine, but I want to pull out of all that just the html part. How can I do this. From markus_wankusGETRIDOFALLCAPS at hotmail.com Sun Oct 24 11:19:31 2004 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Sun, 24 Oct 2004 11:19:31 -0400 Subject: Fedora 1 and Eric3 In-Reply-To: References: Message-ID: Bats wrote: > Bats had this to say: > > >>Has anyone here managed to install Eric (Python GUI) on Fedora Core 1? >>I have had no end of sh*t from qscintilla right on up. It seems I have to >>jump through an endless series of hoops in a certain order to get to the >>end. >> >>Any step-by-step kinda help? >> >>*:* > > Ah well.... no feedback. Well.. I can give you feedback but it is kind of useless. I have found that no matter what distro I used - Fedora 1 or otherwise - getting that program to work (along with all of its seemingly circular dependencies) was a very unpleasant experience and one I never succeeded at. There is something to be said for the simplicity of Windows installers... All I can say is keep trying, and Google this newsgroup. This has come up here before - you are not alone... Markus. From aleaxit at yahoo.com Sun Oct 17 11:13:31 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 17 Oct 2004 17:13:31 +0200 Subject: PythonCom equivalent on Linux! References: Message-ID: <1glszmt.1r4o5td16zzgx1N%aleaxit@yahoo.com> John wrote: ... > across clients. I think you are pointing to something akin to IPC like > DDE. If you think CORBA can be used like an ActiveX in-process > control, please let me know how. CORBA itself allows every activation model one typically wants: in-process, external-process, remote-host. Just choose a CORBA implementation ("broker") that provides a support you like for your preferred activation models. PyORBit, for example (which you can find at ), working together with the ORBit2 object broker, should be fully capable of both using and being used by in-process servers and clients, as normally required for the application it's optimized for (Gnome). Other object brokers might also be suitable for your needs. Different Corba object brokers can interoperate, but might not be able to fully utilize each other's components with in-process activation (communication at the in-process level may be more efficient, but is typically more intrusive and less standardized, than clean communication via the standardized Corba inter-brokers protocol, IIOP). If your main thrust is building the equivalent of ActiveX "controls" (components with a visual interface), and GTK/Gnome is acceptable to you, PyORBit and ORBit2 might suit you best, for example. I have used COM extensively in the past, and Corba more modestly. It appears to me on the basis of this experience that Corba is technically superior to COM. Undoubtedly, on Windows, COM has the advantage of being widespread; particularly for the purpose of automating ("scripting") applications, being able to rely on just about every application of note being forced by market demand to provide _some_ level of COM "scripting" interface is quite enabling (even though many of those interfaces are badly designed, sprawling, ungainly hulks -- mostly not due to COM problems, but to defects inherent in the architecture and internal design of the applications in question -- nevertheless being able to get at them SOMEhow is still better than not getting any access to them). Neither Corba nor any other standard (XPCOM, UNO, etc, etc) is likely to gain total ascendancy comparable to what COM gained in Windows, in my opinion. The very existence of many good standards competing in good part for the same set of niches, and each enjoying significant support, precludes that ascendancy. Moreover, there are objections to the whole concept in some sectors of the Unix community; Eric Raymond's excellent book, "The Art of Unix Programming", has a short section which summarizes those objections, albeit a bit tersely (IMHO, the book is well worth reading even if you think you'll never program for anything but Windows, BTW: it has many important lessons to teach). Alex From deetsNOSPAM at web.de Thu Oct 28 12:34:12 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 28 Oct 2004 18:34:12 +0200 Subject: strong/weak typing and pointers References: Message-ID: > Is it correct to say that strong/weak typing does not make a difference > if one does not use any pointers (or adress-taking operator)? It seems that you mistake strong/weak typing with static/dynamic typing - a completely different beast. Python is in fact strong typed - in opposition to php or perl or even C, this won't work: a = "1" + 2 as "1" is a string and 2 an integer. And even though C is statically typed, it won't complain - you just end up with an unexpected result. And pointers are not evil in themselves - the are a neccessity to create recursive structures. But deliberately casting pointers can be very harmful - a reason why its forbidden in languages like java and AFAIK ada. > More concretely, I am thinking particularly of Python vs C++. > So, are there any examples (without pointers, references, or > adress-taking), which would have a different result in Python and in C++? I have difficulties to understand what you want here. Please elaborate. -- Regards, Diez B. Roggisch From lutherrevisited at aol.com Sat Oct 23 20:41:44 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 24 Oct 2004 00:41:44 GMT Subject: wxIEHTML References: Message-ID: <20041023204144.02596.00002524@mb-m13.aol.com> Thanks alot, that was perfect. From mfuhr at fuhr.org Tue Oct 12 23:47:56 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 12 Oct 2004 21:47:56 -0600 Subject: HTTP Headers to make a download References: <6f402501.0410120756.63276342@posting.google.com> Message-ID: <416ca56c$1_3@omega.dimensional.com> fuzzyman at gmail.com (Michael Foord) writes: > I'm creating a CGI that offers files for download. After googling I > though I had the right headers to send to force a download - but it > sends the data to the browser instead of opening the download 'save > file' dialog. Can anyone see what I'm doing wrong/suggest an > alternative ? > > responseline = '''Content-Type: application/octet-stream > Content-Disposition: attachment; filename=%s > Content-Length: %s > ''' > > print responseline % (filename, len(filedata)) > print filedata What browser and platform are you using? Not all browsers honor Content-Disposition -- some base their display-or-download decision on the content itself. For example, using Opera 7.54 on FreeBSD and your example code, this string displays in the browser: filedata = 'What hath Guido wrought?' Whereas this string, different only in the first character, caused the browser to present a download popup: filedata = '\xbfWhat hath Guido wrought?' In the first case, where the browser displayed the data, clicking "Save" or "File->Save As" did use the file name that was in the Content-Disposition header. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From cmedcoff at hotmail.com Wed Oct 6 22:13:12 2004 From: cmedcoff at hotmail.com (Chuck) Date: Wed, 6 Oct 2004 22:13:12 -0400 Subject: PythonWin Errors while debugging Message-ID: I frequently observe the stack trace below while using PythonWin (which I otherwise love). I seem to be associated with debugging, breakpoints and possibly moving focus from/to PythonWin. Anyone else observe this? [Dbg]>>> Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\dbgcommands.py", line 73, in OnGo self._DoOrStart("do_set_continue", scriptutils.RS_DEBUGGER_GO) File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\dbgcommands.py", line 57, in _DoOrStart method() File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 636, in do_set_continue if self.GUIAboutToRun(): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 787, in GUIAboutToRun if not self.StopDebuggerPump(): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 485, in StopDebuggerPump if self.GUIAboutToFinishInteract(): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 836, in GUIAboutToFinishInteract self.oldForeground.EnableWindow(1) win32ui: The window handle does not specify a valid window win32ui: Error in Command Message handler for command ID 15022, Code 0 Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\dbgcommands.py", line 79, in OnClose d.set_quit() File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 642, in set_quit ok = self.StopDebuggerPump() File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 485, in StopDebuggerPump if self.GUIAboutToFinishInteract(): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 836, in GUIAboutToFinishInteract self.oldForeground.EnableWindow(1) win32ui: The window handle does not specify a valid window win32ui: Error in Command Message handler for command ID 16010, Code 0 Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", line 53, in OnClose pywin.debugger.currentDebugger.close(1) File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 450, in close if not self.StopDebuggerPump(): # User cancelled close. File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 485, in StopDebuggerPump if self.GUIAboutToFinishInteract(): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 836, in GUIAboutToFinishInteract self.oldForeground.EnableWindow(1) win32ui: The window handle does not specify a valid window From aleaxit at yahoo.com Sun Oct 17 11:13:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 17 Oct 2004 17:13:29 +0200 Subject: "Visually following", line by line, the execution of a program References: Message-ID: <1glsw1g.1r6zq9cu24b5bN%aleaxit@yahoo.com> Andr? Roberge wrote: > I want to "import and execute" a python program (input_test.py below) > within another program (execute_test.py below) and "watch it" being > executed. > By watching it, I mean to display the file input_test.py in a window > (GUI) and highlighting the line being executed. The functionality you require is known as 'tracing'. See section 9.2, "How it works", in the Python Library Reference, for all details. With sys.settrace, you establish your chosen 'tracing function', and it gets called with three arguments, frame, event, arg. event is a string which can be 'call', 'line','return', 'exception'. The 'line' event is the main one you care about: from the frame object you can find out what file and line is about to be executed. Be sure to have the trace function return itself if it wants to keep tracing, because for most events the trace function's return value is taken as the new trace function to use (locally, i.e. within the function currently being traced) for future tracing, None meaning stop tracing (at this level of function call). Alex From mwh at python.net Thu Oct 14 11:10:44 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Oct 2004 15:10:44 GMT Subject: read a files particular line References: Message-ID: Frank Grellert writes: > Hi, > does anybody have an idea how to read a particular line of a file like awk's > awk '{if( NR==12) print $0}' filename (reads lineno 12 of filename) > for lineno, line in enumerate(open_file): # lineno starts at 0, though Cheers, mwh -- I feel so special when people quote me -- from Twisted.Quotes From egbert.list at hccnet.nl Sun Oct 10 10:26:59 2004 From: egbert.list at hccnet.nl (Egbert Bouwman) Date: Sun, 10 Oct 2004 16:26:59 +0200 Subject: Graceful handling of first line In-Reply-To: <1glf0aw.d4q2xilmpg8wN%aleaxit@yahoo.com> References: <654bb44cb5ff9def08dab7c56459c4c0@localhost.talkaboutprogramming.com> <4165C9FD.5060000@bellsouth.net> <1glc6g0.1ner1219acqffN%aleaxit@yahoo.com> <1glf0aw.d4q2xilmpg8wN%aleaxit@yahoo.com> Message-ID: <20041010142658.GA1089@mirk.lan> On Sun, Oct 10, 2004 at 12:41:37AM +0200, Alex Martelli wrote: > .... > But the iteration state is not connected with the > file's current position. > That is very useful information.Thanks. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From andrea.valle at unito.it Fri Oct 8 13:47:57 2004 From: andrea.valle at unito.it (andrea valle) Date: Fri, 8 Oct 2004 19:47:57 +0200 Subject: wxPython toot In-Reply-To: <4166C6C9.7030501@comcast.net> References: <4166C6C9.7030501@comcast.net> Message-ID: <30B8EFDA-1952-11D9-8C02-0003939C968C@unito.it> Hi to all can anyone point me to a wxpython tutorial (something like the Intro to tkinter by Lundh)? Thanks -a- From arvid at linux.se Thu Oct 21 11:19:04 2004 From: arvid at linux.se (Arvid Andersson) Date: Thu, 21 Oct 2004 17:19:04 +0200 Subject: Matrix (list-in-list), how to get a column? Message-ID: <20041021151904.GA25755@shell.linux.se> Good afternoon, I have some data that looks like this: data = [[1, 2], [3, 4], [5, 6]] I want to send columns 1 and 2 to a function as two variables, say "plot(col1,col2)". I can get a row by data[r], but how do I get a column? data[:][c] would have been my guess, but that returns the same list as data[r]. I can solve this with two additional lists and a for loop, but that seems like an ugly hack. Five additional lines just seems clumsy. :-) Is there a more elegant solution than this? col1 = [] col2 = [] for i in range(len(data)): col1 += [a[i][0]] col2 += [a[i][1]] /Arvid Andersson From ville at spammers.com Fri Oct 22 11:54:18 2004 From: ville at spammers.com (Ville Vainio) Date: 22 Oct 2004 18:54:18 +0300 Subject: About lambda. References: Message-ID: >>>>> "Xin" == Xin Wang writes: Xin> Some c++ guru said c++ is hard to learn but easy to use. Is I would question such a guru. There is nothing "easy to use" about C++. Or perhaps the Guru hadn't tried any other modern language apart from C. -- Ville Vainio http://tinyurl.com/2prnb From erik at heneryd.com Sat Oct 30 11:56:12 2004 From: erik at heneryd.com (Erik Heneryd) Date: Sat, 30 Oct 2004 17:56:12 +0200 Subject: Regex speed In-Reply-To: <2uh4g5F29ntaoU1@uni-berlin.de> References: <2uff4eF2a7uskU1@uni-berlin.de> <2uh4g5F29ntaoU1@uni-berlin.de> Message-ID: <4183B99C.6050503@heneryd.com> Reinhold Birkenfeld wrote: > OK, thank you. I now got rid of all the regexes, and - surprise, > surprise - the speeds are almost equal. The bitter thing about it is > that there are now twelve LOC more in Python that don't make > understanding the code easier. If your problem is that the re.compile() setup takes too long (compared to the time taken to do the actual matching/replacing), my guess is that you don't operate on that much data. And if that's the case, does it really matter if it's a fraction of a second slower? Note that str.find() currently uses the naive approach resulting in bad time complexity, so it's not suitable for larger data sets. See http://online.effbot.org/2004_08_01_archive.htm#find Erik From adalke at mindspring.com Tue Oct 5 01:56:41 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 05 Oct 2004 05:56:41 GMT Subject: New to Python: Features In-Reply-To: References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> Message-ID: Richard Blackwood wrote: >> exec code, glbls, lcls >> > > > This is a cool language, I love code chunks!! Like I said with eval, DO NOT USE THIS! It almost certainly means you're doing the wrong thing. It's full of security holes and there are nearly always better ways to solve the underlying problem. > How come Python always complains when I don't include the self parameter > in an object method? Your code doesn't work on my interpreter. Remember that pointer to asking smart questions? Remember that part about reading the documentation? Doing those would seriously help your understanding and help us know what you mean with "always complains" and "doesn't work." > I know but that's a real bummer. No way around that? Python is not a functional programming language. Do you want it because it's cool or because it's useful? > So is the print statement ironed into the language and not a function? Documentation. Does it look like a function? >>> 20. Date persistence and serialization >> >> >> >> This can mean any one of a dozen things. >> > > I'd like to store function and variables and of course objects in a form > that can be easily read back into the program/script. This can mean any one of a dozen things. They are all available in Python. Some are standard modules. Read the docs. Python doesn't support Smalltalk's system image. That's probably a good thing. > Oh really?? Exciting, I'm glad of it. Hit the docs I must! Umm... Yes. >>> 22. Is the self parameter hidden from me as a programmer? Can I >>> hide/unhide it as I wish? >> >> It is not hidden, in fact, you get to name it... >> >> class foo: >> def goo(I_AM_SELF, arg): >> pass >> > Cool! DO NOT DO THAT EVER! Seriously not cool. > Not fully implemented, but I guess that will have to suffice. Is there any non-trivial language which is fully implemented for C#? >> Python has no static typing. >> > > Argg! This is precisely why my first reply said this question was way too hard to answer briefly. You claim experience with Smalltalk. Smalltalk has no static typing either. There are many essays available (and books no doubt) on all the nuances here. You've used Ruby -- it's the same there too. > I'd like to be able to use a string as an integer without an explicit > coerion on my part for example. NO! Don't do that. Bad code. Subtle errors. Try Perl or Ruby instead. > Ugly? I disagree, but hey, what do I know? Objective-C is OOP and > messaging is awesome. I love Python though, a hybrid between the two > would be great. Do some research for your own and see if such thing exists. Hint: yes. > That is quite a shame, no modules for this either huh? It quite depends on your expectations of what design by contract, protocols, etc. means. Do some research. Hint: Google for 'python "design by contract"' and related topics. >>> 34. In pure Python, can I change and add new constructs to the Python >>> syntax? >> >> Yes, if you are willing to work for it. >> > > I expect the docs will tell me how to do this. Yes, the docs for modifying the interpreter. >>> 37. Dynamic dispatch >> >> This could mean a few different things. >> > > Like virtual functions in C++ Docs. Read. Enjoy. When you say "like virtual functions in C++" do you also mean supporting the same resolution algorithm for handling diamonds in multiple inheritance? Do you mean are they bound vs. unbound? That you can use pointer arithmetic to go up and down the vtable? That they aren't introspectable? That's why I say it's easier to just read the docs rather than have people give you short answers that aren't useful without the entire context of how Python works. > What I actually meant was are there any facilities (built-in or modules) > which allow for automatic compilation to C/C++/C#/D. For example, > particular Smalltalk distros compile to C as does ObjC. Yes. But you'll never use them. The problem you'll want to solve is "how do I call Python code from a ... library" or "how do I package Python as an executable" and not "how do I convert Python code into C". You are asking the wrong question. You are asking about technique, not goal. >>> 43. Embedding variables in strings like: print "Hello, World. Time: >>> #{Time.now}" >> >> t = time.asctime() >> print "Hello World %(t)s"%{'t':t} >> print "Hello World %(t)s"%locals() >> > > That is messy, exactly why I wanted the kind of clear embedding I gave > an example for. Oh well. You asked for "embedding variables" not embedding expressions. You got what you asked for, not what you wanted. That's part of being able to ask the right question. Remember that essay people suggested you read? > Really? Hmmmm, does anyone know of a bridge between Python and Ruby? Why not just use Ruby? It seems to fit your search criteria much better. Andrew dalke at dalkescientific.com From aleaxit at yahoo.com Wed Oct 13 08:19:56 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 13 Oct 2004 14:19:56 +0200 Subject: strange side effect with lists!? References: Message-ID: <1glllnv.9f2gdijdroqgN%aleaxit@yahoo.com> wrote: > Hello, > > I'm new to Python and playing around. I'm confused by the following > behaviour: > > >>> l1 = [1] # define list > >>> l2 = l1 # copy of l1 ? > >>> l2,l1 > ([1], [1]) > >>> l2.extend(l1) # only l2 should be altered !? > >>> l2,l1 > ([1, 1], [1, 1]) # but also l1 is altered! > > So what is the policy of assignment? When is a copy of an object created? > Where to find dox on this? Bruno's answer seems very thorough so I'll just try to briefly summarize the answers: 1. simple assignment (to a bare name, at least), per se, never implicitly copies objects, but rather it sets a reference to an object (_another_ reference if the object already had some). 2. a new object is created when you request such creation or perform operations that require it. Lists are particularly rich in such operations (see later). Simple assignment to a bare name is not an operation, per se -- it only affects the name, by making it refer to whatever object (new, or used;-) is on the righht of the '='. 3. I believe any decent book on Python will cover this in detail. Now for ways to have a new list object L2 made, with just the same items and in the same order as another list object L1 ("shallow copy"): a. import copy; L2 = copy.copy(L1) This works to shallow-copy _any_ copyable object L1; unfortunately you do have to import copy first. Module copy also exposes function deepcopy, for those rare cases in which you wish to recursively also get copies of all objects to which a "root object" refers (as items, or attributes; there are some anomalies, e.g., copy.deepcopy(X) is X when X is a class, or type...). b. L2 = list(L1) I find this is most often what I use - it works (making a new list object) whatever kind of sequence, iterator, or other iterable L1 may be. It is also what I recommend you use unless you have some very specific need best met otherwise. c. various operations such as...: L2 = L1 * 1 L2 = L1 + [] L2 = L1[:] i.e. "multiply by one", "concatenate the empty list", or "get a slice of all items". I'm not sure why, but the latter seems to be very popular, even though it's neither as concise as L1*1 nor as clear and readable as list(L1). Alex From mcfletch at rogers.com Tue Oct 12 22:09:43 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 12 Oct 2004 22:09:43 -0400 Subject: Python control of desktop properties In-Reply-To: <416c8404$1_3@alt.athenanews.com> References: <416c8404$1_3@alt.athenanews.com> Message-ID: <416C8E67.3040900@rogers.com> You want to call the function: user32.SystemParametersInfo( SPI_SETDESKWALLPAPER, 0, imageLocation, |SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE ) You can likely do that fairly readily with ctypes. Sorry, don't have time to do more than point you at it tonight. Good luck, Mike | ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From alikakakhel3 at hotmail.com Fri Oct 29 21:38:37 2004 From: alikakakhel3 at hotmail.com (Ali) Date: 29 Oct 2004 18:38:37 -0700 Subject: How to use python in matlab Message-ID: <8f17f4bc.0410291738.2f3708b8@posting.google.com> How to use python in matlab? From les_ander at yahoo.com Tue Oct 5 11:51:15 2004 From: les_ander at yahoo.com (les ander) Date: 5 Oct 2004 08:51:15 -0700 Subject: convert scientific integer to normal integer Message-ID: Hi, i have a file with lines like this: 1.7000000e+01 2.4000000e+01 1.0000000e+00 8.0000000e+00 1.5000000e+01 2.3000000e+01 5.0000000e+00 7.0000000e+00 1.4000000e+01 1.6000000e+01 4.0000000e+00 6.0000000e+00 1.3000000e+01 2.0000000e+01 2.2000000e+01 1.0000000e+01 1.2000000e+01 1.9000000e+01 2.1000000e+01 3.0000000e+00 1.1000000e+01 1.8000000e+01 2.5000000e+01 2.0000000e+00 9.0000000e+00 Notice that they are all integers. What I want to do is write them out in a regular way, by which I mean that the output should look like this: 17 24 1 9 15 23 5 7 14 16 etc I tried the following but it did not work: fp=open(argv[1]) for x in fp: xc=[int(e) for e in x.split()] print " ".join(xc) any help would be much appreciated From m_vddungen at yahoo.com Sun Oct 17 17:25:16 2004 From: m_vddungen at yahoo.com (Marcel van den Dungen) Date: 17 Oct 2004 14:25:16 -0700 Subject: Python in HTAs Message-ID: <98862c6.0410171325.352a5df4@posting.google.com> Does anybody know how to use Python as the scripting language for HTML applications? I tried the following, but I get a script error ('Object expected') on the body element. Python controlled HTML application Could not find any example on Google either. TIA, Marcel From harddong at 21cn.net Fri Oct 1 04:46:20 2004 From: harddong at 21cn.net (Dong Ge) Date: Fri, 01 Oct 2004 16:46:20 +0800 Subject: Search and Replace in a text. References: <06opl01rgc7d31l1efuc8ce7apgj9g1dq4@4ax.com> Message-ID: <2d5ql0pd8f5m1jnf090h30ufiirekln7c7@4ax.com> Thanks for your reply. First, I need find the the "Layer:" tag in the orginal text file, then copy fllowing text string until the new line beginning ( The first text string is "TV-Frame" in the "Text 1".). Second, I need find the "Attr:" tag fllowing the previous "Layer:" tag, and replace the text string next to the "Attr:" tag with the content in clipboard. Third, finding the next "Layer:" tag and repeat the first step and second step until the end of file. A lot of thanks again! ---- Dong Ge 2004.10.01 Text 1: ... Layer: Tv-Frame Flags: 0x0 Attr: 1 Focus Point: 0 0 0 Layer: Tv-pic Flags: 0x2300 Attr: 1 Focus Point: 0 0 0 Layer: Tv-shell Flags: 0x0 Attr: 1 Focus Point: 0 0 0 ... Text 2: ... Layer: Tv-Frame Flags: 0x0 Attr: Tv-Frame Focus Point: 0 0 0 Layer: Tv-pic Flags: 0x2300 Attr: Tv-pic Focus Point: 0 0 0 Layer: Tv-shell Flags: 0x0 Attr: Tv-shell Focus Point: 0 0 0 On Fri, 01 Oct 2004 09:23:13 +0100, Michael Hoffman wrote: >Dong Ge wrote: > >> I'm a new beginner of Python. I want to convet "Text 1" to "Text 2" >> below. How to do it? > >Sorry, you're going to have to describe your problem a little more fully >before I can help you. Otherwise I can only guess. From bokr at oz.net Mon Oct 4 20:59:01 2004 From: bokr at oz.net (Bengt Richter) Date: 5 Oct 2004 00:59:01 GMT Subject: Mandis Quotes (aka retiring """ and ''') References: <1db750f5.0410040645.352cd68c@posting.google.com> Message-ID: On 4 Oct 2004 07:45:54 -0700, nelson at crynwr.com (Russell Nelson) wrote: >Jef Raskin (namedropping) has pointed me at a neat scheme for quoting >arbitrary textual matter called "Mandis quotes". Since google is >ignorant of the phrase, I presume that Jef made it up. It is >disgustingly simple, and very Pythonesque. Here's how it works: If >you have a string that doesn't have any single quotes in it, you >surround the string by a pair of doubled single quotes. ''Like >this''. No backslash interpolation. If you want a character in >there, you put it in there (yes, I know, stand down your armies). >Clearly, then, any character except a single quote can go into one of >these strings. If you need to put a single quote in, then you put >an arbitrary string in-between the single quotes which does NOT >appear in the string. For example, "Bill's house" becomes >'x'Bill's house'x'. > >More formally, a mandis quote is a pair of tokens surrounding a >completely arbitrary sequence of bytes. These tokens are comprised of >a possibly null sequence of characters preceded by and followed by a >single quote. I once started a thread with the same (quoting arbitrary text) goal, but I made it a special case of Python string syntax, using a q or Q prefix: q'x'Bill's housex I thought about re-quoting the 'x' at the tail, but thought more typical usage would use a special character for single-character delimiters, e.g., q'|'Bill's house| See http://groups.google.com/groups?group=comp.lang.python.*&selm=a5srm2%24254%240%40216.39.172.122&rnum=2 And click on view complete thread to see all 36 posts ;-) > >To save time, here's why this pre-PEP proposal sucks in decreasing >order of severity: > >o Python source is typically represented, not as an arbitrary string > of ASCII or Unicode characters, but instead as a sequence of lines > separated by the native line terminator (e.g. CRLF, LF, or CR). See Q'... in the above cited thread. > >o Editors are not all up to the task of inserting arbitrary > characters into strings (although they SHOULD). > >o Email cannot withstand arbitrary strings of characters (although > quoted-printable suffices). > >o Some distinct Unicode characters are represented using the same > glyph, so that information is lost when text gets printed (but > that's more of a Unicode stupidism.) > >Obviously, the justification for it is that it eliminates ", ', r", >r', """, and ''' from the syntax, replacing them by a single 'x' that >suffices for everything. Makes the code easier to read (only one >visual element), easier to parse, and easier to write, because you >don't need to decide which literal method to use. IMO a special use case does not justify complicating ordinary usage, but can be justified as a special syntax variant if it stays out of the way and provides otherwise unavailable capability. As others have pointed out, you couldn't just switch to Mandis Quotes as a complete replacement, since it would break existing programs. But you could prefix e.g. and 'm' for a special syntax a lot like mine ;-) m'x'Bill's House'x' Quoting "arbitrary" text also involves the issue of encoding, which is something I hadn't thought through when I proposed my syntax. E.g., what happens when you paste arbitrary text of possibly different encoding between some delimiters? Do you depend on the editor's (if you are using an editor, not programmatically concatenating text from various sources) ability to call for encoding transformations from clipboard content to its current encoding? Does that lose information if the current encoding is not unicode? It's a long discussion, involving what byte sequences really mean in the various representations involved (in source files, memory, screen presentations, etc.), and which are transient escaped byte representations and which are abstract text entities. Another time ... ;-) Regards, Bengt Richter From rtilley at vt.edu Sat Oct 16 22:52:58 2004 From: rtilley at vt.edu (Brad Tilley) Date: Sat, 16 Oct 2004 22:52:58 -0400 Subject: See when process exits in Windows XP Message-ID: I've tested this function out and it works well... it'll loop until ntbackup.exe has exited and then the script goes on to rename the backup.bkf file and copy it to a file server. Having _never_ done this before I thought it'd be wise to run this by comp.lang.python. I know it's a simple and stupid way in which to monitor a process, but it works for me... is it safe to do this? I don't want to get too complex. Thanks, Brad def wait_for_ntbackup_to_exit(procname): while True: try: pids = win32pdhutil.FindPerformanceAttributesByName(procname) if len(pids) > 0: print pids print len(pids) print "ntbackup is running... waiting for it to exit." continue except: return From klaus_neuner82 at yahoo.de Tue Oct 5 04:57:10 2004 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 5 Oct 2004 01:57:10 -0700 Subject: re bug Message-ID: <3e96ebd7.0410050057.29a15174@posting.google.com> Hello, it seems that there is a bug in the re module. Below there is a sample program that illustrates it.(Sorry for its length. I was not able to write a simpler regex that produced the same effect.) The regex rx compiles. It can be used to search the strings str1 and str2. Yet, when used with str3, the program will not terminate for days. I had already had this problem some months ago in another program. I had the program run for several days. In the end, the regex search terminated and returned the right result. As I could avoid regular expressions of the kind that led to the problem, I did avoid them. At the time being, I can neither avoid these regular expressions, nor can I afford to wait days for the result of my program. And, even if the search on str3 would terminate some day, I would still consider this behaviour a serious bug. I am searching tons of texts with regular expressions. And in tons of texts there will always be something of the type of str3. This means that my program just doesn't terminate, although it has no (home made) bug. I am REALLY reluctant to change my program, because it is very complex and it runs fine apart from the regex-search-does-not-terminate problem. But, if changing my program was the most efficient way to make the problem go away, I would do it. (I cannot afford to wait for some future version of the re module that doesn't have the problem.) Is there perhaps a way to tell Python something like "Try the search for 5 minutes. If you don't find anything, continue." Or are there any other solutions? Klaus ######################################################################### import re, sys rx = re.compile("(?:^| )(?P(?:[^/ ]*/[^/ ]*/(?:cn(?::[^/ #]+)*) )*[^/ ]*/[^/ ]*/(?:cn(?::[^: /#]+)*:2(?::[^: /#]+)*:3(?::[^: /#]+)*))(?=( |$))") str1 = "mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:2:3" test1 = rx.search(str1) if test1: print test1.group("ALLES") str2 = "//bos Innit/no/no ?/?/pun:? Mm/mm/adj:4 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:2:3 ././pun:." test2 = rx.search(str2) if test2: print test2.group("ALLES") # Part below will not terminate for days # str3 = "//bos Innit/no/no ?/?/pun:? Mm/mm/adj:4 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 mm/mm/cn:nom:akk:3 ././pun:." # test3 = rx.search(str3) # if test3: # print test3.group("ALLES") From jcarlson at uci.edu Fri Oct 22 14:34:56 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 22 Oct 2004 11:34:56 -0700 Subject: IDLE--what are your experiences with it? In-Reply-To: References: Message-ID: <20041022113155.0AE0.JCARLSON@uci.edu> Kevin Walzer wrote: > I'm looking for other peoples' viewpoints about their experiences with > IDLE as an editor--what are its good points? What are its limitations? > Any advice/insight is appreciated. It is a decent editor for a handful of files at a time. The moment you get beyond just a few documents; your taskbar becomes cluttered with entries. It also doesn't have code folding, project support, ... - Josiah From pit.grinja at gmx.de Fri Oct 1 15:55:26 2004 From: pit.grinja at gmx.de (Piet) Date: 1 Oct 2004 12:55:26 -0700 Subject: wxPython: "Nesting" wx.NoteBooks? Message-ID: <39cbe663.0410011155.1da62051@posting.google.com> Hi, I am trying to generate an "hierarchical" layout based on wx.NoteBooks. That means, every page of a Notebook should be a NoteBookon its own. Here is a (short but complicated) piece of code that I put together to see whether it works: import wx #____________________________ class MainWindow(wx.Frame): def __init__(self,parent,id,title): self.dirname='' wx.Frame.__init__(self,parent,-4, title, style=wx.DEFAULT_FRAME_STYLE) self.Notebook = wx.Notebook(self,-1,wx.DefaultPosition,wx.DefaultSize,wx.NB_TOP) self.panels = [] self.SubNoteBooks = [] for panelNumber in range(3): self.panels.append(wx.Panel(self.Notebook,-1)) self.Notebook.AddPage(self.panels[panelNumber],"Tab"+str(panelNumber))# self.SubNoteBooks.append(wx.Notebook(self.panels[panelNumber],-1,wx.DefaultPosition,wx.DefaultSize,wx.NB_TOP)) self.SubNoteBooks[panelNumber].subPanels = [] for subPanelNumber in range(3): self.SubNoteBooks[panelNumber].subPanels.append(wx.Panel(self.SubNoteBooks[panelNumber],-1)) self.SubNoteBooks[panelNumber].AddPage(self.SubNoteBooks[panelNumber].subPanels[subPanelNumber],"Subtab"+str(panelNumber)+str(subPanelNumber)) app = wx.PySimpleApp() frame = MainWindow(None, -1, "MultiTabControl") frame.Show(1) app.MainLoop() However, what I get is only the "first level", i.e. a normal NoteBook with three tabs. Is it possible to get the "second level tabs" working? Many thanks in advance Piet From michele.simionato at gmail.com Fri Oct 15 00:37:10 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Oct 2004 21:37:10 -0700 Subject: Order in metaclass References: <416cf48f.140377111@news.oz.net> <416d2af0.154298900@news.oz.net> Message-ID: <4edc17eb.0410142037.3703195c@posting.google.com> Carlos Ribeiro wrote in message news:... > On Thu, 14 Oct 2004 14:51:52 GMT, Michael Hudson wrote: > > bokr at oz.net (Bengt Richter) writes: > > > > > IIRC it was Guido himself who let the cat out of the bag about a > > > function, in some early metaclass notes. But maybe I don't RC ;-) > > > > I don't get the fuss about a function vs a class for the value of > > __metaclass__. It's a callable. It gets called. No mystery *here* > > :) > > I think it has something to do with the intended working of > metaclasses. After all, they're called meta_classes_, not > metafunctions :-) But on a more serious note: in other languages, such > as Smalltalk, metaclasses are a standard part of the language, and are > _classes_. There is a _metaclass hierarchy_, superimposed to the class > hierarchy. Metaclasses are supposed to be classes because they can be > inherited from, for example. And I believe that was only by accident, > and not by a explicit design choice, that Python's implementation > accepts any callable as a metaclass. Using a "metafunction" is a kind of abuse, yes. Nevertheless, I used this trick to resolve the metaclass conflict: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197c Later on, I also found a way to avoid the usage of the meta-function, but it was too brain-exploder to publish ;-) Michele Simionato From reinhold-birkenfeld-nospam at wolke7.net Sat Oct 30 10:02:43 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Oct 2004 16:02:43 +0200 Subject: What is Python's answer to Perl 6? In-Reply-To: <1099144064.931829.257240@z14g2000cwz.googlegroups.com> References: <2uh4j7F2a86uqU1@uni-berlin.de> <1099144064.931829.257240@z14g2000cwz.googlegroups.com> Message-ID: <2uhl84F2ahviqU1@uni-berlin.de> Jonathan Ellis wrote: > A.M. Kuchling wrote: >> The list of features for Python 3000 is described in PEP 3000, >> appropriately enough: >> >> http://www.python.org/peps/pep-3000.html >> >> Most of the suggested changes remove redundancy, such as removing >> now-unneeded built-in functions and language features. > > I'm sure this has been brought up before, but a quick google search > didn't find anything on moving [has|get|set]attr into attributes of > object. Why wouldn't this be considered a Good Thing? Just because > Ruby people would like it? :) You can take this step even further: The builtin functions (that aren't doomed for py3k) can be classified in those groups: A. Constructors for built-in types basestring, bool, complex, dict, file, float, int, list, long, object, str, slice, tuple, type These cannot be made attributes of some object. B. Functions that can be attributed to some class or module abs, divmod, round, pow -> math ord -> str In consequence: [uni]chr -> int hex, oct -> int super, *attr, isinstance, issubclass -> object hash -> sys? C. Functions that could be made attributes of lists/sequences max, min, len, enumerate, sum But that would require to implement them for all sequence types or implement a common basetype 'seq'. D. Other functions I cannot attribute to a class eval globals, locals, vars iter property classmethod, staticmethod cmp [x]range repr __import__ Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From steven.bethard at gmail.com Mon Oct 11 01:58:03 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 11 Oct 2004 05:58:03 +0000 (UTC) Subject: difference between class statement and def statement (WAS Re: End of file) References: <6a13a506.0410062329.5de9e695@posting.google.com> <1glatop.p9hsopf3b9m4N%aleaxit@yahoo.com> <2sucjlF1p5plpU1@uni-berlin.de> <416a09c4.4267802054@news.oz.net> <59e9fd3a0410102158179dac9e@mail.gmail.com> Message-ID: Andrew Durdin gmail.com> writes: > Another [sort-of related] question: why does the following not produce > a NameError for "foo"? > > def foo(): print foo > foo() I'm thinking this was meant to be "left as an exercise to the reader" ;), but just in case it wasn't, you've exactly illustrated the difference between a class definition statement and a function definition statement. Executing a class definition statement executes the class block, while executing a function definition statement only initializes the function object, without actually executing the code in the function's block. Hence: >>> class C(object): ... print C ... Traceback (most recent call last): File "", line 1, in ? File "", line 2, in C NameError: name 'C' is not defined The name of a class is bound to the class object at the end of the execution of a class statment. Since executing a class statement executes the code in the class's block, this example references C before it has been bound to the class object, hence the NameError. >>> def f(): ... print f ... >>> f() The name of a function is bound to the function object when the def statement is executed. However, the function's code block is not executed until f is called, at which point the name f has already been bound to the function object and is thus available from the globals. Steve From mhoward at mahoward.com Tue Oct 5 10:38:09 2004 From: mhoward at mahoward.com (Mike Howard) Date: 5 Oct 2004 07:38:09 -0700 Subject: Problem with string parsing Message-ID: <948b993a.0410050638.3a0340ec@posting.google.com> If I do this: string.lstrip('1_mature_dt=10-May-2002','1_mature_dt=') I get: '0-May-2002' Which I did not expect string.lstrip('1_mature_dt=20-May-2002','1_mature_dt=') I get '20-May-2002' Which I expected string.lstrip('1_mature_dt=01-Jun-2003','1_mature_dt=') I get '01-Jun-2003' Which I expected Is this a bug or am I doing something wrong? From heikowu at ceosg.de Sun Oct 24 12:57:29 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 24 Oct 2004 18:57:29 +0200 Subject: Passing an event handler through a list In-Reply-To: References: Message-ID: <200410241857.29378.heikowu@ceosg.de> Am Sonntag, 24. Oktober 2004 18:20 schrieb StvB: > In main.py, I add an event handler to a list: > [snip] > > In GUI_Function.py, > --------------------- > from wxPython.wx import * > def AddItemsToSizer(self, sizer, panel, evtHandlerList ): > [snip] Try this, and read up on parameter passing (and also read up on what *evtHandlerList means... Heiko. From ofnap at nus.edu.sg Tue Oct 5 14:29:59 2004 From: ofnap at nus.edu.sg (Ajith Prasad) Date: 5 Oct 2004 11:29:59 -0700 Subject: Cross-tabulation module in Python Message-ID: <37ee60c8.0410051029.1cd88083@posting.google.com> Anyone knows of a reference to a statistical cross-tabulation module in Python? Thanks in advance. From pit.grinja at gmx.de Sun Oct 3 12:51:59 2004 From: pit.grinja at gmx.de (Piet) Date: 3 Oct 2004 09:51:59 -0700 Subject: wxPython: "Nesting" wx.NoteBooks? References: <39cbe663.0410011155.1da62051@posting.google.com> <88e23673.0410022250.4f8a2933@posting.google.com> Message-ID: <39cbe663.0410030851.276b37f@posting.google.com> jcarlson at uci.edu (Josiah Carlson) wrote in message news:<88e23673.0410022250.4f8a2933 at posting.google.com>... > > However, what I get is only the "first level", i.e. a normal NoteBook > > with three tabs. Is it possible to get the "second level tabs" > > working? > > Though it is ugly, yes, it can be done. Nearly anything can be done > with wxPython, you just need to structure it correctly. > > import wx > #____________________________ > > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > self.dirname='' > wx.Frame.__init__(self,parent,-4, title, > style=wx.DEFAULT_FRAME_STYLE) > self.Notebook = > wx.Notebook(self,-1,wx.DefaultPosition,wx.DefaultSize,wx.NB_TOP) > self.SubNoteBooks = [] > > for subnotebook in xrange(3): > self.SubNoteBooks.append(wx.Notebook(self.Notebook, -1)) > self.Notebook.AddPage(self.SubNoteBooks[-1], > 'Tab %i'%subnotebook) > for i in xrange(3): > self.SubNoteBooks[-1].AddPage(wx.Panel( > self.SubNoteBooks[-1], -1), > 'SubTab %i %i'%(subnotebook,i)) > > app = wx.PySimpleApp() > frame = MainWindow(None, -1, "MultiTabControl") > frame.Show(1) > app.MainLoop() Thanks, Josiah. It took me some time to figure out how to put something on a notebook panel (i.e. in which order the wx.Notebook and the panel have to be created and which is the child of what), so leaving out the panel for the "1st level notebooks" would habe probably the last thing I would have tried. Piet From macrocosm at fastmail.fm Wed Oct 6 16:11:00 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Wed, 06 Oct 2004 16:11:00 -0400 Subject: Python Macros In-Reply-To: <10m8gqrtj31kndc@corp.supernews.com> References: <41618797$0$69737$ed2619ec@ptn-nntp-reader01.plus.net> <416190BE.6080802@fastmail.fm> <10m8gqrtj31kndc@corp.supernews.com> Message-ID: <41645154.5020306@fastmail.fm> Jeff Shannon wrote: > Arich Chanachai wrote: > >> > > >>> You mean some refinement of this sort of thing: >>> >>> class X(object): >>> a = "lives in X" >>> def __getattr__(self, name): >>> return getattr(U,name) >>> class U(object): >>> b = "lives in Y" >>> x = X() >>> print x.a >>> print x.b >>> >>> ? >>> >> >> >> Sure, but what if I dynamically (at runtime) extend X to include >> variable b. Will it then print X.b or still U.b? > > > > In this case, as I understand it, adding an attribute b to either x > (the instance) or X (the class) will cause x.b to resolve to the new > attribute, and *not* to U.b -- attributes are dynamically looked up > each time they are used, and __getattr__() is called only when the > standard lookup methods (instance, class, superclass, ...) fail. > Jeff Shannon > Technician/Programmer > Credit International > Cool. This seems then to have the same functionality as ObjC messages. I am beginning to like Python more and more. From clifford.wells at comcast.net Wed Oct 13 08:24:27 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Wed, 13 Oct 2004 05:24:27 -0700 Subject: locks In-Reply-To: References: Message-ID: <1097670267.12092.70.camel@devilbox.devilnet.internal> On Wed, 2004-10-13 at 14:11 +0200, Diez B. Roggisch wrote: > Ajay wrote: > > > what would happen if i try to access a variable locked by another thread? > > i am not trying to obtain a lock on it, just trying to access it. > > If you first tell us haw you actually lock a variable, we then might be able > to tell you what happens if you access it.... > > And in general: python has the PIL - Python Interpreter Lock - that I think you mean the GIL (Global Interpreter Lock). PIL is the excellent Python Imaging Library. > "brutally" serializes (hopefully) all accesses to python data-structures - Nope. It doesn't do this. For access to items such as integers you are probably fine, but for things like lists, dictionaries, class attributes, etc, you're on your own. The GIL only ensures that two threads won't be executing Python bytecode simultaneously. It locks the Python *interpreter*, not your program or data structures. > so e.g. running several threads, appending to the same list, won't result > in messing up the internal list structure causing segfaults or the like. True, you won't get segfaults. However, you may very well get a traceback or mangled data. > That makes programming pretty easy, at the cost of lots of waiting for the > individual threads. Threading in Python is pretty easy, but certainly not *that* easy. And just to be certain, importing PIL won't help you here either . Regards, Cliff -- Cliff Wells From fumanchu at amor.org Sun Oct 10 23:52:13 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 10 Oct 2004 20:52:13 -0700 Subject: help explaining default function arg weirdness Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3022F58@exchange.hqamor.amorhq.net> John M. Gabriele wrote: > This is almost straight out of the Python tutorial, > section 4.7.1 > > ------------------------code --------------------- > #!/usr/bin/python > > def func( append_this, default_list=[] ): > default_list.append( append_this ) > return default_list > > print func( "foo" ) > print func( "bar" ) > print func( "baz" ) > ------------------------/code----------------- > > And running it gives me this: > > ['foo'] > ['foo', 'bar'] > ['foo', 'bar', 'baz'] > > which looks wrong to me. The explanation in the tutorial > says "The default value is evaluated only once. This makes a > difference when the default is a mutable object such as a > list, dictionary, or instances of most classes." > > I don't get it: isn't default_list a local to func()? The name is. The value, however, is just another spot on the heap. > Doesn't it get created/destroyed with each call to func() > so we'd get a fresh empty one with each function call? Nope. > What's the rationale for having the function remember > default_list across calls? http://www.python.org/doc/faq/general.html#why-are-default-values-shared -between-objects The setting of default values is performed when the function is defined (only once), not when it is called (each time). Robert Brewer MIS Amor Ministries fumanchu at amor.org From Doran_Dermot at emc.com Mon Oct 25 07:47:12 2004 From: Doran_Dermot at emc.com (Doran_Dermot at emc.com) Date: Mon, 25 Oct 2004 12:47:12 +0100 Subject: Implementing class attribute access methods via pseudo-functi on o verloading. Message-ID: <97B6410BE753D411894E00D0B77E6F7F018DCCFE@neam2mx1.isus.emc.com> Hi Daniel, The "return" statement will do just that! Nothing gets executed after the return and therefore the else is not required. However, this does suggest that this code is not clear to others! That in itself is worth noting! I agree that the manner in which I was trying to simulate "function overloading" might also be unclear! Thanks for the reaction. -----Original Message----- From: python-list-bounces+doran_dermot=emc.com at python.org [mailto:python-list-bounces+doran_dermot=emc.com at python.org]On Behalf Of Daniel Dittmar Sent: 25 October 2004 12:13 To: python-list at python.org Subject: Re: Implementing class attribute access methods via pseudo-function o verloading. Doran_Dermot at emc.com wrote: > def title( self, title=None ): > if title == None: > return self._title > self._title = title You probably meant def title( self, title=None ): if title == None: return self._title else: self._title = title or every read access would clear the attribute. 1. Some people dislike methods that do very different things depending on the parameters. These are difficult to explain. Though in your case, one central explanation and links from all the methods should be enough. 2. None is often a useful value, so perhaps you should use a module local variable like _GetValue (actual value is irrelevant) def title (self, title = _GetValue): Daniel -- http://mail.python.org/mailman/listinfo/python-list From kdombrowski at gmail.com Fri Oct 29 00:03:11 2004 From: kdombrowski at gmail.com (Kenneth Dombrowski) Date: Fri, 29 Oct 2004 04:03:11 GMT Subject: Open Source License Question In-Reply-To: References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <97-dnSRAYPEwPuLcRVn-rA@rogers.com> Message-ID: <4181C21F.6080106@gmail.com> Hi, I was just browsing the group as a newbie to python, and I would hate to be thought (or be baited by) a FOSS licensing troll with my first post, so I apologize if these issues have been gone over already; in fact several people have said that they have, but I am compelled to reply to this thread: Peter Hansen wrote: > Dan Perl wrote: > >> Michael, I have one comment in-line (see below), but other than that I >> can only say that I chose GPL for my own project. It may discourage >> use of my code for commercial purposes !?? I can only assume you're referring to the restriction that authors of non-free software can't link to your libraries With your code under the GPL, anybody can use your code for commercial purposes, or any other purposes. Anybody can sell it, anybody can link to it and sell the derivative work, with the provision that in that case they use the GPL for that derivitave work > > This seems like an appropriate post to which to attach a reference > to a nice article contrasting the GPL and the Mozilla Public License > (MPL): http://croftsoft.com/library/tutorials/gplmpl/ > > Summary of that essay, in the words of its author: This is a very misleading article to point someone to. in the words of its author: "The GPL prevents code from being sold by itself or as part of a larger work." This is thoroughly false. There is no restriction on selling GPLed software; from the FSF GNU GPL FAQ: http://www.gnu.org/licenses/gpl-faq.html#TOCDoesTheGPLAllowMoney "Does the GPL allow me to sell copies of the program for money? Yes, the GPL allows everyone to do this. The right to sell copies is part of the definition of free software. Except in one special situation, there is no limit on what price you can charge. (The one exception is the required written offer to provide source code that must accompany binary-only release.)" He continues, "However, it leaves the door open for the authors to commercially sell the code under different licensing terms if they so choose. For example, this can easily occur: 1. a single author may initially release code as GPL; 2. the author later decides that the code has commercial viability; 3. the author stops distributing the code with the GPL. 4. the author then reissues the exact same code with a fee-based license. What does this mean? It means that the GPL is a nice hedge for an author or organization who wants to reserve the exclusive right to commercially sell the software at some future point without competition." This argument is expanded on in some detail; but relies on two misinterpretations of the GPL: 1. An author is certainly free to sell his/her code while it is under the GPL. As is anyone else, there simply is no "right to sell the code exclusively" in the GPL, see above. 2. As the copyright holder, I believe the author is certainly free to change his/her license with a future release -- regardless of whether the code had changed. But even if all reference to the GPL were removed from the future release, that would not revoke earlier releases' GPL licenses; anyone who cared to could fork a GPL release and continue development provided they used the GPL license. Thus the GPL achieves the one thing the author of this article attributes as the benefit of the MPL: a free market incentive to keep software free. His next argument is with the "viral" nature of the GPL, but his first point supporting the argument is not true: "First, it prevents the use of code released under other Open Source licenses, with the exception of Public Domain, from being used in combination to create a larger work. For example, suppose that you have located a third of the source code components that you need for your project under the GPL, another third under the X consortium/MIT style licenses, and the final third as Public Domain. Problem solved? No, you will either have to rewrite the GPL or the X consortium/MIT components as GPL will not co-exist with the other." From the top of http://www.gnu.org/philosophy/license-list.html: "We classify a license according to certain key questions: * Whether it qualifies as a free software license. * Whether it is a copyleft license. * Whether it is compatible with the GNU GPL. (This means you can combine a module which was released under that license with a GPL-covered module to make one larger program.)" In fact his X11/MIT example is listed as compatible with the GPL on that page; I can't say whether this has changed since 1999, when this article was written, but it is clearly wrong today. Last he complains that the GPL effectively creates a gulf between proprietary developers and FOSS developers... this certainly was an issue for a lot people in 1999, but I don't consider it important enough anymore to bore the list further btw, I am a big fan of Mozilla, & had never bothered to read up on their license. I see a version 1.1 (which presumably came out since that article was written) can, under certain conditions be compatible with the GPL -- at least according to the FSF: http://www.gnu.org/philosophy/license-list.html#TOCGPLIncompatibleLicenses "MPL 1.1 has a provision (section 13) that allows a program (or parts of it) to offer a choice of another license as well. If part of a program allows the GNU GPL as an alternate choice, or any other GPL-compatible license as an alternate choice, that part of the program has a GPL-compatible license." I certainly don't believe that the GPL is best for everyone, and if your main issue with the GPL is its viral nature, the MPL looks like it may be a good alternative, after the LGPL & X11 licenses of course, IANAL TINLA etc... Kenneth From __peter__ at web.de Thu Oct 28 09:43:14 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Oct 2004 15:43:14 +0200 Subject: logging question References: Message-ID: Neal D. Becker wrote: > Why isn't my formatter used when I use DatagramHandler? I'd say your formatting efforts happen on the wrong end of the connection. What is actually sent are LogRecord objects, not formatted messages. This gives you more flexibility, as you can add as many handlers (possibly with different formatters) as you may wish. Below is a modification of your "server" along these lines: #!/usr/bin/env python import socket import logging import pickle sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) sock.bind (("", 8881)) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger = logging.getLogger("fromFarAway") logger.addHandler(handler) try: while True: data, address = sock.recvfrom(8192) rec = logging.makeLogRecord(pickle.loads(data[4:])) logger.handle(rec) finally: sock.close() Whether there is a way to automatically replicate a logger hierarchy I don't know. Peter From ny_r_marquez at yahoo.com Thu Oct 7 15:47:44 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 7 Oct 2004 12:47:44 -0700 Subject: 2.3.4 windows installer References: Message-ID: <8a27e309.0410071147.6153ee16@posting.google.com> Brad Tilley wrote in message > changed manually at install, but that's a pain when you have > dozens/hundreds of machines. When you have "dozens/hundreds of machines" in Windows you will be better off having some kind of Application deployment mechanism such as SMS (not that I am promoting that particular one). Those tools will allow you to create a wrapper installation package whith which you can automate the way the original setup program is run. You can then push this installation packages at will or simply allow the users to pull them in as desired. From gohadbhai at rediffmail.com Thu Oct 21 03:05:20 2004 From: gohadbhai at rediffmail.com (Sandeep Avinash Gohad) Date: 21 Oct 2004 07:05:20 -0000 Subject: how to reading binary data... Message-ID: <20041021070520.2594.qmail@webmail25.rediffmail.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- ? Hello I opened any particular file with the 'rb' mode that is read binary mode. so python will treat the data as a raw data. now i want to read first 4 bytes only then i will convert the first 4 bytes into long datatype and then again read 4 bytes and will do the same. But how to set & move the pointer using loop? also how to convert into long? Regards Sandeep From deetsNOSPAM at web.de Fri Oct 29 06:18:20 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 29 Oct 2004 12:18:20 +0200 Subject: Multiple XML-RPC calls over the same connection? References: Message-ID: <2uekatF286019U1@uni-berlin.de> The Fumigator wrote: > Hi. > > I want to be able to create a persistent connection between an XML-RPC > client and server... i.e. I want to be able to login once, carry > out a number of calls and then logout rather than send login info > every call. > Is there a way to do this with the xml-rpc code in the standard library? Not to my knowlegde - and the reason is not python, but the primitiveness of xmlrpc. It simply doesn't allow for connection state to be associated. What I do is to create handles, and pass these around - that at least limits and sort of normalizes the api usage: proxy = xmlrpclib.Server('http://localhost:7080/') ak = proxy.authenticate(user, password) print proxy.some_method(ak, argument) If you want stateful connection, use better IPC-standards, as CORBA - its way more advanced. SOAP gets attention lately, but its similarily limited as xmlrpc, and while session state associoated with soap connections is possible sometimes, its not standarized.... -- Regards, Diez B. Roggisch From carribeiro at gmail.com Tue Oct 5 18:37:10 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 5 Oct 2004 19:37:10 -0300 Subject: Python in Process Control? In-Reply-To: References: Message-ID: <864d37090410051537477555f3@mail.gmail.com> On Tue, 05 Oct 2004 21:51:31 GMT, Andrea Griffini wrote: > On Tue, 5 Oct 2004 12:12:39 -0300, Carlos Ribeiro > wrote: > >Keeping with the same reasoning line, why don't the engineers that > >work in the company take more responsibility? Because they were never > >in such a position. They don't have a choice. They have to keep things > >running, period. The one who messes up with stuff is fired. And doing > >development is not their company business, anyway. Want to do it? Go > >working for a vendor. > > Well... in our case we have customers that didn't probably > see an engineer in past 10 years. Still they can buy and use > rather hi-tech machines from us that cost several tens of > thousands of dollars. It doesn't come as a surprise to me they > don't want to take the responsibility for them being functional. I was afraid that my experience would not reflect the state of the art elsewhere. Seems it wasn't any far from truth :-) > A sad part is that sometimes our customer support has to > spend time to explain people what does it mean to copy a file > from a floppy disk to a certain directory; but I've to say > that the users that create more troubles are actually the > "expert" ones. I would actually refuse to provide any support > to anyone relinking my application with a newer versions of > a library... you really wanna do it ? You're welcome, but > don't call me if something doesn't work and you've something > urgent to do with the system... unless you really like being > insulted over the phone. Luckily this doesn't happen often... > It's much more common (and a bit annoying) to see someone > fearing updates... When the market finally awakes from the stone age, you'll surely start to get more calls like this. Not only from people relinking, but patches, and *real* bug tickets found by your very customers. Get used to it. You can't complain this way once the market is open. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From ianb at colorstudy.com Fri Oct 22 12:17:00 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 22 Oct 2004 11:17:00 -0500 Subject: Python vs PHP In-Reply-To: <1098460034.4596.1.camel@devilbox.devilnet.internal> References: <41790054$0$203$edfadb0f@dread12.news.tele.dk> <1098460034.4596.1.camel@devilbox.devilnet.internal> Message-ID: <4179327C.4030409@colorstudy.com> Cliff Wells wrote: >>Have you tried PageTemplates from Zope? >> >>They are very clever, and the macros makes it much better at reusing >>code than anything I have seen elsewhere. > > > Can they be used outside of Zope? One of my criteria was usability > Yep, I use them regularly. zpt.sf.net has a somewhat out of date distribution (it still works fine though), and simpletal is another implementation. There's even a Perl implementation (PETAL). At some point the Zope people are going to make a fully up-to-date release of that package (without the rest of Zope), but they are mostly stuck on the packaging issues (the dependencies have already been worked out; it doesn't depend on the rest of Zope). -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From adalke at mindspring.com Sun Oct 3 02:56:43 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 03 Oct 2004 06:56:43 GMT Subject: WeakValueDictionary In-Reply-To: References: Message-ID: Bryan wrote: > i have another question about weak references. how do you know that b > is dead? > > > >>> a = A() > >>> b = weakref.ref(a) > >>> b > > >>> del a > >>> b > Quoting from the weakref PEP at http://www.python.org/peps/pep-0205.html A weak reference object will allow access to the referenced object if it hasn't been collected and to determine if the object still exists in memory. Retrieving the referent is done by calling the reference object. If the referent is no longer alive, this will return None instead. >>> class Spam: ... def hello(self): print "Hello!" ... >>> a = Spam() >>> b = weakref.ref(a) >>> b().hello() Hello! >>> del a >>> b().hello() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'hello' >>> b() >>> b() is None True >>> Andrew dalke at dalkescientific.com From adurdin at gmail.com Tue Oct 12 19:30:03 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 13 Oct 2004 10:30:03 +1100 Subject: Reading struct with structs In-Reply-To: <453D335C35136F4B8163C281D58BBD882DCA6B@NBNUNYCEXCH1.nesbittburns.ca> References: <453D335C35136F4B8163C281D58BBD882DCA6B@NBNUNYCEXCH1.nesbittburns.ca> Message-ID: <59e9fd3a04101216307167ae7a@mail.gmail.com> On Tue, 12 Oct 2004 17:27:29 -0400, Baillargeon, Sonny wrote: > > The custom structs are arbitrary. The struct module only allows me to > have strict C datatypes. How can I read in a struct recursively given I > have to feed the struct.unpack? Here's one idea. Suppose we have the following structs: struct foo { int x; int y; }; struct bar { int a; struct foo; } If we've read in len(struct bar) bytes into a string s: # This Thing is only for this example; presumably you'll be wanting # to read the data into some other class instances. class Thing(object): pass bar = Thing() bar.foo = Thing() (bar.a, bar.foo.x, bar.foo.y) = struct.unpack("iii", s) From s917124 at mail.yzu.edu.tw Thu Oct 7 13:53:35 2004 From: s917124 at mail.yzu.edu.tw (mike) Date: 7 Oct 2004 10:53:35 -0700 Subject: hi...about HTMLparser Message-ID: <761727b3.0410070953.44f66d23@posting.google.com> regards: (1)could I use HTMLparser to delete some element and the element's content from a file? (2)Is there a good document about how I can use the HTMLparser? thank you best wishes From martin at v.loewis.de Sat Oct 2 05:42:35 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 02 Oct 2004 11:42:35 +0200 Subject: should these be fixed for python 2.4? In-Reply-To: References: <415d9229$0$18966$9b622d9e@news.freenet.de> Message-ID: <415e7803$0$9581$9b622d9e@news.freenet.de> Alexander Schmolck wrote: > OK, but let me say that this is *not* obvious -- it is difficult to find in > the docs (I don't really want to spawn anything and it's burried amongst a > zillion cryptically named similar functions with a complex interface) and > difficult to use. I fail to see the last point. What you proposed is equally difficult to use. And yes, you do want to spawn a new process. > So I think many (most?) people will use os.system instead and in a way that is > broken. If changing system is a bad idea, how about introducing a convenience > function or adding a note to the os.system docs? Adding notes to documentation is always possible. I don't see the point of adding a convenience function, because os.spawn* is already there. Regards, Martin From fabio_listasdiscussao at yahoo.com.br Thu Oct 28 15:39:30 2004 From: fabio_listasdiscussao at yahoo.com.br (Fabio) Date: Thu, 28 Oct 2004 16:39:30 -0300 (ART) Subject: newbie: pygtk (win, slack10) In-Reply-To: Message-ID: <20041028193930.66724.qmail@web54001.mail.yahoo.com> thank you!! I found another cool link, hosted in a 'brazilian' site, but not in 'portugUese' :) http://www.async.com.br/faq/pygtk/index.py?req=index thats it.. thank you guys! --- Dave Cook escreveu: > In article > , > Pierre N > wrote: > > > Should be enough for a while :-)) > > If I could speak Brazilian as well as you speak > English, I would be > > sooo happy... > > See > > http://pygtk.org > > for the tutorial and reference. > > If you want to run on windows, download and install > the gladewin package: > > http://gladewin32.sourceforge.net/ > > as well as the pygtk package for win32: > > http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ > > If you have questions, there is a significant cabal > of Portuguese > speaking pygtk developers that hang out on gimpnet's > #pygtk IRC channel. > > http://www.xach.com/gimpnet/ > > Dave Cook > -- > http://mail.python.org/mailman/listinfo/python-list > _______________________________________________________ Yahoo! Acesso Gr?tis - Internet r?pida e gr?tis. Instale o discador agora! http://br.acesso.yahoo.com/ From macrocosm at fastmail.fm Fri Oct 8 14:28:55 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Fri, 08 Oct 2004 14:28:55 -0400 Subject: wxPython toot In-Reply-To: <20041008110316.ED97.JCARLSON@uci.edu> References: <4166C6C9.7030501@comcast.net> <30B8EFDA-1952-11D9-8C02-0003939C968C@unito.it> <20041008110316.ED97.JCARLSON@uci.edu> Message-ID: <4166DC67.1030304@fastmail.fm> Josiah Carlson wrote: >>Hi to all >>can anyone point me to a wxpython tutorial (something like the Intro to >>tkinter by Lundh)? >> >> > >I don't know if there is such a good resource, but I find just looking >through the wxPython demo to be very educational. > > - Josiah > > > I imagine that wxpython mailing-list would better serve you for such questions. From aleaxit at yahoo.com Tue Oct 26 02:47:08 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 26 Oct 2004 08:47:08 +0200 Subject: int/long unification hides bugs References: <940ee3e8.0410250456.65445bbd@posting.google.com> <1gm8jkc.7gtvc31avo0xhN%aleaxit@yahoo.com> <940ee3e8.0410252025.34e671d9@posting.google.com> Message-ID: <1gm98e3.ewsm1jxg9y3tN%aleaxit@yahoo.com> kartik wrote: ... > integers are used in different ways from strings. i may expect file Integers are used in a huge variety of ways, and so are strings. > paths to be around 100 characters, and if i get a 500-character path, > i have no problem just because of the length. but if a person's age is > 500 where i expect it to be less than 100, then **definitely** > something's wrong. Try doing some accounting in Turkish liras, one of these days. Today, each Euro is 189782957 cents of Turkish liras. If an Italian firm selling (say) woodcutting equipment bids on a pretty modest contract in Turkey, offering machinery worth 2375220 Euros, they need to easily compute that their bid is 450776275125540 cents of Turkisk Liras. And that's a _pretty modest_ contract, again -- if you're doing some computation about truly substantial sums (e.g. ones connected to government budgets) the numbers get way larger. [[and yes, integer numbers of some fraction of a currency, typically cents, are a good and practical way to do accounting -- nix floating point, be it binary or decimal]]. Sure, Turkey will rebase its currency in 2005 -- but who can predict when some other country's currency will similarly debase. Even just for accounting, unlimited-size integers are simply much more practical. > as another example, using too long a string as an index into a > dictionary is not a problem (true, the dictionary may not have a > mapping, but i have the same issue with a short string). but too long > an index into a list rewards me with an exception. But the same index, used as a dictionary key, works just fine. Specious argument, therefore. > as i look at my code, i rarely have an issue with string sizes, but if > an integer variable gets very large (say > 2**31 or 2**63), it > generally reflects a bug in my code. This may be peculiar to the kind of code you write -- if you hit more bugs whose symptom is a large integer than ones whose symptom is a large string, you're probably generating fewer strings than integers. But many other people's code have the opposite character, and it's quite presumptous of you to suggest changing Python without considering that. > i suggest u base your comments on real code, rather than reasoning in > an abstract manner from your ivory tower. I suggest you take your blinkers off, and look at all ways integers are commonly used in all sorts of computations, rather than imagining your personal code is the end of the world. As common and everyday a computation (in some fields) as the factorial of 1000 (number of permutations of 1000 objects) is 2**8530 -- and combinatorial arithmetic is anything but an "ivory tower" pursuit these days, and factorial is the simplest building block in combinatorial arithmetic. If you need objects with constraints, build them as custom types. Subclass int, str, whatever, to accept bounds or other checkers in their constructors (or as compiletime constants, whatever), convert the result of each operation to the same type, and raise as soon as an instance is constructed that's out of bounds. It's not a difficult exercise, and if you design and apply your constraints well it may help you catch some categories of bugs sooner than without such constraints. Once you have convincing use cases and experience to show that this kind of thing is more useful than previously noticed, _then_ you may stand a chance to have some kind of optional limit-checking subtypes rolled into Python's core/standard library. So far, you have nothing of the kind. Alex From clifford.wells at comcast.net Wed Oct 13 10:20:46 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Wed, 13 Oct 2004 07:20:46 -0700 Subject: locks In-Reply-To: References: Message-ID: <1097677246.12092.152.camel@devilbox.devilnet.internal> On Wed, 2004-10-13 at 16:10 +0200, Diez B. Roggisch wrote: > > Okay, to clarify, for the most part I *was* in fact referring to "higher > > level issues". I doubt tracebacks or mangled data would occur simply > > due to the operation's being non-atomic. However, if you have code that > > say, checks for an item's existence in a list and then appends it if it > > isn't there, it may cause the program to fail if another thread adds > > that item between the time of the check and the time of the append. > > This is what I was referring to by potential for mangled data and/or > > tracebacks. > > _That_ of course I'm very well aware of - but to my expirience, with several > dozen threads appending to one list I never encountered a interpreter > failure. That is in contrast to java, where you get an > "ConcurrentModificationException" unless you don't ask specifically for a > synchronized variant of the collection of yours. Have you looked at the Queue module? It was explicitly designed for this sort of thing and removes all doubt about thread-safety. Regards, Cliff -- Cliff Wells From j at jochem.{N0SP4M}.tv Mon Oct 4 03:08:01 2004 From: j at jochem.{N0SP4M}.tv (Berends) Date: Mon, 04 Oct 2004 09:08:01 +0200 Subject: detecting socket in use on localhost Message-ID: I am looking for some code to detect whether or not there is already a listener to a socket (tcp or udp) on the localhost. I am writing some software that can be run multiple times on a localhost and each will instantiate a listener in a range of ports. I have checked several resources (Cookbook, Python Network Programming (Goerzen), Programming Python(Lutz)) but cannot find the crux. Anyone care to point me to some nice methods? ciao Jochem From peter at engcorp.com Tue Oct 12 20:22:52 2004 From: peter at engcorp.com (Peter L Hansen) Date: Tue, 12 Oct 2004 20:22:52 -0400 Subject: How to: get list of modules in a package In-Reply-To: References: <4OudnSEQhLvFyfbcRVn-pg@rogers.com> Message-ID: Mike C. Fletcher wrote: > referring to Peter's comment that he'd not seen anyone produce modules > 'from "thin air"', rather than to whether this could be solved in the > general case. I was backing him up in his assertion that there's no > *general* way to solve the problem, rather than attempting to contradict > him :) (those Canucks get dangerous when contradicted). ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ No they don't! -Peter P.S.: See you at the PyGTA meeting in two weeks, Mike... From michele.simionato at gmail.com Fri Oct 15 03:19:32 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Oct 2004 00:19:32 -0700 Subject: ANN: PySourceColor 1.7 References: <18282ecb.0410141705.4fb6de25@posting.google.com> Message-ID: <4edc17eb.0410142319.289a980c@posting.google.com> mefjr75 at hotmail.com (M.E.Farmer) wrote in message news:<18282ecb.0410141705.4fb6de25 at posting.google.com>... > Hello all, > This version of PySourceColor supports decorators. > It looks like the syntax is there for a while, so I decided add them > in. > They parser code has also been extended to seperate all 12 types of > string. > I rewrote the _Null colorscheme to actually be null format. > Changed the old _Null to _Mono a black and white colorscheme for > printing. > Also added a few utility functions. > If you don't like the builtin colorschemes you should be able to write > a colorscheme that looks exactly like you want. > This is something that would be nice to have built into pydoc. > The links at the top-right of a pydoc page could point to a colorized > source and a plain text version :) > This program should run with Python 2.0 -> 2.4. > The code can be any version. > Just save to a file and run it. > It will parse itself into 6 diffrent webpages and show them. Hey, this is pretty cool! However the long lines where cut in the posted message and I had to fix them by hand (those are the rare situations where I would lke Python was not an indentation-sensitive language :-(). I also replaced "MyDir" with "tmp" which looks as a sensible default, at least on Unices. Good work, Michele Simionato From aleaxit at yahoo.com Tue Oct 5 03:34:32 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 5 Oct 2004 09:34:32 +0200 Subject: New to Python: Features References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> Message-ID: <1gl6e9j.1cn88p21wfi6s0N%aleaxit@yahoo.com> Andrew Dalke wrote: ... > Like I said with eval, DO NOT USE THIS! It almost certainly > means you're doing the wrong thing. It's full of security > holes and there are nearly always better ways to solve > the underlying problem. Applause and full agreement. > > I know but that's a real bummer. No way around that? > > Python is not a functional programming language. > > Do you want it because it's cool or because it's useful? I'd bet a decorator to munge a function or method (by bytecode hacking) into lean tail-call won't be long emerging. My use case for this was the nightmare of 'recursion limits exceeded' for a nevow page with a few hundred deferreds -- they got (implicitly, by the framework) chained to each other by tail call (for termination purposes), and besides the orrid waste of time in building all those frames for nothing, the exception-within-an-exception was hell to debug. There are workarounds, of course, but being able to code the obvious solution directly would be useful. > Python doesn't support Smalltalk's system image. That's > probably a good thing. I was very used to workspaces back in the days of APL and I still miss them. Why is it good not to have them? > > I'd like to be able to use a string as an integer without an explicit > > coerion on my part for example. > > NO! Don't do that. Bad code. Subtle errors. > > Try Perl or Ruby instead. Not Ruby! That's a _good_ language: kallisti:~/cb/cha/tex/cba alex$ ruby 2+"23" -:1:in `+': String can't be coerced into Fixnum (TypeError) from -:1 to perpetrate such horrors, he definitely wants Perl. > > That is quite a shame, no modules for this either huh? > > It quite depends on your expectations of what design by > contract, protocols, etc. means. Do some research. Hint: > Google for 'python "design by contract"' and related topics. 'python protocols' and/or adaptation is quite a different (but related) tack also worth googling for. > >>> 43. Embedding variables in strings like: print "Hello, World. Time: > >>> #{Time.now}" > >> > >> t = time.asctime() > >> print "Hello World %(t)s"%{'t':t} > >> print "Hello World %(t)s"%locals() > > > > That is messy, exactly why I wanted the kind of clear embedding I gave > > an example for. Oh well. > > You asked for "embedding variables" not embedding expressions. > You got what you asked for, not what you wanted. That's part > of being able to ask the right question. Remember that essay > people suggested you read? Well, in 2.4 w/string.Template he does get variables specifically (with nicer syntax), but if the '%(...)s' syntax ain't too messy for him interpolating expressions is still possible (maybe not _wise_...): >>> class map: ... def __getitem__(self,name): return eval(name) ... >>> print 'hello world at %(time.asctime())s' % map() hello world at Tue Oct 5 09:22:52 2004 Not sure what docs (besides Python Cookbook and Python in a Nutshell) one would have to read to find this answer -- differently from most other questions he's asking, this one's hardly obvious from docs... > > Really? Hmmmm, does anyone know of a bridge between Python and Ruby? > > Why not just use Ruby? It seems to fit your search criteria > much better. I agree with you that it does, though not as well as you appear to believe (e.g. no `` 2 + "23" '' abominations in Ruby, either). Perl might be better still for what he's asking -- said abomination does work, he gets to mess with syntax (google for lingua latina perligata), and so forth. Alex From bokr at oz.net Sat Oct 30 02:07:23 2004 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Oct 2004 06:07:23 GMT Subject: "number-in-base" ``oneliner'' References: <1gmfz0k.a3xefz1xzms61N%aleaxit@yahoo.com> Message-ID: <41832f8b.1140475326@news.oz.net> On Fri, 29 Oct 2004 23:58:47 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >I hesitate a bit to post this, but... on the Italian Python NG, somebody >was asking whether there was any way to convert an integer number x into >a string which represents it in an arbitrary base N (given a sequence >with a len of N that gives the digits to use) as "a single expression". > >I haven't found a really general way, much less a clear one, but, the >best I have so far is...: > >def number_in_base(x, N, digits, maxlen=99): > return '-'[x>=0:] + ( > (x and ''.join([digits[k%N] for i in range(maxlen) > for k in [abs(x)//N**i] if k>0])[::-1] > ) or digits[0]) > >Besides the lack of clarity, the obvious defect of this approach is that >darned 'maxlen' parameter -- but then, since I can have only a 'for', >not a 'while', in a list comprehension or generator expression, and I >don't think recursion qualifies as 'a single expression'...:-( > >Anyway, improvements and suggestions welcome, thanks! > Maybe something useful in this? Not very tested (and not terribly clear either ;-) >>> def number_in_base(x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter( ... lambda qr=[abs(x),0]:qr[0] and ( ... qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]) ... , 0)][::-1]) ... >>> number_in_base( 126 ,2,'0123456789ABCDEF') '1111110' >>> number_in_base( 126 ,8,'0123456789ABCDEF') '176' >>> number_in_base( 126 ,16,'0123456789ABCDEF') '7E' >>> number_in_base( 1 ,16,'0123456789ABCDEF') '1' >>> number_in_base( 0 ,16,'0123456789ABCDEF') '0' >>> number_in_base(-126 ,16,'0123456789ABCDEF') '-7E' >>> number_in_base(-126 ,2,'0123456789ABCDEF') '-1111110' Even less tested, and using a list subtype with overridden next to do the same: >>> def number_in_base(x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in type('',(list,),{ ... '__iter__':lambda s:s, 'next':lambda s:( ... s[0] is 0 and iter([]).next() or ... s.__setslice__(0,2,divmod(s[0],N)) or digits[s[1]]) ... })([abs(x),0])][::-1]) ... >>> number_in_base(-126, 8, '01234567') '-176' >>> number_in_base(-126, 2, '01') '-1111110' >>> number_in_base(126, 2, '01') '1111110' >>> number_in_base( 0 , 2, '01') '0' >>> number_in_base( 1 , 2, '01') '1' ;-) Regards, Bengt Richter From just at xs4all.nl Fri Oct 29 03:38:20 2004 From: just at xs4all.nl (Just) Date: Fri, 29 Oct 2004 09:38:20 +0200 Subject: ctypes 0.9.2 released References: <1gmeuqj.1p0mkh41y1zvfcN%aleaxit@yahoo.com> Message-ID: In article <1gmeuqj.1p0mkh41y1zvfcN%aleaxit at yahoo.com>, aleaxit at yahoo.com (Alex Martelli) wrote: > Ganesan R wrote: > ... > > That aside, I am wondering if it isn't time to push ctypes for inclusion > > into the standard Python distribution. Too late for Python 2.4, but how > > about Python 2.5? > > Seconded! Python 2.5 should be mostly about standard-library > enhancements, and ctypes would be a huge enhancement to Python's stdlib. In general, Guido is very reluctant to accept thing which make is easy to cause segfaults. I predict you'll have a very hard time convincing him... Just From noone at here.com Sun Oct 3 15:52:29 2004 From: noone at here.com (M. Clift) Date: Sun, 3 Oct 2004 20:52:29 +0100 Subject: append to items depending on prior item References: Message-ID: Hi Peter, Thankyou. You have been really helpful, I appreciate it. Malcolm From aleaxit at yahoo.com Mon Oct 4 03:14:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 4 Oct 2004 09:14:29 +0200 Subject: append to items depending on prior item References: Message-ID: <1gl4jhm.1phvdnik1aiefN%aleaxit@yahoo.com> M. Clift wrote: ... > What I want to do is append to each item an extra value depending on the > previous item. > > Too keen to get help, what I should have written is; > > What I want to do is append to each item an extra value depending on the > previous item and itself. So, you mean the key is not just the previous, but the pair (previous,item)? OK, not necessarily a big difference...: you can either use the pairs as keys, or make a nested dictionary. > Alex gave me this; > > def weird_appender(sequence): > choices = dict({None: 'abc'}, item1='abc', item2='def') Change this to something like: # what if there IS no 'previous item', i.e., the first time, or for # all those cases which are not explicititly in the dictionary...: first_time_choices = {'item1': 'abc', 'item2': 'def', } # general case choices = { None: first_time_choices, 'item1': {'item1': 'blu', 'item2': 'ghi', }, 'item2': {'item1': 'jkm', 'item2': 'nop', }, } > previous = None > for item in sequence: > yield item+random.choice(choices.get(previous, choices[None])) > previous = item and here, access the nested dicts -- clearer when done less concisely, in separate steps rather than all inline: d = choices.get(previous, first_time_choices) choose = d.get(item, ['']) yield item + random.choice(choose) previous = item > print weird_appender(sequence) this is misaligned -- remove leading space, I don't know how it got there (it definitely wasn't there in my post!!!). The 'p' of print must align with the 'd' of 'def weird...'. The print is done after the function weird_appender is done being defined, most definitely *NOT* as part of the 'for' loop in said function's body...!!! > > What I want to do is append to an item, but rather than just getting this > value based on the previous choice > I'd like to say if previous item is 'item1a' and the current item is item2 Ah, you want to key on the previous _output_ item rather than the previous _input_ one? OK, then further alter in the latest snippet the last two statements to be instead: previous = item + random.choice(choose) yield previous > append some choice. or else if the current item is > item3 append a diferent choice. If you LIKE to say if/else if, there's nothing stopping you from saying it. I think the dictionary accesses are clearer, but changing them into a few nested if/elif/else trees is hardly difficult - it just (IMHO) worsens the code's quality, that's all. > Now, I know none of you are on my payroll (and I have been asking for help a > lot), but if that is easy to impliment I would be grateful > if someone could show me how. However, if it isn't so easy to do, is the > previous code Alex gave me along the right lines for my new requirement? If your requirement is now correctly expressed and divined, yes. If you gave us the true requirement (what application problem are you actually trying to solve) rather than asking for advice on how to implement one design you appear to have already chosen, we might be on a sounder basis in making such statements, of course. > So that if I go away and change / add to it myself I might eventually get it > to work. If not, could someone point me in the direction I should look > at other than a dictionary method. I see it as a sort of multiplication > lookup table i.e. previous items already appended are looked for along the > x axis, the current item unappended is on the y axis, reading along from > both gives the value to append to the current item. Right, the nested dictionaries give you something akin to a 2-d array, except that each axis is indexed by string rather than by number. Again, this contrasts with your assertion in this very post that you'd LIKE to say "if" and "else" -- the dictionaries are there exactly in order to _avoid_ the rich nesting of 'if/elif/else' trees, moving some complexity from code to "data tables". > Thanks for putting up with me, No problem, really. Alex From sean0601 at pchome.com.tw Fri Oct 15 02:34:16 2004 From: sean0601 at pchome.com.tw (Sean) Date: 14 Oct 2004 23:34:16 -0700 Subject: pythondoc or epydoc? References: Message-ID: <684bd072.0410142234.35ee0c85@posting.google.com> I would like to use epydoc to generate documents, but got the following error. C:\PROJECT>\python23\python \python23\scripts\epydoc.py --debug test1.py Importing 1 modules. [1/1] Importing test1.py Building API documentation for 1 modules. [1/1] Building docs for test1 Building docs for test1 Building docs for test1.main Building docs for test1.MyApp Traceback (most recent call last): File "\python23\scripts\epydoc.py", line 17, in ? cli() File "C:\Python23\lib\site-packages\epydoc\cli.py", line 110, in cli docmap = _make_docmap(modules, options) File "C:\Python23\lib\site-packages\epydoc\cli.py", line 483, in _make_docmap try: d.add(module) File "C:\Python23\lib\site-packages\epydoc\objdoc.py", line 2954, in add self._add(objID) File "C:\Python23\lib\site-packages\epydoc\objdoc.py", line 2968, in _add self._add(link.target()) File "C:\Python23\lib\site-packages\epydoc\objdoc.py", line 2961, in _add self.add_one(objID) File "C:\Python23\lib\site-packages\epydoc\objdoc.py", line 2900, in add_one self.data[objID] = ClassDoc(objID, self._verbosity) File "C:\Python23\lib\site-packages\epydoc\objdoc.py", line 1589, in __init__ self._base_order = [make_uid(b) for b in base_order] File "C:\Python23\lib\site-packages\epydoc\uid.py", line 781, in make_uid uid = ObjectUID(object) File "C:\Python23\lib\site-packages\epydoc\uid.py", line 418, in __init__ name = self._findname() File "C:\Python23\lib\site-packages\epydoc\uid.py", line 509, in _findname return '%s.%s' % (self.module(), objname) File "C:\Python23\lib\site-packages\epydoc\uid.py", line 585, in module if (self._module is not None and File "C:\Python23\Lib\site-packages\wx\misc.py", line 3581, in __eq__ return _misc.DateTime___eq__(*args) TypeError: Expected a pointer The version of wxpython is 2.5. This script can be executed normally. How could I solve the problem? Regards, Sean From bokr at oz.net Sun Oct 17 17:50:19 2004 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Oct 2004 21:50:19 GMT Subject: acting on items passed to a method via a dictiomary References: <1glsuhc.10eukauy09rs8N%aleaxit@yahoo.com> Message-ID: <4172e878.73704100@news.oz.net> On Sun, 17 Oct 2004 19:33:32 +0200, "Diez B. Roggisch" wrote: >> However, there are no problems whatsoever with the issue you remark on, >> as long as the method never alters the 'items' object. As long as only >> nonmutating methods get called on 'items', i.e., 'items' is practically >> treated as "read-only", Donnal Walter's approach is just fine. The >> issue you remark on does deserve to be made, but it's also important to >> understand when it does matter and when it doesn't. > >You are right of course, but the high frequency of postings regarding >"strange default value behaviour" made me want to make this point before >Donnal steps into that pitfall. And while the example at hand didn't alter >the contents of items, I'd nevertheless settled for items=None and used >something like this: > >def foo(items=None): > if not items is None: > .... I like to use the idiom def foo(items=None): if items is None: items = {} # or whatever non-shared mutable ... Regards, Bengt Richter From fumanchu at amor.org Tue Oct 19 12:50:42 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 19 Oct 2004 09:50:42 -0700 Subject: itertools candidate: warehouse() Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3244FDF@exchange.hqamor.amorhq.net> Peter Otten wrote: > Robert Brewer wrote: > > def warehouse(stock, factory=None): > > Most of the building blocks for the warehouse() are already > there, but you didn't use them, oddly enough. Oddly enough, tee isn't in my version (2.3.2) of Python except as an example. ;) Thanks for the exhaustive discussion below. > So here comes a variant written in terms of current (2.4) itertools: > > >>> from itertools import * > >>> def peek(iterable): > ... a, b = tee(iterable) > ... try: > ... return a, b.next() > ... except StopIteration: > ... raise ValueError("cannot peek into an empty iterable") > ... > >>> iterable = iter("abc") > >>> iterable, first = peek(iterable) > >>> factory = first.__class__ > >>> data = range(10) > >>> for a, b in izip(data, chain(iterable, starmap(factory, > repeat(())))): > ... print a, repr(b) > ... > 0 'a' > 1 'b' > 2 'c' > 3 '' > 4 '' > 5 '' > 6 '' > 7 '' > 8 '' > 9 '' [snip] > So now you can do > > chain(iterable, repeatfunc(factory)) > > after putting a copy of these recipes into your > site-packages. Why aren't they already there, btw? I'm not sure which particular recipes you mean (peek?). But in general, I don't write scripts for my own limited use; I'm writing frameworks, which shouldn't depend upon little recipes scattered hither and yon. :/ > The only extra your warehouse() has to offer is the (last) > item's class as the default factory for the padding items. > I don't think that is needed often enough to warrant the > inclusion in the itertools. Understood. I think Raymond is right; at most, it should be a Cookbook entry. Actually, the big "extra" I see with warehouse() is wrapping up all of the iteration cruft(combined with the return of the inner iterator to the caller, who can then clean up any remaining items). Having seen your alternative, I can see it basically comes down to readability for me; I find warehouse() to be a nice packaging of a common idiom for my apps. I'm the only programmer here at my organization; sometimes I just need a "guy down the hall" to keep me in line. :) Thanks for doing that. Robert Brewer MIS Amor Ministries fumanchu at amor.org From rff_rff at remove-yahoo.it Fri Oct 1 16:40:48 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Fri, 01 Oct 2004 20:40:48 GMT Subject: Exception feature creep! (was: re-entering in the normal flow after an exception is raised) In-Reply-To: <4b39d922.0410011152.31fb1dae@posting.google.com> References: <4b39d922.0410011152.31fb1dae@posting.google.com> Message-ID: Lonnie Princehouse ha scritto: > In a recent post, Michele Simionato asked about resumable (or > re-entrant) exceptions, the basic idea being that when raised and > uncaught, these exceptions would only propagate backwards through a > limited number of frames before being implicitly ignored. I don't understand: why resumable exceptions should be ignored after they propagate for a limited number of frames? the only idea of resumable exceptions I have is that they allow you to , well, resume excution from the point they were raised. From limodou at gmail.com Fri Oct 8 03:02:30 2004 From: limodou at gmail.com (limodou) Date: Fri, 8 Oct 2004 15:02:30 +0800 Subject: ANN:NewEdit 2.8 released Message-ID: <505f13c04100800026c8c2f3b@mail.gmail.com> The new version 2.8 NewEdit is released! You can download it from : source: http://wiki.woodpecker.org.cn/moin.cgi/NewEdit?action=AttachFile&do=get&target=newedit_2.8r1.zip windows installer: http://wiki.woodpecker.org.cn/moin.cgi/NewEdit?action=AttachFile&do=get&target=NewEdit2.8.exe What's new? New Features: 1. When searching in regular expression, you can replace in regular expression 2. Inputing Chinese Charactors in Shell window and Message window 3. Auto completion, Auto calltip 4. Dispaly free memory in statusbar in Windows platform 5. Directly output text to HTML view window 6. User definced hotkey 7. Modification: [skip] There are two unresolving prombles in Windows Installer that: 1. DDE invalidation 2. Plugin wxPythonDocument and PythonDoc path error, the path is not the Python installation directory, but NewEdit installation directory, so if you want to use them, please correct the path yourself. The document is written in Chinese, so if you have any question, please me email. project homepage: http://newedit.tigris.org -- I like python! From danperl at rogers.com Wed Oct 6 18:43:49 2004 From: danperl at rogers.com (Dan Perl) Date: Wed, 6 Oct 2004 18:43:49 -0400 Subject: difficult zipefile Question References: Message-ID: I may be wrong, and I may have to eat my words later, but I think that the zip file format does not handle empty folders. I tried it myself with winzip just a few days ago. I think that zip only keeps a list of files with their path so the folder will not be stored in the zip file if there is no file in that folder. Like I already said, I may be wrong, but I would recommend that you use tarfile instead. Dan "matthiasjanes" wrote in message news:d588131f.0410061437.4ecda4bf at posting.google.com... > hello all, > > i want to zip a folder plus the files and subfolders. > > which works something like that: > > #sample code > > import os, zipfile > > def zipit(path, ziper): > > for root, dirs, files in os.walk(path): > > for anyFile in files: > > fullname = os.path.join(root, anyFile) > > if __name__ == '__main__': > > ziper = zipfile.ZipFile('test.zip', 'w') > zipit('somefolderTozip', ziper) > ziper.close() > #____________________________ > > > this works fine as long as there is no empty subfolder. > > can anyone tell me - or better give me a small example of code how to > add an empty folder to the zip archive. > > thanks mr. janes From emanuel.landeholm at telia.com Fri Oct 29 06:54:03 2004 From: emanuel.landeholm at telia.com (Emanuel Landeholm) Date: Fri, 29 Oct 2004 10:54:03 GMT Subject: C API q Message-ID: Hello! I'm a Py neophyte trying to code an extension module in C. I would like to know how, canonically, to remove a certain PyObject from a PyList, from C. The solution I have come up with so far involves iterating through the PyList keeping a counter, and then using PyList_DelItem(counter) on the counter when the iter item == the PyObject. But this is kind of messy. I'm sure there's a cleaner way to do it? TIA, Emanuel From loritsch at gmail.com Sat Oct 16 20:32:05 2004 From: loritsch at gmail.com (Michael Loritsch) Date: 16 Oct 2004 17:32:05 -0700 Subject: windows services References: Message-ID: Francis Lavoie wrote in message news:... > Is it possible to restart windows services? (remotely and locally) > > Because I have a little script that retreive the LastWaitTimeout key of > the automatic update, delete that key if it out schedule for our > production needs. But still the service need to be restarded if I want > that key to be reset, when Win Update will resynchronize with the sus > server for new update. > > Thankx Since this is a windows specific question, you must have the windows extensions installed. I'm assuming you either already have them, or know where to get them, as that is a different question entirely... The python module that you need to perform this task is win32service. In order to restart a service, you should do two things: 1) Tell the service control manager (SCM) to stop the service 2) Then tell the SCM to start the service. Thus, the pseudocode to restart a service is as follows: 1) Obtain a handle to the SCM -> use win32service.OpenSCManager 2) Obtain a handle the service you wish to stop -> use win32service.OpenService 3) Tell the service to stop -> use win32service.ControlService with the proper control code for stopping a service. 4) Start the service -> use win32service.StartService Regards, Michael Loritsch From jeff at ccvcorp.com Mon Oct 11 16:51:00 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 11 Oct 2004 13:51:00 -0700 Subject: I sing the praises of lambda, my friend and savior! In-Reply-To: References: <2qtl0oF139gn6U1@uni-berlin.de> <10mli0vohrtf8b6@corp.supernews.com> <10mllq67t1qah3b@corp.supernews.com> Message-ID: <10mlsct69hmtgca@corp.supernews.com> gabriele renzi wrote: > > then what you want is a better lambda. One where you can use return, > maybe, and where you can have statements and multiple expressions. > Don't throw away the baby with the bathwater. But because of Python's line- and indentation-based syntax, doing all of that on a single line is... um... awkward at best, to put it mildly. And once you make a lambda multiline, then you lose most of the point of it -- at least, as far as I understand what the point is (having an in-line, anonymous callable). Once you allow statements and multiple expressions, all you're gaining is anonymity, which seems like a pretty paltry benefit to me. >> That's a lot of special treatment for those cases where there >> actually might be a slight advantage to using an anonymous function, >> and "Special cases aren't special enough to break the rules." >> Lambdas *do* break many of Python's usual rules. >> > > Just because you're thinking of lambdas as special cases. Whenever a > case is very useful it is possible to break the rules. That's why > there are all those funny literals. I agree that, if a case is *very* useful, it is possible to break the rules. List comprehensions, for example, break some of the rules, but they are indeed very useful, so the rule-breakage is more forgiveable. Maybe I'm just ignorant or behind the times, but I still haven't seen a real argument as to *why* lambdas are so useful. There's some assertions about how avoiding giving something a name makes things clearer, which I disagree with. ('Explicit is better than implicit.' I don't see how 'no name' makes the purpose of a code segment clearer than 'some meaningfully descriptive name', no matter how many times it's asserted.) There's complaints that it takes a whole two extra lines to type a proper function def, as opposed to being able to use lambdas inline... but again, I'd claim that with a properly named function, the intent at point-of-use will be quite clear and the cost of two extra lines of code is minimal. (I also tend to break complex expressions into multiple steps to increase clarity -- packing as much as possible into a single line doesn't strike me as all that desirable.) There's complaints about polluting the namespace... but ISTM that it's not *that* hard to come up with uniquely descriptive names. Lambdas may once have had some utility in capturing and tinkering with the scoping of names, but that became moot with the introduction of nested scopes 'way back when. I understand that lambdas are very popular in other programming languages (such as Lisp). But Python is not those languages, and which constructs are useful may well be different. I don't know enough Lisp to judge how helpful lambdas are there; I do know enough Python to believe that I should be able to see the advantages if they were as wonderful as their proponents say. My suspicion is that all of the Python users who like lambdas originally discovered them in other languages and are comfortable with them from that environment, but those who have no previous exposure to lambdas tend to be unimpressed (at best) by Python's take on them. This renders them, IMO, in the same category as the ternary operator that's continually proposed by converts from, say, C/C++ -- a feature whose usability is much greater in other languages than in Python, and whose inclusion would only satisfy those familiar with the feature from those other languages. The only difference between the two features, IMO, is that someone managed to talk Guido into including lambdas (which he reportedly regrets), and nobody managed to talk him into including the ternary operator. Jeff Shannon Technician/Programmer Credit International From whwang at autotradecenter.com Mon Oct 11 14:31:51 2004 From: whwang at autotradecenter.com (w) Date: 11 Oct 2004 11:31:51 -0700 Subject: a question to run a Python program using PMW Message-ID: <68b8ad51.0410111031.507a3f35@posting.google.com> I am new to Python and I am trying to run an old program. I do not know what version this old program was running back in 2001 ( I know it was run successfully). I got the source codes from the office and I downloaded Python 2.3 and Pmw 1.2. when ran the program I got the following message Traceback (most recent call last): File "BidderUI.py", line 12, in ? import os.path, string, Pmw File "C:\Python23\Pmw\__init__.py", line 35, in ? __import__(_loader) ImportError: No module named Pmw_1_2.lib.PmwLoader I did create Pmw.py by running bunddlepmw.py. I also find PmwLoader.py under the PMW_1_2/lib directory. Does anyone know how to fix this? did I miss any steps ? Thanks W From Mark.English at liffe.com Tue Oct 5 07:18:15 2004 From: Mark.English at liffe.com (Mark English) Date: Tue, 5 Oct 2004 12:18:15 +0100 Subject: [OT] New to Python: Features Message-ID: <40E605146701DE428FAF21286A97D3091744C6@wphexa02.corp.lh.int> Ignore those unhelpful comments you've seen. You're obviously just here to learn and learn you shall. > Hi, I'm new to Python and I'd like to know if Python has the > following > support: *please answer to each individually, thanks* I'm relatively new myself but just this second a large C++ program is building and sucking up most of my CPU so I'll try to answer some of these intriguingly well thought out questions while it does so. My knowledge is a little sketchy but I'm sure others on the list will clarify my many mistakes. Apologies for the length of this post. Actually, apologies for this post. > 1. Multi line comments No. There are no comments in Python. > 2. Functions as variables: > a. functions can be stored in variables, passed as arguments to > other functions, and returned as results. Confusingly Python programmers use snake names when talking about programming languages. Conversely, when talking about functions in Python people are actually refering to an endangered species of blue-winged penguin. > 3. Function nesting with proper lexical scope (i.e. closures) The penguins do nest, yes. > 4. Operator overloading (inc. the ability to define new > operators) You can't define more than 5 new operators. After this it was decided you'd really be going too far with this whole O-O thing, leading to a quite different meaning for "overloading" in Python. Python programmers like to be different ;) 5. Can I do this? print("Hello " .. "World") --> > Hello World You just did it ! In Python you can do anything. Join us. 6. Constructors In Python these are called "Buildy Things". 7. "Chunks": as in a code block > contained within a string, file, or > delimited by some sort of notation (such as brackets) which can be > passed to and from functions, stored in objects, with the option of > local scoping of variables declared within it. Code is actually contained in special "envelopes" fed into Python-engineered devices built into the back of most computers these days. Hand-crafted code in Python is literally just that. > 8. "Repeat-Until" as in : > repeat > line = os.read() > until line ~= "" > print(line) Yes but this invokes the special Python boolean syntax where false is "bored" and true is "interesting". You'll see a lot of "repeat until bored" code in Python. > 9. Generic for loops where " for i=1,f(x) do print(i) end" > would print i > only once. No. "for" loops are branded with a tiny icon embedded in the "f". > 10. Can I call an object's method as object:method(arg) and have that > translate into object.method(object, arg) Yes but the object is actually a sub-object belonging to the object type which is itself an instance of class object. What you need to do is: object.type(object).method(object, arg(object, bored)).arg.object.call(instance=object.method, arg=arg, method=whatever, time=invented_by_Swiss). > 11. Can I make dynamic statements and nature like with eval() > in Javascript? There's a lot of nature in Python. Most programmers prefer a pastoral setting although some are hardy sea-faring folk. You should therefore intersperse any documentation with thoughts about your garden, when to harvest your crops, when the tide is likely to come in this evening, etc. Also many Python programmers consider "eval" to be evil because of that one letter difference. It's all in the semiotics. 12. Can I make calls to a function with a varying number of arguments? See 5. But then re-read 2. 13. Named arguments They're all named by repetitions of spam, where argument 1 is "spam", argument 2 is "spamspam" and so on. 14. Tables with built-in methods for manipulation such as sort, etc. Python doesn't use tables. Ever. 15. Table filters See 14. 15. Proper Tail Call (otherwise known as Proper > Tail Recursion) That's two 15's. Is this a form of duplicit recursion ? 16. The ability to call a function without > brackets You're kidding, right. Right ? Without brackets ? That's... that's just not possible is it ? 17. Is the Python interpreter a JIT? Does it have a > bytecode? Is it as > fast as Java? Python is generally 2000 to 3000 times faster than Java if you run Java on a toaster and Python on a super-cooled space computer orbiting Saturn. > 18. The ability to modify the import/require functionality > (how modules > can be loaded) "Modules" are the envelopes code comes in. See 7. Sorry, my compilation has finished. Hope that helps... ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From fuzzyman at gmail.com Fri Oct 15 08:08:34 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 15 Oct 2004 05:08:34 -0700 Subject: Recycle Bin and Python Message-ID: <6f402501.0410150408.165c95c4@posting.google.com> How do I move files into the windoze recycle bin from python ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From peter at engcorp.com Fri Oct 8 10:17:59 2004 From: peter at engcorp.com (Peter L Hansen) Date: Fri, 08 Oct 2004 10:17:59 -0400 Subject: literal hex value to bin file. In-Reply-To: <6e07b825.0410072051.5504e4f2@posting.google.com> References: <6e07b825.0410070125.5b3e47a3@posting.google.com> <6e07b825.0410072051.5504e4f2@posting.google.com> Message-ID: yaipa h. wrote: > I seemed to have worked it out. The bit of code below will write the > actual > hex string literal to a binary file as is. What I kept getting was > the hexascii representation of the hex string, so that '9' would write > to file as 0x39 and 'a' would write to the file as 0x61. What I wanted > was '9' to write to the file as 0x09 and '7f' to write out as 0x7f. > > #----------------------------------------------- > import struct > > a = struct.pack('B', int('ff', 16)) > > fh = open("a.hex", "wb") > fh.write(a) > fh.close() > #----------------------------------------------- > # results in the binary file 'a.hex' containing, > 0xff # only Yep, you've got it. As Paul suggests, chr() works nicely for a single byte though. Also investigate the binascii module, specifically the hexlify() and unhexlify() methods, which work nicely on entire strings of 2-digit hex values: >>> import binascii >>> binascii.unhexlify('097f') '\t\x7f' >>> chr(9) + chr(0x7f) '\t\x7f' >>> struct.pack('BB', int('09', 16), 0x7f) '\t\x7f' All of those are of course the same... depends on your needs. (Note that the output is the repr() value of the string, which in this case contains an ASCII 9 and 7F, thus the \t or TAB escape sequence followed by the hex escape sequence representation of the 7F byte. Sometimes the fact that the interactive interpreter always does a repr() on the output of expressions can be confusing.) -Peter From donn at u.washington.edu Tue Oct 19 12:43:18 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 19 Oct 2004 09:43:18 -0700 Subject: Kerberos authentication w/ Python on Windows References: Message-ID: In article , Brian Beck wrote: > After a bit of searching I haven't been able to find a definite resource > for Kerberos authentication from Python. Any help would be appreciated. The only thing I know out there - ftp://www.python.org/pub/www.python.org/ftp/python/contrib-09-Dec-1999/Sy stem/krb5module-0.1.tar.gz Written by Fred Drake and Roger Masse for CNRI, it's not very recent but that's probably the least of your problems. It does have some preprocessor conditionals as though they were building it on Windows at some point. > Here's what I've found... ... > [2] The best I could find in Zope appears to just get its result from > the UNIX/Linux krb5 command, which does all the heavy lifting. This is > not available on Windows. That krb5 command does not sound like anything I have ever seen. It isn't "available" on UNIX either, it's just something that you have to get and probably build (I guess - I've never heard of external Kerberos authentication, sounds like a bad idea to me.) > [3] http://pygss.sourceforge.net/ > I can't really tell if this is what I'm looking for. It does > provide a way to interface with MIT's krb5, but it must be obtained > separately and compiled... Well, naturally. I don't know this software, but by the name evidently it's a GSSAPI interface. Conventional wisdom has it that applications should use GSSAPI for Kerberos 5 authentication. It actually doesn't have complete, end-to-end coverage for the problem area, so commonly you end up needing to call the underlying krb5 library anyway for some miscellaneous functions, and honestly it's a verbose, awkward mess to program to, but you get a more reliable application out of it if you're doing things like data encryption on top of the minimal authentication function. And I understand that at some level it may be compatible with a protocol that Microsoft Windows' native Kerberos 5 implementation uses. I don't know much about any special issues that you might be facing on Microsoft Windows, but all this is fairly simple on UNIX and I know MS made Kerberos5 integral to Windows authentication, so what could go wrong? Donn Cave, donn at u.washington.edu From bryanjugglercryptographer at yahoo.com Fri Oct 1 21:24:03 2004 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: 1 Oct 2004 18:24:03 -0700 Subject: Close a socket externally In-Reply-To: References: <1096673569.579558.114260@k26g2000oda.googlegroups.com> Message-ID: <1096680243.955122.263530@h37g2000oda.googlegroups.com> The method I like is to compute a deadline for all the action on the socket, then compute a new timeout for each blocking operation. The following isn't tested, or even compiled, but it shows the idea: deadline = time.time() + hard_limit_on_the_time while stuff_to_do: timeout = deadline - time.time() if timeout < 0: break # time limit expired (readable, _, _) = select.select([mysock], [], [], timeout) if ! readable: break # time limit expired # at this point mysock has data available (barring weird things) -- --Bryan From aleaxit at yahoo.com Sun Oct 24 04:26:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 24 Oct 2004 10:26:28 +0200 Subject: simple recursion help References: <1gm4uqv.nmgjbj1vt0spjN%aleaxit@yahoo.com> <8ef9bea6.0410231916.450f67d@posting.google.com> Message-ID: <1gm5ojm.10239ef1m2hnrpN%aleaxit@yahoo.com> Stephen Waterbury wrote: > Hung Jung Lu wrote: > > ... The functional version would be: > > > > strings = lambda Xs, k: reduce(lambda r, i: [p + x for p in r for x > > in Xs], range(k), ['']) > > Wow! Grand prize for elegance. :) And almost for performance -- it's an order of magnitude faster than other ones I've timed. Of course, as usual, you can get another 10% or so if you avoid reduce and lambda, implementing exactly the same algorithm as: def stringo(Xs, k): r = [''] for i in range(k): r = [p+x for p in r for x in Xs] return r $ python -m timeit -s'import ov' 'ov.strings("abc",3)' 10000 loops, best of 3: 144 usec per loop $ python -m timeit -s'import ov' 'ov.strings("abc",3)' 10000 loops, best of 3: 142 usec per loop $ python -m timeit -s'import ov' 'ov.stringo("abc",3)' 10000 loops, best of 3: 126 usec per loop $ python -m timeit -s'import ov' 'ov.stringo("abc",3)' 10000 loops, best of 3: 125 usec per loop Alex From fuzzyman at gmail.com Fri Oct 22 18:02:02 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: Fri, 22 Oct 2004 23:02:02 +0100 Subject: ClientCookie problem - Difference between 'post' on the local network and the internet References: <4178F159.7060100@mxm.dk> Message-ID: <7o0jn01jn22kdmlpni3mh2oortrc66hpuv@4ax.com> On Fri, 22 Oct 2004 13:39:05 +0200, Max M wrote: >I am using ClientCookie for login on to servers and browsing them as >authenticated users. > >I kept getting "HTTP Error 400: Bad Request" errors when submitting my >forms. So I boiled it down to a simple example. > >When I try to use ClientCookie.urlopen() on my private network with ip >numbers like "http://localhost:8081/test_site/logged_in", it works fine. > >If I try to call the same site through the Internet, with a url like: >http://www.mxm.dk/test_site/logged_in I get the 400 message. But only >when using "post". 'get' works fine :-s > Are you using Version 1.0.0a ? There is a bug (well actually a bug in urllib2 - but it amoutns to the same thing) that is fixed in CVS. Either use CVS or go back to 0.4 whatever which is the latest stable version. Regards, Fuzzy >On the Internet I go out through a gateway, so my external IP is >different than my internal. > >I assume that it causes an url mismatch somewhere. With my local ip >being set in some header by urlopener, and the server expecting the >remote ip. > >But I have no idea as to how I can avoid it? Any takers? > > >######################################### > >import ClientCookie, urllib > >req = ClientCookie.Request >urlopen = ClientCookie.urlopen > >def login(came_from, login_form): > data = { > 'came_from' : came_from, > '__ac_name' : name, > '__ac_password' : password, > '__ac_persistent' : '1', > 'submit' : 'Log ind', > } > encoded_data = urllib.urlencode(data) > > request = req(login_form, encoded_data) > response = urlopen(request) > content = response.read() > return content > ># This works >came_from = 'http://localhost:8081/test_site/request_tester' >login_form = "http://localhost:8081/test_site/logged_in" >print login(came_from, login_form) > ># This results in "HTTP Error 400: Bad Request" >came_from = 'http://www.mxm.dk/test_site/request_tester' >login_form = "http://www.mxm.dk/test_site/logged_in" >print login(came_from, login_form) > > > >############################################ ># traceback from the last call to login() > >Traceback (most recent call last): > File "E:\zopes\test_site\PRODUCTS\MXMPRO~1\z.py", line 35, in ? > print login(came_from, login_form) > File "E:\zopes\test_site\PRODUCTS\MXMPRO~1\z.py", line 22, in login > response = urlopen(request) > File >"G:\uninstalled\Python\ClientCookie-1.0.0a\ClientCookie\_urllib2_support.py", >line 715, in urlopen > return _opener.open(url, data) > File >"G:\uninstalled\Python\ClientCookie-1.0.0a\ClientCookie\_Opener.py", >line 125, in open > response = meth(req, response) > File >"G:\uninstalled\Python\ClientCookie-1.0.0a\ClientCookie\_urllib2_support.py", >line 387, in http_response > response = self.parent.error( > File >"G:\uninstalled\Python\ClientCookie-1.0.0a\ClientCookie\_Opener.py", >line 189, in error > return apply(self._call_chain, args) > File "C:\pytyons\Python23\lib\urllib2.py", line 306, in _call_chain > result = func(*args) > File "C:\pytyons\Python23\lib\urllib2.py", line 412, in >http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) >urllib2.HTTPError: HTTP Error 400: Bad Request From __peter__ at web.de Thu Oct 7 06:36:37 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 07 Oct 2004 12:36:37 +0200 Subject: correct way to detect container type References: <41650CAE.704@chamonix.reportlab.co.uk> <4165178F.1080300@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > lots of good ideas, but I think this breaks in 2.1 Yes, I think it requires at least 2.2. Back to square one then... Peter From ialbert at mailblocks.com Tue Oct 12 15:17:06 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 12 Oct 2004 15:17:06 -0400 Subject: Options, ConfigParser, modules, and SQLObject connections In-Reply-To: <78cd5819.0410120624.5b67bbbe@posting.google.com> References: <78cd5819.0410120624.5b67bbbe@posting.google.com> Message-ID: Robin Munn wrote: > I'm sure others have faced similar problems before. How have you > managed? What I do in a similar situation is to set an environment variable. This environment variable points to the .ini configuration file. Then I put the configuration loading in the body of the module. That way when it gets imported for the first time it executes the instructions. --- globalconf.py --- # put whatever code you need here to # fetch the environment variable and process the file db_filename = 'database_name' --- sqldefs.py --- import globalconf import sqlobject __connection__ = sqlobject.SQLiteConnection(globalconf.db_filename) Istvan. From danperl at rogers.com Fri Oct 29 16:11:18 2004 From: danperl at rogers.com (Dan Perl) Date: Fri, 29 Oct 2004 16:11:18 -0400 Subject: Open Source License Question References: <6f402501.0410270331.6f0d5fd6@posting.google.com> <97-dnSRAYPEwPuLcRVn-rA@rogers.com> <6f402501.0410271123.5a7e68d9@posting.google.com> <2ue65gF28i9f7U1@uni-berlin.de> Message-ID: "Joachim Bowman" wrote in message news:2ue65gF28i9f7U1 at uni-berlin.de... > Hi, > > Dan Perl wrote: >> "Michael Foord" wrote in message >> news:6f402501.0410271123.5a7e68d9 at posting.google.com... >>>A lot of people use python as part of their job and are active >>>participants in teh python community. A lot of what I write are >>>library modules to do a particular job. Using the GPL means someone is >>>unable to use your work in a business setting. i don't expect other >>>people to sell products containing my work - but neither do I want to >>>prevent them from being able to use it. >> >> Fair enough. LGPL, X, or BSD should allow you to do that. > > So does the GNU GPL. Freedom/Open Source and commercial use are two > orthogonal concepts. The two don't interfere in any way. I beg to differ. Let's take a possible scenario. Let's say that my company has a complex software product that sells for $1M a piece. And let's also say that I need some encryption for the product. I find an encryption library that is free and is GPL licensed. What happens if I use it? Correct me if I'm wrong in any part (and I genuinely admit that I may be wrong). I have to release my entire product under a GPL license and I have to publish the entire code (I assume that the use of the encryption library is not isolated to only one part of the product). Would my company want to do something like that? I don't think so. Sure, we are still entitled to try to sell the product but who would pay $1M when with a little effort they can put the entire product together from the code and any support that we could sell is never going to be worth the money we are asking for? Red Hat can make money from selling their Linux distribution, but apart from companies that have deeper pockets and for whom getting the support and warranties that Red Hat offers are worth a relatively small fee, how many small consumers buy the commercial distribution when they can just download the same thing for free? No wonder that Red Hat also sells things like mugs and T-shirts. So getting back to my scenario, leaving theory and "orthogonality" aside, practical reasons will stop many companies from using GPL licensed code in a commercial product. I think that constitutes interference. Dan > You can have Free Software (under the GPL) that is used and distributed > commercially, Free Software that is used and distributed in a non > commercial way (Python), proprietary software that is used and distributed > commercially (think about MS Word), and proprietary software that is used > and distributed free of charge and without a commercial background > (sometimes called freeware). > > J From richardblackwood at cloudthunder.com Mon Oct 4 23:40:16 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Mon, 04 Oct 2004 23:40:16 -0400 Subject: New to Python: Features In-Reply-To: <1001523104100420251887d96a@mail.gmail.com> References: <416210AF.5060908@cloudthunder.com> <1001523104100420251887d96a@mail.gmail.com> Message-ID: <416217A0.5040101@cloudthunder.com> Paul Bissex wrote: >On Mon, 04 Oct 2004 23:10:39 -0400, Richard Blackwood > wrote: > > >>Hi, I'm new to Python and I'd like to know if Python has the following >>support: *please answer to each individually, thanks* >> >>1. Multi line comments >> >> >[items 2 through 45 mercifully omitted] > > >Wow. Obsessive-compulsive trolling. > > > How is that trolling? I was just wondering if Python had the features I specified. Your statement confuses me. Anyhow, any help would be great, thanks. From deetsNOSPAM at web.de Sat Oct 23 07:36:54 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 23 Oct 2004 13:36:54 +0200 Subject: Python C API Question. References: Message-ID: Adonis wrote: > This is my first crack at using Python from a C level, and also a long > time since I have even used C, so my wording might be off, when creating a > new list utilizing the PyList_New(...) function, instead of creating a > list of a fixed length, is there a way to create a variabled length > instead? AFAIK they are always variable length - they always support appending to them. The argument is just about the initial capacity, so if you know that beforehand, you can optimize allocation of list entries. -- Regards, Diez B. Roggisch From connellybarnes at yahoo.com Fri Oct 1 03:49:09 2004 From: connellybarnes at yahoo.com (C. Barnes) Date: Fri, 1 Oct 2004 00:49:09 -0700 (PDT) Subject: Manipulate HTML documents via data structure Message-ID: <20041001074909.32565.qmail@web14521.mail.yahoo.com> Python provides HTML parsing through the HTMLParser and htmllib modules. For my application, I needed to search through an HTML document in a nonlinear fashion and dynamically change parts of the document. The most logical way to do this is to translate HTML back and forth to a data structure. I wrote a module called htmldata, available from: http://oregonstate.edu/~barnesc/htmldata/ Example: >>> from htmldata import dumps, loads >>> o=loads('blahfoo') >>> o [('img', {'src':'hi.gif', 'alt':'blah'}), 'foo', ('/body', {})] >>> dumps(o) 'blahfoo' Pros: * More powerful for HTML editing. * Easy to reproduce the original document (at least, a document that is HTML-equiv to the original). Cons: * Less user friendly than HTMLParser module. I tested it on several popular sites. Feedback, bug reports, etc appreciated. - Connelly Barnes __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From macrocosm at fastmail.fm Mon Oct 4 13:54:55 2004 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Mon, 04 Oct 2004 13:54:55 -0400 Subject: Python Macros In-Reply-To: <20041004101511.FECD.JCARLSON@uci.edu> References: <41616B9B.1080009@fastmail.fm> <20041004101511.FECD.JCARLSON@uci.edu> Message-ID: <41618E6F.5030403@fastmail.fm> Josiah Carlson wrote: >>How hard/easy is it to extend the Python syntax? Perhaps there are >> >> > >Check out the tokenizer module. > > > > Is this easy to use? Are there good tutorials? >>macro facilities for this? >> >> > >Python has no macro facilities. > > > > Really? I read that Python was just like Scheme in that it had macro facilities. >>I'd like to add messages and message >>passing, for example. >> >> > >Macros are not necessary for message passing. There are at least a >dozen message passing libraries for inter and intra-machine >communications, including versions that work with DCOM, Corba, MPI, and >I'm sure just about anything else you could want to do. > >Heck, writing message passing with TCP sockets is even quite easy, if >you have experience with writing network protocols. > >If you are just wanting to pass messages in your program, and you are >using threads, use the Queue module (in 2.4 it will be faster). > > - Josiah > > > Great, thanks. From rowen at cesmail.net Wed Oct 27 13:27:07 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 27 Oct 2004 10:27:07 -0700 Subject: os.popen3 with windows; help? References: <81a41dd.0410260035.60aee489@posting.google.com> Message-ID: In article , "Patrick L. Nolan" wrote: >Lad wrote: >> "Russell E. Owen" wrote in message >> news:... >>> I'm trying to launch an application from Python 2.3 on Windows. The >>> application is "ds9" (an image viewer), and is installed in C:\Program >>> Files\ds9\ds9 >>>... >> I think the problem is in long name folder: Program Files. So, try > >> Progra~1 instead of Program Files > >An automatic way to accomplish this is > >import win32api >shortpath = win32api.GetShortPathName(path) >os.popen3(shortpath) > >Also, I have found by bitter experience that ds9 is unable to open any >file whose path includes a space. Put your data files somewhere else. Thanks to everyone for their replies. Lad and Patrick's suggestions both worked perfectly. (Simply trying to protect the path with an extra set of quotes, as suggested by one kind non-Windows-savvy soul, did not work).. I also tested the bug mentioned by Patrick. I put a fits image file into a directory whose name contained a space and tried to open that file in ds9. it worked fine. I hope this means that the problem with spaces in names has been thoroughly fixed. Tip for ds9 and xpa users (xpa is a communication protocol used by ds9): I learned from a ds9 developer that a proper installation of ds9 and should have the xpa files in the same directory as ds9. This is NOT how the binary ds9 and xpa installers do it, but it is easy to fix after the installation. Unless this is done, ds9 cannot register itself with xpa, making communication needlessly messy. One more question: - I noticed that when I use os.popen3 to open ds9, i have to keep the returned reference to stdout around as long as ds9 itself is open or Python hangs. I can't close it. I can't lose the reference and allow it to be garbage-collected. Any suggestions for avoiding this? (At least it doesn't prevent Python from shutting down when requested.) I had been using os.spawn... to launch ds9, but spawn is not supported on Windows, alas. I communicate with ds9 via xpa, so the pipes returned by popen3 are of no interest. -- Russell From adurdin at gmail.com Wed Oct 13 01:20:37 2004 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 13 Oct 2004 16:20:37 +1100 Subject: Intercept and Tag STDOUT values In-Reply-To: References: Message-ID: <59e9fd3a04101222204b7f90f6@mail.gmail.com> On Wed, 13 Oct 2004 04:06:54 GMT, Wes S. wrote: > > class cStdOutRedirect : > stdOld = sys.stdout You don't need this line -- that would try and save stdout when the class is created, not when an instance is created. > def __main__(self) : I believe you mean __init__, not __main__ (which is not a meaningful method name) > self.stdOld = sys.stdout > sys.stdout = self > return True Any return value from __init__ is never used, so there's no point having one. > def write(self,str) : It's probably not a good idea to name a variable "str", as that will override the builtin str() function. > self.stdOld.write("REDIRECTED OUTPUT: " + str) > return True The write() function is not expected to return a value, so again omit it. > def close(self) : > sys.stdout = self.stdOld > return True Ditto regarding return value for close(). With these changes, here's an example: >>> class cStdOutRedirect(object): ... def __init__(self): ... self.stdOld = sys.stdout ... sys.stdout = self ... def write(self, s): ... self.stdOld.write("REDIRECTED OUTPUT: " + s) ... def close(self): ... sys.stdout = self.stdOld ... >>> import sys >>> f = cStdOutRedirect() >>> print "Hello" REDIRECTED OUTPUT: HelloREDIRECTED OUTPUT: >>> f.close() >>> print "Hello" Hello This shows a couple of pitfalls: first, you might not want to have stdout redirected as soon as the class is instantiated. Secondly, the tag is put on every write() call, not just at the start of lines. Thirdly, this may not work nicely if you try to redirect more than once. Finally, you might need to override another few methods for better compatibility (e.g. flush()). I would also suggest renaming "close" to "end_redirect" or something, as calling f = cStdOutRedirect() sys.stdout.close() comes across strangely. From __NOSPAM at rogers.com__NOSPAM__ Mon Oct 4 09:07:31 2004 From: __NOSPAM at rogers.com__NOSPAM__ (Martin) Date: Mon, 04 Oct 2004 09:07:31 -0400 Subject: Piecemeal script interpretation via C API Message-ID: It is possible to interpret a script in chunks using C API functins? In other words, once you have called Py_CompileString and you have a PyObject for the compiled script (?), can you evaluate the object piece meal so that your program can take care of other important updates, etc? Thanks Martin From agriff at tin.it Thu Oct 7 01:59:35 2004 From: agriff at tin.it (Andrea Griffini) Date: Thu, 07 Oct 2004 05:59:35 GMT Subject: New to Python: Features References: <1gl6e9j.1cn88p21wfi6s0N%aleaxit@yahoo.com> <1gl6qcq.kcu4qi1qojaksN%aleaxit@yahoo.com> <_sB8d.3545$M05.1351@newsread3.news.pas.earthlink.net> <1gl7k7p.1a37gv1o1klclN%aleaxit@yahoo.com> <1gl97ps.endfhf1dfa6l0N%aleaxit@yahoo.com> Message-ID: <52m9m0d58mkslq7t3sg92aihchlpat714h@4ax.com> On Wed, 6 Oct 2004 21:40:11 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: >Yeah, sigh, ditto here, in theory -- then I ended up as the software >consultant for 200+ good programmers new to C++ and saw first-hand what >nightmare it was sometimes to make stuff const-correct and how little in >fact it bought you, so I got rather disillusioned about it. This is interesting; I've come to the conclusion that logical const-correctness is not worth in programming as the cost it requires is higher than the payoff it can bring back; but I was actually stared at like a martian in c.l.c++.m when I said this. I thought it was just because I'm used to work only as a team of one and probably things were different if working on big teams. Now, if I understand you correctly in the "disillusioned" part, looks like you found that the payoff is not worth even in bigger teams... Or may be you found just that adding const-correctness *later* is a suicide ? That is quite acknowledged, my opinion is instead that it's not even worth to put it in from the beginning. Unfortunately it's something you just can't refuse to do in C++ because const correctness is tied to other parts of the language and was used to try to patch problems in other philosophically unrelated areas (I'm talking about temporaries and implicit conversions). Andrea From http Thu Oct 7 19:28:31 2004 From: http (Paul Rubin) Date: 07 Oct 2004 16:28:31 -0700 Subject: Python script that generates blob files References: <1097189229.883950.253450@z14g2000cwz.googlegroups.com> Message-ID: <7xr7oa3y74.fsf@ruckus.brouhaha.com> "Sean Carey" writes: > I am wondering if anyone knows of a python script or any other script > that will generate random files with random sizes that I can specify. Python 2.4 should have an os.urandom function that gives you a random character string of a size you specify. I'm not sure if that's what you're asking. From tim.peters at gmail.com Fri Oct 8 16:03:09 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 8 Oct 2004 16:03:09 -0400 Subject: UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 10: ordinal not in range(128) In-Reply-To: <20041008194249.GB22344@unpythonic.net> References: <95c29a5e.0410071540.c27186a@posting.google.com> <95c29a5e.0410081125.18907895@posting.google.com> <20041008194249.GB22344@unpythonic.net> Message-ID: <1f7befae0410081303209996b8@mail.gmail.com> [Robin Siebler] >>> It's just a file path. It doesn't *have* any non-ASCII chars in it to >>> begin with! [Jeff Epler] >> Well, then, be sure to follow up when you find the real cause, because I >> don't know of another reason that isn't along the lines I mentioned. Robin, your original report disagrees with your belief: > if(ap == pp): > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 10: ordinal > not in range(128) 0xa0 is not an ASCII character. We can't tell from the traceback which of ap and pp is Unicode, and which isn't, but presumably your knowledge of your app will tell you. That something is "a file path" doesn't mean anything -- you're running on Windows, and Windows doesn't restrict paths to containing ASCII characters. >>> f = open('\xa0\xa0.txt', 'w') >>> f.name '\xa0\xa0.txt' >>> f.close() >>> import os >>> for fn in os.listdir('.'): ... if fn.endswith('.txt'): ... print fn b.txt bb.txt BUILDno.txt NormalizationTest-3.2.0.txt readme.txt ??.txt The last line may not show up correctly for you, since it contains non-ASCII characters. When I sent it, it looked like aa.txt but with diacritcal marks "on top of" the a's. From Moiz.Golawala at ge.com Wed Oct 27 13:07:57 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Wed, 27 Oct 2004 13:07:57 -0400 Subject: mod_python newbie question. Message-ID: Hi All, I am very new to mod_python (I have developed application with python but am new to web development in general). I have read most of the documentation and I have a couple of questions. I am planning to use mod_python along with Cheetah to build an internal website for my company. So far I have include some basic handlers in apache and can view a hello world script on my browser. Now when I try to do something a little more complicated I am lost. I have a couple of text fields that I want the user to fill out and then hit the submit button. I can get that html page up but I don't understand the mechanism where once a user hits the submit button, how does he/she get to the next page on the site. In the documentation I don't see any multi page working examples. Can some one point me to some resource that has working mult-page html (PSP or Cheetah based) examples with the necessary Directory tags in the httpd.conf file so I can better understand what is going on. Here is an some code to explain what I am trying to do and what my confusion is: In my httpd.conf file: PythonHandler main PythonDebug on in my main.py file: from cheetah.Template import Template from mod_python import apache def handler(req): t = Template(file,"/var/www/html/main.tmpl") textlen = len(str(t)) req.set_content(t) req.set_content_length(textlen) apache.OK in my main.tmpl file:
My problem is that the browser renders the page that is defined in the main.tmpl file. But once I enter the text and click submit. I want the browser to display the page that is defined the template used in valid.py (as the form tag shows) but some how I get the main.py page back. The reason this is happening is that once I click the submit button, I get back to the server and the handler is invoked and main.py is called. I can never go to another page. I am sure I am doing something wrong. Please can someone help me out.. Or direct me to some place that show an example of how this mechanism works correctly. Again, any help is appreciated. Thanks Moiz Golawala Moiz Golawala GE Infrastructure, Security Software Engineer Enterprise Solutions T 561 994 5972 F 561 994 6572 E moiz.golawala at ge.com www.gesecurity.com 791 Park of Commerce Blvd., Suite 100 Boca Raton, FL, 33487, U.S.A. GE Security, Inc. From __peter__ at web.de Thu Oct 14 04:11:37 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Oct 2004 10:11:37 +0200 Subject: Order in metaclass References: Message-ID: Carlos Ribeiro wrote: > if?not?isinstance(value,?self.mytype): > #?if?it's?a?string,?tries?to?convert?to?the?correct > #?target?type?(this?is?needed?because?most?things?read > #?from?files?will?be?strings?anyway) > if?isinstance(value,?StringType): > value?=?self.mytype(value) I haven't checked if this is relevant in the context, but implicit conversion from string is usually a bad thing. E. g.: >>> bool("False"), bool("0") (True, True) Peter From theller at python.net Fri Oct 29 14:38:54 2004 From: theller at python.net (Thomas Heller) Date: Fri, 29 Oct 2004 20:38:54 +0200 Subject: ctypes 0.9.2 released References: <1gmeuqj.1p0mkh41y1zvfcN%aleaxit@yahoo.com> Message-ID: Ian Bicking writes: > Just wrote: >>>One of the perceived strengths of Python is the fact that it >>>integrates well with the platforms it is running on, so it's not an >>>insulated box like Java. >> Another one of Pythons perceived strengths is that if you get a >> segfault, it's a bug in Python. With ctypes that will no longer be >> as clear. > > It's always been the case that C extensions can cause segfaults. This > is just a tool for incorporating C extensions, without writing any > extra C. It even says "c" right in the name, which should cause a > certain amount of (justified) fear for anyone who knows what that > means ;) > > Having ctypes in the stdlib would be cool, because it would mean that > many C library extension could be installed with no compilation step, > since ctypes would already be compiled as part of the default > install. Assuming the C library was already installed, but typically C > libraries get packaged for distribution long before the associated > Python extension is packaged. Of course I think that ctypes in the standard lib would be great, but I won't try to push this myself anymore. I tried several times in the past, and have failed miserably (at least that's how I feel). Thomas From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Sat Oct 2 14:44:24 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Sat, 02 Oct 2004 19:44:24 +0100 Subject: limitations of current logging package In-Reply-To: <2e37dc1.0410020754.739f8744@posting.google.com> References: <2e37dc1.0409230442.7e74543d@posting.google.com> <4edc17eb.0409232031.66ad3d4e@posting.google.com> <2e37dc1.0409260220.6ad5cb6c@posting.google.com> <2e37dc1.0410020754.739f8744@posting.google.com> Message-ID: Vinay Sajip wrote: > The following documentation, which is in CVS for Python and will be > part of the next release, does give information for simple usage: > > http://www.python.org/dev/doc/devel/lib/minimal-example.html +1! I think that makes the example much less intimidating. I don't understand why it is in the middle of the table of contents instead of at the beginning or end. And personally I would take some of the stuff off the module root page and put it on a subpage so the table of contents can be seen immediately... but that is just me. Thanks for this great module! -- Michael Hoffman From ialbert at mailblocks.com Mon Oct 11 08:56:31 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 11 Oct 2004 08:56:31 -0400 Subject: [ANN] Boo 0.4.3 - python-like language for .NET/Mono In-Reply-To: References: <8PGdnS7wN_uwg_rcRVn-qw@comcast.com> Message-ID: Doug Holton wrote: > Like I said in the first sentence of my earlier message: > "I thought I'd share it here since there has been so much interest for > similar projects like IronPython." What I referred to was that the reason IronPython got so much interest in this group is not because it is a *python-like* language on the CLI but because it aims to be *python* on the CLI. Big difference IMO. If you'd make your language a valid python implementation, that could also access .NET components (a la python) it would instantly become a bazillion times more popular and talked about. A "hey, it looks like python but it is not really python" approach has little chance of capturing a python programmer's imagination. It just muddies the water and sows confusion among potential adopters. this is just an opinion, and I've been wrong many times before... Istvan. From psparago at yahoo.com Sun Oct 17 13:00:14 2004 From: psparago at yahoo.com (Peter Sparago) Date: 17 Oct 2004 10:00:14 -0700 Subject: win32com extension help Message-ID: <584da15e.0410170900.3f090aa4@posting.google.com> (Sorry in advance for the long post.) Hi, I'm having a great deal of difficulty buiding a Python COM extension. I am using the MSHTML ActiveX control in my application but I need to interact with and implement some Custom COM interfaces. All is well with the basic operation of the control using Python. Basically, I want to take over the right-click (context) menu from MSHTML. To do this (to the best of my knowledge), you must request the ICustomDoc interface from the control and set up your own implementation of the IDocHostUIHandler interface. In Python COM extension lingo, I need an ICustomDoc interface and an IDocHOstUIHandler gateway. First off, any link to HOW-TO documentation on this subject would be greatly appreciated. I wanted to start with something very simple, so I am trying to implement an extension that understands only the ICustomDoc interface. I ran makegw and hand-edited the resulting interfaces to get my .PYD to compile and link (and even load!). I pretty much understand the actual implementation of the COM support generated by makegw, but I'm very hazy on the extension "wiring" necessary to publish this COM support to Python. (i.e. the use of PyMethodDef and PyCom_InterfaceSupportInfo etc.) So, I thought I'd look for a working example and do a knock-off. I'm running Python 2.3 and I've downloaded and built pywin32-203. I have previously worked in great detail with the IFilter interface, so I chose that win32comext project to use as a model. The problem is, when I run the demo python code (called filterDemo.py) to exercise the IFilter support, it fails with the following error: C:\Joey\pywin32-203\com\win32comext\ifilter\demo>filterDemo.py test.txt Traceback (most recent call last): File "C:\Joey\pywin32-203\com\win32comext\ifilter\demo\filterDemo.py", line 4, in ? from win32com.ifilter import ifilter ImportError: cannot import name ifilter This is the same error I'm getting with my own implementation .PYD. (BTW: Yes, I have moved ifilter.pyd into the C:\Python23\Lib\site-packages\win32com directory.) Can ANYONE help? Please? From jzgoda at gazeta.usun.pl Sat Oct 16 06:17:35 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 16 Oct 2004 10:17:35 +0000 (UTC) Subject: Eric3 + Qt licensing [was Re: The IDE question] References: <416f9663$0$94915$bed64819@news.gradwell.net> Message-ID: pitkali pisze: >>>> Windows versions are named, royalty-free, commercial licenses. >>>> [... long, tortuous explanation ...] Hallo, any lawyers around >>>> here? >>> >>> As he said, "way too messy"! ;) >> >> I am not sure if Detlev can pose such exceptions... Well, >> Qt-and-around is not an easy shoot. ;) > > He hold the copyright (with Phil Thompson). He is the licensor. He can > do all he wants. Don't think it's possible to claim "software is GPL but you cann't distribute it". Either don't pose such restriction or use another license. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From jmeile at hotmail.com Wed Oct 27 15:20:44 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 27 Oct 2004 21:20:44 +0200 Subject: module signal In-Reply-To: <3e96ebd7.0410270509.10e4c8b2@posting.google.com> References: <3e96ebd7.0410260054.197dd951@posting.google.com> <417EA12C.6060803@hotmail.com> <3e96ebd7.0410270509.10e4c8b2@posting.google.com> Message-ID: <417fd8ee@pfaff2.ethz.ch> > I don't see how to do it with a Timer object only. Could you rewrite > the regexp example with a Timer object such that it works? Oh yes, I'm wrong. I confused this module with something else, sorry. From bokr at oz.net Sun Oct 17 16:34:45 2004 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Oct 2004 20:34:45 GMT Subject: Some notes References: <5c882bb5.0410121238.71ae761a@posting.google.com> <1glm9eg.1yldhpvtdfww2N%aleaxit@yahoo.com> <416fee05$1@nntp0.pdx.net> <1glr5vz.s10y5ympbao9N%aleaxit@yahoo.com> Message-ID: <4172c795.65285525@news.oz.net> On Sat, 16 Oct 2004 14:34:30 +0200, aleaxit at yahoo.com (Alex Martelli) wrote: [...] > >The iterator over arguments, which I propose, could not be implemented >in Python today (Python today has no way to collect yet-unevaluated >arguments). I do believe that the C interpreter would need few changes >to implement it (what syntax to use to signal it being the one >contentious part), and even fewer to accept a .skip method on generators >and use it to set a local variable _must_skip_next_yield in the >generator's frame (not particularly useful, I believe -- not all >iterators would have to be skippable, and, unless strong use cases >emerge, normal generators might well be deemed nonskippable ones). > If py3k eliminated current back-ticks in favor of a new use, namely `expr being short spelling of lambda:expr (Actually, I think 'expr should not just be lambda:expr but capture snapshot references to the variables in the expr. I.e., if expr was 2*a.x-3 you'd have lambda a=a:2*a.x-3 -- while making sure that a etc are just bare name references, but then I couldn't just type in the simplified examples below, which I don't want to retype ;-) then you could write stuff like >>> def ifelse(c, t, f): ... if c(): return t() ... else: return f() ... and call that using ifelse(`condition, `value_if_true, `value_if_false) except for now we have to use the long spelling of lambda (and should use longer yet spelling ;-) : >>> def show(x): print 'evaluated %r'%(x,); return x ... >>> c = lambda: show(True) >>> t = lambda: show('true value') >>> f = lambda: show('false value') >>> ifelse(c, t, f) evaluated True evaluated 'true value' 'true value' >>> ifelse(lambda:show(0), t, f) evaluated 0 evaluated 'false value' 'false value' of course, if you are modifying python, you could make ifelse a special form, along with cond, and have the back-ticks implied instead of explicit. if you think of cond as a flat series of (condition, value_expr) pairs, (was that the intent?) >>> def cond(*cvp): ... cvp = iter(cvp) ... for c in cvp: ... if c(): return cvp.next()() ... cvp.next() ... return False ... >>> true = lambda:show(True) >>> false = lambda:show(False) >>> >>> cond(false, f, false, t, true, t, false, f) evaluated False evaluated False evaluated True evaluated 'true value' 'true value' >>> cond(false, f, false, t, false, t, false, f) evaluated False evaluated False evaluated False evaluated False False >>> cond(false, f, true, t, false, t, false, f) evaluated False evaluated True evaluated 'true value' 'true value' Regards, Bengt Richter From wrightca at hotmail.com Sun Oct 17 03:14:13 2004 From: wrightca at hotmail.com (Chris Wright) Date: Sun, 17 Oct 2004 07:14:13 GMT Subject: How to get user input with time limit? In-Reply-To: <6bq3n09a3dlbnhbhpt1nrt1ud7l9g4b9t7@4ax.com> References: <6bq3n09a3dlbnhbhpt1nrt1ud7l9g4b9t7@4ax.com> Message-ID: <9Zocd.29080$5O5.17757@news-server.bigpond.net.au> User wrote: > Anyone know of a function like raw_input(), but with a built-in or > user-specified time limit? Ideally, it would return an empty string > ('') and resume processing if the user didn't enter something within > ~10 seconds. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 might help Chris Wright From ptmcg at austin.rr._bogus_.com Wed Oct 20 08:39:45 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 20 Oct 2004 12:39:45 GMT Subject: Help needed: cryptic perl regular expression in python syntax, Ugly solution References: <41756F67.1060307@wlanmail.com> Message-ID: "Steven Bethard" wrote in message news:mailman.5207.1098253340.5135.python-list at python.org... > Could you do something like: > > >>> line = ' s^\\?AAA\\?01^BBB^g; #Comment ' > >>> expr = r'(^\s*)(s|tr)(.)(\\\?%s)\3(.*?)\3(.*)' > >>> matcher = re.compile(expr % re.escape("AAA\?01")) > >>> matcher.findall(line) > [(' ', 's', '^', '\\?AAA\\?01', 'BBB', 'g; #Comment ')] > > Basically, I still use the r'' string so that I don't have to write so many > backslashes, but then I use a %s to insert the "AAA\?01" into the middle of > the expression. Looks at least a little cleaner to me. > > Steve > Here's a more verbose version of Steve Bethard's suggestion. By building up the regexp from individual parts, it is possible to give each part some semi-meaningful name, or to attach comments to individual pieces. It also makes it easier to maintain later. What if you had to support an additional command besides s and tr, like 'rep'? Just change replaceCmd to read replaceCmd = r'(s|tr|rep)'. What if you needed to support leading tabs in addition to leading spaces? Change leadingWhite as needed. For that matter, just giving the finished regexp the name 'replaceCmdExpr' gives the reader more of a clue as to what the regexp's purpose is, as the original code did with extra comments. I find nearly *all* regexp's to be cryptic, and when I need them, I usually assemble them in some fashion such as this. David Mertz proposes a similar style in his very good book, "Text Processing in Python." (Some quibble with the practice of aligning '=' signs, but I find it to be a helpful guide to the eye when declaring a set of related strings such as these, assuming of course that one edits using a fixed space font.) So why does the key get prepended with the backslashes and question marks? -- Paul (I'll bet you thought I'd post a pyparsing version. :) Well, in a certain way, I did.) import re line = ' s^\\?AAA\\?01^BBB^g; #Comment ' r1 = r'(^\s*)(s|tr)(.)(\\\?\\??' key = "AAA\?01" r2 = r'\\??)\3(.*?)\3(.*)' r = r1 + re.escape(key) + r2 print re.compile(r).findall(line) # desired regexp, from Steve Bethard's post # r'(^\s*)(s|tr)(.)(\\\?%s)\3(.*?)\3(.*)' # build up regexp by parts key = r'AAA\?01' leadingWhite = r'(^\s*)' replaceCmd = r'(s|tr)' sepChar = r'(.)' # prepend \'s and ?'s, only the OP knows why... findString = r'(\\\?\\??%s)' % re.escape(key) # sepCharRef references the char read by sepChar, # to support separators other than '^' sepCharRef = r'\3' replString = r'(.*?)' restOfLine = r'(.*)' replaceCmdExpr = leadingWhite + replaceCmd + \ sepChar + findString + sepCharRef + \ replString + sepCharRef + restOfLine matcher = re.compile( replaceCmdExpr ) print matcher.findall(line) From greg.lindstrom at novasyshealth.com Wed Oct 13 16:48:09 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Wed, 13 Oct 2004 15:48:09 -0500 Subject: Working with Forms in MS Word Message-ID: <029e01c4b165$f36f2fe0$054b12ac@D18SYX41> Greetings- I have been asked if I can populate existing Forms in a Microsoft Word Document. I have the book Python Programming on Win 32 (Hammond/Robinson) which addresses Microsoft products, but it does not address forms. Has anyone attempted this? And if so, would you pass along your knowledge? Thanks!, --greg Greg Lindstrom (501) 975-4859 NovaSys Health greg.lindstrom at novasyshealth.com "We are the music makers, and we are the dreamers of dreams" W.W. From sholden at flexal.cs.usyd.edu.au Fri Oct 1 03:02:33 2004 From: sholden at flexal.cs.usyd.edu.au (Sam Holden) Date: 1 Oct 2004 07:02:33 GMT Subject: python vs c# References: <415CFA79.9070105@holdenweb.com> Message-ID: On Fri, 01 Oct 2004 02:34:33 -0400, Steve Holden wrote: > Jan Dries wrote: > >> Bengt Richter wrote: >> [... ] >> >>>I almost posted a similar comment ;-) OTOH ... >>>How many relevant points do you need to start a debate? > > Well, terrific. Now I get to talk about one of my pet peeves. A friend > just gave me a bumper sticker which, as a true (but hopefully liberal) > pedant I had real trouble with. It reads "Some village in Texas is > missing their idiot", and the reason for my perplexity was, while I feel > the sentiment it expresses is admirable (though perhaps mistaken: I only > wish George W Bush *were* as stupid as he manages to appear), I have to > take issue with the grammar used to express it. > > This particular pickle is a disagreement of number: since there is only > one village, the correct slogan should be "... is missing its idiot". If > you thought it was "... it's idiot" then take two demerits and refrain > from posting on c.l.py for 48 hours. Their isn't necessarily plural so that isn't a problem. Since arguing grammar isn't something I can do successfully, I'll instead resort to an appeal to authority and say that one of the authors of "The Cambridge Grammar of the English Language" agrees with me: http://itre.cis.upenn.edu/~myl/languagelog/archives/000172.html -- Sam Holden From gdamjan at gmail.com Thu Oct 28 04:17:32 2004 From: gdamjan at gmail.com (Damjan) Date: Thu, 28 Oct 2004 10:17:32 +0200 Subject: ReportLab newbie References: <2uac8bF2802bfU1@uni-berlin.de> Message-ID: <2ubo8sF2999dfU1@uni-berlin.de> >>from reportlab.pdfbase import pdfmetrics >>from reportlab.pdfbase.ttfonts import TTFont >>fontname = 'Arial-Bold' >>my_TTF = '/opt/Fonts/arial.ttf' >>font = TTFont(fontname, my_TTF) >>pdfmetrics.registerFont(font) > > Do you realize that arial.ttf is normal Arial, and not bold? Arial bold > lives in arialbd.ttf. Ahh, stupid copy/paste... the exception was raised when fontname = "Arial" ... the above example doesn't raise an exception, and it was experiment. > Reportlab automatically registers the Arial family.??You?shouldn't?need?to > register it yourself. it seems that I can't register "Arial" as fontname since Reportlab does it automatically... in the end, fontname = 'MyArial' did fine. -- damjan From 00hello00 at hellokitty.com Fri Oct 22 22:40:41 2004 From: 00hello00 at hellokitty.com (marie) Date: 22 Oct 2004 19:40:41 -0700 Subject: How to use date object Message-ID: <91c5be0a.0410221840.1a5d4cc@posting.google.com> I am a newbie in python. And I would like to know how to create and use the methods in date. Can someone please show me some code about it. Thanks. From richardblackwood at cloudthunder.com Thu Oct 7 00:07:00 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Thu, 07 Oct 2004 00:07:00 -0400 Subject: New to Python: Features In-Reply-To: <4164a43a.3914128499@news.oz.net> References: <20041005101730.ECD4.JCARLSON@uci.edu> <4162E3CC.3080200@cloudthunder.com> <20041005111159.ECE0.JCARLSON@uci.edu> <4162f360$0$55262$a1866201@newsreader.visi.com> <4164a43a.3914128499@news.oz.net> Message-ID: <4164C0E4.9000107@cloudthunder.com> Bengt Richter wrote: >On Wed, 06 Oct 2004 09:29:07 +0100, Richie Hindle wrote: > > > >>[Richard] >> >> >>>I could care less honestly. >>> >>> >>[Grant] >> >> >>>I've always been curious about that phrase. It seems to imply >>>that you _do_ care, since it would be possible for you to care >>>less than you do. Shouldn't the expression be "I couldn't care >>>less"? >>> >>> >>In the UK we say "I couldn't care less". >> >> >> > >Perhaps Richard was proposing the notion that he could care differently. >(i.e., less honestly ;-) >(Otherwise, IMO, there should have been a comma after his "less.") > > > >>One theory is that in the US it has become the sarcastic opposite of >>itself, as in "tell me about it" or "I should be so lucky". >> >>Another theory is that it's been mangled through overuse - the >>individual syllables ceased to matter a long time ago, and the "n't" was >>lost because of sloppy speech. >> >>As revealed by PSU Research Paper "UU788", the *real* reason is a side >>effect of the nanovirus encroaching into non-whitespace, as first >>proposed by "UU355" and then earlier proven (twice, as it turned out) by >>"UU6 9". The only defence is t*^$Z:%Z* NO CARRIER >> >> >> >My linguistic feature-clustering/distribution detector signals significant >probability of non-English-first-language when scanning Richard's prose. >Possible origin: planet U^g%% > >Regards, >Bengt Richter > > Trying to figure out which language was my first is like trying to bake a vegan chicken dish--- there are only so many vegans so I doubt you will be able to find a recipe that will serve you right. From dubal at khimjiramdas.com Sat Oct 2 07:33:11 2004 From: dubal at khimjiramdas.com (J Dubal) Date: 2 Oct 2004 04:33:11 -0700 Subject: help: pypgsql: this code works in Fedora core 1, Not in FC2 References: Message-ID: Cliff Wells wrote in message news:... > On Sun, 2004-09-26 at 00:41 -0700, J Dubal wrote: > > Hello good people, > > > > Following works in FC1 (python-2.2.3-7, postgresql-7.3.4-11, > > kernel-2.4.22-1.2194.nptl, pyPgSQL-2.4) > > > > from pyPgSQL import PgSQL > > conn = PgSQL.connect('localhost',database='rop') > > loccur = conn.cursor() > > loccur.execute("DECLARE itemcursor CURSOR FOR \ > > SELECT * FROM locmf") > > loccur.execute("FETCH ALL FROM itemcursor") > > rec=loccur.fetchall() > > print rec > > > > However, following errors are produced in FC2 (python-2.3.3-6, > > postgresql-7.4.2-1, kernel-2.6.8-1.521, pyPgSQL-2.4): > > > > /usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py:2644: FutureWarning: > > %u/%o/%x/%X of negative int will return a signed string in Python 2.4 > > and up > > name = "PgSQL_%08X" % id(self) > > Traceback (most recent call last): > > File "tt1.py", line 5, in ? > > loccur.execute("DECLARE itemcursor CURSOR FOR \ > > File "/usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3091, > > in execute > > self.res = self.conn.conn.query('FETCH 1 FROM "%s"' % self.name) > > libpq.OperationalError: ERROR: cursor "PgSQL_F6F9906C" does not exist > > > > Out of this, the first error is produced by conn.cursor() statement. > > > > We have to use the "declare cursor" statement because we have to use > > "fetch prior" statement later in the program. Is there a better way of > > achiving this? > > > > Something seems to have changed either python or in postgresql that is > > causing this error. Can someone provide a solution/workaround? > > Don't know if anything changed between the versions of the software you > are using, but see > > http://www.postgresql.org/docs/current/static/sql-declare.html > > particularly the section on "WITH HOLD/WITHOUT HOLD" and the first > paragraph in "Notes". I'm guessing that perhaps you aren't starting a > new transaction before declaring the cursor and that perhaps pyPgSQL is > autocommitting the DECLARE statement which would result in your declared > cursor going out of scope. Try adding WITH HOLD or put your stuff > inside of "BEGIN/COMMIT" statements. > > Regards, > Cliff > > > Thanks in advance. > > J Dubal. Many thanks for your response. We tried a few things and found that although the above code does not work on FC2, it works if we change this statement: conn = PgSQL.connect('localhost',database='rop') to this: conn = PgSQL.connect('192.168.1.5',database='rop') 192.168.1.5 happens to be another host running redhat 8.0 and postgresql-server-7.3.4-1PGDG. It appears that the older (7.3.4) engine was allowing the above syntax but the newer (7.4.2) is not allowing. Then we tried conn.conn.toggleShowQuery. This shows what sql statements are executed. Based on its output we worked out the following solution. Relace these lines: loccur.execute("DECLARE itemcursor CURSOR FOR \ SELECT * FROM locmf") loccur.execute("FETCH ALL FROM itemcursor") by these lines: loccur.execute("SELECT * FROM locmf") curname=loccur.name loccur.execute('FETCH ALL FROM "%s"' %curname) Then everything works as expected. Even with the old engine. Thanks and regards. J Dubal. From HansWL at msn.com Wed Oct 6 19:15:05 2004 From: HansWL at msn.com (HansWL) Date: 6 Oct 2004 16:15:05 -0700 Subject: Dynamically Generating a Graph in Python References: <47f7cc78.0409300618.332a3278@posting.google.com> <691232ce.0410030304.2f84c04b@posting.google.com> <691232ce.0410040930.2ed080d9@posting.google.com> Message-ID: <691232ce.0410061515.36ee0f23@posting.google.com> John Hunter wrote > It would be interesting to know where this performance hit is coming > from. What happens if you set backend : TkAgg and interactive : True > in your rc file, and then fire up a standard python shell > > >>> from matplotlib.matlab import * > >>> t = arange(0.01, 2.0, 0.01) > >>> s = sin(2*pi*t) > >>> figure(1) > >>> plot(t,s) > > In interactive mode, all the plotting commands are acted upon when > they are issued, which should enable you to debug which of these > commands, if any, causes the long delay. Finally got sometime to try again. Seems most time was spent importing (30 seconds). So in interactive mode, I imported once, then execfiled your examples with import commented out. Now the figures came on within seconds. From peter at engcorp.com Tue Oct 26 16:17:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Oct 2004 16:17:40 -0400 Subject: int/long unification hides bugs In-Reply-To: References: <940ee3e8.0410250456.65445bbd@posting.google.com> <940ee3e8.0410252005.25a94170@posting.google.com> Message-ID: Rocco Moretti wrote: > (I'm surprised no one has mentioned unit testing yet.) The topic (without the word "unit" in it, mind you) was raised fifteen minutes after kartik first posted. Istvan and Steve have both mentioned it as well. -Peter From stewart.midwinter at gmail.com Sat Oct 9 12:07:14 2004 From: stewart.midwinter at gmail.com (Stewart Midwinter) Date: 9 Oct 2004 09:07:14 -0700 Subject: xml file structure for use with ElementTree? References: Message-ID: Andrew Dalke wrote > Legal XML would look like > sigh... after a good night's sleep I discovered that myself this morning. It's obvious, of course. > for person in tree.findall("person"): > if person.attrib["name"] == "joe": > tree.remove(person) > break > else: > raise AssertionError("Where's joe?") That's the ticket! Unfortunately at the moment when I run this code I get the following error:' ElementTree instance has no attribute 'remove' but I'll try to work through that. > Given what you've shown, you need a reference to XML > and not ElementTree. The latter assumes you understand > the former. I don't have one handy. that's a polite way of saying I'm clueless about XML, which is true! The main appeal of ElementTree was so I could avoid having to learn a whole lot about XML in order to parse a simple file, but I am coming to the conclusion that ElementTree is only simple if you already have an understanding about XML. thanks again, S From sw at wordtech-software.com Fri Oct 22 09:59:10 2004 From: sw at wordtech-software.com (Kevin Walzer) Date: Fri, 22 Oct 2004 09:59:10 -0400 Subject: IDLE--what are your experiences with it? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm looking for other peoples' viewpoints about their experiences with IDLE as an editor--what are its good points? What are its limitations? Any advice/insight is appreciated. - -- Kevin Walzer, PhD WordTech Software--Open Source Applications and Packages for OS X http://www.wordtech-software.com http://www.smallbizmac.com http://www.kevin-walzer.com mailto:sw at wordtech-software.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFBeRItJmdQs+6YVcoRAlMfAJ9HCm/JWKZF4SpYBrivPHM1EO3slgCdGrJF wgbnOgkYH0ywOlF0dFy9rUU= =DUrq -----END PGP SIGNATURE----- From listserver at tdw.net Sun Oct 10 19:26:52 2004 From: listserver at tdw.net (Tim Williams) Date: Mon, 11 Oct 2004 00:26:52 +0100 Subject: Python email References: <41696005.1080902@mail.ru> Message-ID: <000a01c4af20$9fe29f20$ccbefea9@twilliams> "LutherRevisited" wrote in message news:20041010135948.07384.00002435 at mb-m29.aol.com... > I'm attempting to write an email client, and I've run into a snag. I've seen > several docs on email, but they're not dumbed down enough for me. Basically > I'm downloading my messages like this: > M = poplib.POP3('pop.mail.yahoo.com') > M.user('username') > M.pass_('password') > inMail = str(M.retr(i)) > and I get the message just fine, but I want to pull out of all that just the > html part. How can I do this. as a pointer using your inMail string (untested, and you should read the docs for the email module to find the functions that will really suit your requirements) import email emailobj = email.message_from_string(inMail) # or emailobj = email.message_from_string( str(M.retr(i)) ) if not emailobj.is_multipart(): # return/break/pass etc e_payload = emailobj.get_payload() #then something like for x in range(len(e_payload)): e_name = e_payload[x].get_filename() #or e_type = e_payload[x].get_content_type() # I doubt the last two functions will do what you need, but there will be functions in the email module that you can use in their place From fuzzyman at gmail.com Tue Oct 12 11:56:18 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 12 Oct 2004 08:56:18 -0700 Subject: HTTP Headers to make a download Message-ID: <6f402501.0410120756.63276342@posting.google.com> I'm creating a CGI that offers files for download. After googling I though I had the right headers to send to force a download - but it sends the data to the browser instead of opening the download 'save file' dialog. Can anyone see what I'm doing wrong/suggest an alternative ? responseline = '''Content-Type: application/octet-stream Content-Disposition: attachment; filename=%s Content-Length: %s ''' print responseline % (filename, len(filedata)) print filedata TIA Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From __peter__ at web.de Tue Oct 5 03:51:17 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 05 Oct 2004 09:51:17 +0200 Subject: Miscellaneous personal prejudices (was: Dr. Dobb's Python-URL! - weekly Python news and links (Oct 4)) References: <36i932-lr5.ln1@lairds.us> <1tudnWqDWMKcpf_cRVn-qg@rogers.com> Message-ID: Ville Vainio wrote: >>>>>> "Dan" == Dan Perl writes: > > Dan> "What do I have to say to get into the QOTW?" > > Change your last name? Or his first name? Damn Perl... Peter From exogen at gmail.com Mon Oct 4 15:19:32 2004 From: exogen at gmail.com (Brian Beck) Date: Mon, 04 Oct 2004 15:19:32 -0400 Subject: Comparing WSDL & SOAP libraries... In-Reply-To: <86vfdqpcjl.fsf@stronzo.brainbot.com> References: <86vfdqpcjl.fsf@stronzo.brainbot.com> Message-ID: > > For your purposes there is a complete python package: > http://pygoogle.sourceforge.net/ > Wow, thanks for the heads-up. I figured such a package would be included directly in Google's API demos if it existed since they seem to be such big Python advocates. Brian From torsten.marek at student.uni-tuebingen.de Fri Oct 8 10:03:27 2004 From: torsten.marek at student.uni-tuebingen.de (Torsten Marek) Date: Fri, 08 Oct 2004 16:03:27 +0200 Subject: ANN: GUI wrapper for pygtk, pyqt and wxpython In-Reply-To: References: Message-ID: <41669E2F.7090208@student.uni-tuebingen.de> Stelios Xanthakis schrieb: > Hi. > > I'd like to announce the availability of a high-level GUI wrapper > for pygtk, pyqt and wxpython. > > Check out the screenshot at > > http://students.ceid.upatras.gr/~sxanth/twgui/ > > I wanted to write a *simple* app with a GUI that didn't look as horrible > as Tk and without having to ask from the users to install this or that. > All three (pygtk, pyqt and wxpython) have serious drawbacks for one to > invest their time learning them. > Having had just a short peek at your code (I come from a PyQt background), I'd suggest that you use properties for stuff like enabled (any widget) and text (line edits), which saves you a lot of functions. It should also be possible to define the shadow classes automatically (either dynamically or with a script that generates them from an input file), because the simple widgets (at least for PyQt) look pretty much the same. greetings Torsten From reinhold-birkenfeld-nospam at wolke7.net Sat Oct 30 12:03:48 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 30 Oct 2004 18:03:48 +0200 Subject: Regex speed In-Reply-To: References: <2uff4eF2a7uskU1@uni-berlin.de> <2uh4g5F29ntaoU1@uni-berlin.de> Message-ID: <2uhsb4F2998pnU1@uni-berlin.de> Erik Heneryd wrote: > Reinhold Birkenfeld wrote: >> OK, thank you. I now got rid of all the regexes, and - surprise, >> surprise - the speeds are almost equal. The bitter thing about it is >> that there are now twelve LOC more in Python that don't make >> understanding the code easier. > > If your problem is that the re.compile() setup takes too long (compared > to the time taken to do the actual matching/replacing), my guess is that > you don't operate on that much data. And if that's the case, does it > really matter if it's a fraction of a second slower? My data file is 6 MB in size, I don't think that to be too little. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From d+pydev at trit.org Sun Oct 31 10:13:27 2004 From: d+pydev at trit.org (Dima Dorfman) Date: Sun, 31 Oct 2004 15:13:27 +0000 Subject: Pickle breakage with reduce of recursive structures (was: AssertionError in pickle's memoize function) In-Reply-To: References: Message-ID: <20041031151326.GB22539@trit.org> [Followups to python-dev, please.] [Michael Hohn] > > > under python 2.2, the pickle/unpickle sequence incorrectly restores > > > a larger data structure I have. > > > > > > Under Python 2.3, these structures now give an explicit exception from > > > Pickle.memoize(): > > > assert id(obj) not in self.memo > > > [Tim Peters] > > Assertions are never expected to fail, so "something impossible > > happened" when they do fail. [Michael Hohn] > Here is a code sample that shows the problem I ran into: Summary for the OP: This is a bug in Python. Using cPickle won't help, but if you don't subclass builtin container types others than list, dict, and tuple, using pickle protocol 2 should work. The rest of this message is for python-dev. The simplest breaking case is: t = type('t', (list,), {}) obj = t() obj.append(obj) pickle.dumps(obj) [infinite recursion] The subclass causes save_reduce to be used instead of save_list. For proto < 2, copy_reg._reduce_ex returns (_reconstructor, list(a)), and the args--list(a)--cycle back through obj. Initially it looks like this should be okay, but the args are saved before obj is memoized, and obj can't be memoized until REDUCE can be executed with the args--and there's the cycle. It is even more obviously impossible from the unpickler's perspective because it has to call _reconstructor([obj]) to create obj! There are two separate problems: 1. Any __reduce__ implementation that returns args that cycle back through the object it tried to reduce hasn't done its job. As described above, _reduce_ex is one such implementation. reduce_2 avoids this by using the listitems and dictitems parameters. Since that's a pickler-side feature it can be used in _reduce_ex too. The basetype(obj) hook (documented in PEP 307) would remain for immutable bases; it doesn't work for containers, but user-defined containers already have to implement their own reduce functions. POC patch: http://www.trit.org/~dima/home/reduce_ex.diff At least the set and deque types also have this problem. 2. The pickle implementations don't detect reduction cycles. Pickling an instance of this obviously broken class causes an infinite recursion: class evil(object): def __reduce__(self): return evil, (self,) It's easy to detect this case. POC patch for the pickle module: http://www.trit.org/~dima/home/redcycle.diff BTW, the failed assert the OP is seeing happens when the cycle goes through another object: t = type('t', (list,), {}) obj = t() d = {'obj': obj} obj.append(d) pickle.dumps(obj) [AssertionError] cPickle has the same problem, but it lacks the assert, so it writes garbage instead: new = cPickle.loads(cPickle.dumps(obj)) new[0]['obj'] is new -> False # wrong obj[0]['obj'] is obj -> True # right This makes the reduction cycle check (#2 above) more than just cosmetic since if cPickle had that assert (it should) it would've been a crash. Right now it's garbage output instead, which is arguably worse. Formally complete versions of the above patches will be on SF tomorrow unless someone suggests better alternatives. Dima. From fuzzyman at gmail.com Fri Oct 29 03:29:47 2004 From: fuzzyman at gmail.com (Michael Foord) Date: 29 Oct 2004 00:29:47 -0700 Subject: Becoming Unicode Aware References: <6f402501.0410270256.13cf5727@posting.google.com> <1gmd10n.1xt7l7q6ahyacN%aleaxit@yahoo.com> Message-ID: <6f402501.0410282329.3728361c@posting.google.com> aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1gmd10n.1xt7l7q6ahyacN%aleaxit at yahoo.com>... > Michael Foord wrote: > ... > > def afunction(setoflines, encoding='ascii'): > > for line in setoflines: > > if encoding: > > line = line.decode(encoding) > > This snippet as posted is a complicated "no-op but raise an error for > invalidly encoded lines", if it's the whole function. > :-) It wouldn't be the whole function...... glad you attribute me with some intelligence ;-) > Assuming the so-called setoflines IS not a set but a list (order > normally matters in such cases), you may rather want: > > def afunction(setoflines, encoding='ascii'): > for i, line in enumerate(setoflines): > setoflines[i] = line.decode(encoding) > > The removal of the 'if' is just the same advice you were already given; > if you want to be able to explicitly pass encoding='' to AVOID the > decode (the whole purpose of the function), just insert a firs line > > if not encoding: return > > rather than repeating the test in the loop. But the key change is to > use enumerate to get indices as well as values, and assign into the > indexing in order to update 'setoflines' in-place; assigning to the > local variable 'line' (assuming, again, that you didn't snip your code > w/o a mention of that) is no good. The rest of the function (which I didn't show) would actually process the lines one by one...... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html > > A good alternative might alternatively be > > setoflines[:] = [line.decode(encoding) for line in setoflines] > > assuming again that you want the change to happen in-place. > > > Alex From adam at 757.org Mon Oct 18 22:57:37 2004 From: adam at 757.org (Adam) Date: Mon, 18 Oct 2004 22:57:37 -0400 Subject: python-dev Summary suggestion In-Reply-To: <41747A89.6070608@ocf.berkeley.edu> References: <41746E2A.7080703@757.org> <41747A89.6070608@ocf.berkeley.edu> Message-ID: <417482A1.5090301@757.org> Brett C. wrote: > Adam wrote: > >> Would it be possible to provide some kind of either syndication (RSS?) >> or (dedicated) email list for the Summary? I don't have time to read >> / keep track of python-dev, so I really appreciate all the work you >> put into the summary - I'm just wondering if there might be a better >> way to 'get it out', rather than just a static web page on python.org. >> > > RSS would be possible, but the last time I suggest the idea to the web > team they didn't think it was worth it. The thought was that since it > is on python-announce you can subscribe to that to get the Summary when > it comes out. I noticed after I had sent the first email that it came out on regularly on python-announce, and picking it up there may be the simpler solution in the end - beats trying to remember to hit the website every two weeks! > >> Has this been discussed before? I googled around and didn't see >> anything mentioning this. I see the cross post between python-dev and >> c.l.p.announce, but no mention of anything else (it may have been lost >> in the tons of hits :). >> > Tell you what, can you reply to the c.l.py and ask for people to comment > on the idea? If enough people like the idea I will add the feed. > > -Brett Anybody have any comments on this? Good idea, horrid idea? Now that I know it comes out on CLPA regularly, I'm not tied to the idea, though the notion of RSS is still attractive, given my personal browsing habits. -- Adam From davecook at nowhere.net Tue Oct 26 10:10:33 2004 From: davecook at nowhere.net (Dave Cook) Date: Tue, 26 Oct 2004 14:10:33 GMT Subject: newbie: pygtk (win, slack10) References: <20041025212503.94278.qmail@web54001.mail.yahoo.com> Message-ID: In article , Pierre N wrote: > Should be enough for a while :-)) > If I could speak Brazilian as well as you speak English, I would be > sooo happy... See http://pygtk.org for the tutorial and reference. If you want to run on windows, download and install the gladewin package: http://gladewin32.sourceforge.net/ as well as the pygtk package for win32: http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ If you have questions, there is a significant cabal of Portuguese speaking pygtk developers that hang out on gimpnet's #pygtk IRC channel. http://www.xach.com/gimpnet/ Dave Cook From adalke at mindspring.com Wed Oct 6 12:48:18 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 06 Oct 2004 16:48:18 GMT Subject: Retrieving the full path of Unix apps In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > def is_executable(filename): > return os.access(filename, os.X_OK) Ahh. Didn't know about 'access'. Looks like I could change >> if (os.path.exists(filename) and >> os.path.isfile(filename) and >> is_executable(filename)): into if (os.access(filename, os.X_OK) and os.path.isfile(filename)): because access returns false if the file/directory doesn't exist. Andrew dalke at dalkescientific.com From lutherrevisited at aol.com Mon Oct 11 17:45:33 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 11 Oct 2004 21:45:33 GMT Subject: Python email References: <10mj13bcgn25v33@corp.supernews.com> Message-ID: <20041011174533.19211.00002356@mb-m03.aol.com> I have no idea what this derived from POP3Magic thing is, can you give me more on that. I've begun to familiarize myself with the methods in email, but my big snag seems to be that I get a single string that I can't manipulate with these methods from what should be a multi-part message. From jcarlson at uci.edu Tue Oct 5 00:05:08 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 04 Oct 2004 21:05:08 -0700 Subject: New to Python: Features In-Reply-To: <416210AF.5060908@cloudthunder.com> References: <416210AF.5060908@cloudthunder.com> Message-ID: <20041004203353.ECBC.JCARLSON@uci.edu> Had you read the tutorial, you would discover the answers to all of these questions, but I'll answer them anyways. > 1. Multi line comments No. > 2. Functions as variables: > a. functions can be stored in variables, passed as arguments to > other functions, and returned as results. Yes. > 3. Function nesting with proper lexical scope (i.e. closures) Yes. > 4. Operator overloading (inc. the ability to define new operators) Yes, check the operator module for names of operations. > 5. Can I do this? print("Hello " .. "World") --> Hello World Not precisely. You can do: print "Hello","World" print ("Hello " "World") print "Hello "+"World" and many other variants. > 6. Constructors If you mean class instantiation, yes. > 7. "Chunks": as in a code block contained within a string, file, or > delimited by some sort of notation (such as brackets) which can be > passed to and from functions, stored in objects, with the option of > local scoping of variables declared within it. code = "print 'hello world'" glbls = {} lcls = {} exec code, glbls, lcls > 8. "Repeat-Until" as in : > repeat > line = os.read() > until line ~= "" > print(line) line = sys.stdin.readline() while line != '': print line line = sys.stdin.readline() > 9. Generic for loops where " for i=1,f(x) do print(i) end" would print i > only once. for i in xrange(1,n+1,1): print i break > 10. Can I call an object's method as object:method(arg) and have that > translate into object.method(object, arg) class foo: def goo(self, arg): print self, arg def bar(arg): print arg bar = staticmethod(bar) a = foo() a.goo(arg) #will print information about the instance and argument a.bar(arg) #will only print information about the argument > 11. Can I make dynamic statements and nature like with eval() in Javascript? Yes, check both eval and exec > 12. Can I make calls to a function with a varying number of arguments? Yes. > 13. Named arguments Yes. > 14. Tables with built-in methods for manipulation such as sort, etc. We call them lists. > 15. Table filters filter(callable, iterable) > 15. Proper Tail Call (otherwise known as Proper Tail Recursion) No, it kills tracebacks. > 16. The ability to call a function without brackets No. > 17. Is the Python interpreter a JIT? Does it have a bytecode? Is it as > fast as Java? There is a module called Psyco that does do JIT compilation. In the CPython implementation, bytecode is automatically generated. If you want to know about speed, check a benchmark site. > 18. The ability to modify the import/require functionality (how modules > can be loaded) Yes, you can write custom import hooks. > 19. Coroutines and threads (non-preemptive) Threads, yes. For corutines, check out greenlets or Stackless Python. > 20. Date persistence and serialization This can mean any one of a dozen things. > 21. May modules be stored in variables, passed to and produced from > functions, and so forth? Yes, though it isn't done very often. > 22. Is the self parameter hidden from me as a programmer? Can I > hide/unhide it as I wish? It is not hidden, in fact, you get to name it... class foo: def goo(I_AM_SELF, arg): pass > 23. Prototype-based OOP or the ability to extend a class without > physically modifying it We have unlimited subclassing. If you want prototypes, check out Prothon. > 24. Manual garbage management You can disable it, or force collection. gc.disable() gc.collect() > 25. A fully implemented .NET counterpart (I should be able to write > Python scripts for both with the same code) Check IronPython and PythonNET > 26. How easily can other languages access it and vice versa? C and C++ are easy. There is a TCL interface. Anything with C or C++ interfaces are arguably trivial to talk to. > 27. The option of mixing in static typing Python has no static typing. > 28. Automatic type coercion Certain kinds of things can do what is known as "type coercion" in other languages. What kinds of coercion did you want to do. > 29. Is Python designed in such a way that I may merely "plugin" a > C/C++/Java/D module which will then allow for mixing their syntax and > perhaps even access to their facilities within Python? You can call C/C++ functions in Python (a large portion of the standard library is implemented in C). Jython allows nearly transparent use of Python and Java. You don't get other language syntaxes, generally. > 30. Messaging syntax such as : [myColor setRed:0.0 green:0.5 blue:1.0] > or [dog bring:paper to:me] and [[myAunt phone] setTo:[myUncle phone]] > <--- Nested messages and [dog perform:sel_get_uid("bark")] which is the > same as [dog bark] We don't do messaging syntax. Combining messaging and object-oriented syntax would make for an ugly language. > 31. Concepts of Protocols (whereby one may organize related methods into > groups and check whether a particular object implements the methods > within this protocol), or Interfaces similar to those in Java whereby > classes or objects which implement the interface (sign the contract) > must implement the methods and attributes as specified in the interface, > and/or programming by contract such as in Eiffel (see: > http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=595) No. Test-driven development is the norm in Python. > 32. Support for unplanned reuse of classes such as in TOM > (http://www.gerbil.org/tom/) Subclassing. > 33. Function/Method overloading Yes. > 34. In pure Python, can I change and add new constructs to the Python > syntax? Yes, if you are willing to work for it. > 35. May I modify the garbage collector? If you really want, though it already works fine. > 36. May I implement control structures as object messages? If you want. > 37. Dynamic dispatch This could mean a few different things. > 38. Reflection and/or templates Think subclasses. > 39. Unicode Yes. > 40. Ability to call external APIs and DLLs with relative ease Check pywin32. > 41. How easy is it to port my Python code to C/C++/C# or Java? Depends on how experienced you are with those languages. > 42. The ability to assign a method(s) to a collection/group of objects > [with a particular signature i.e.] No. > 43. Embedding variables in strings like: print "Hello, World. Time: > #{Time.now}" t = time.asctime() print "Hello World %(t)s"%{'t':t} print "Hello World %(t)s"%locals() > 44. Case or Switch statements with functionality as such: > case score > when 0...40 > puts "Horrible!" > when 40...60 > puts "Poor" > when 60...80 > puts "You can do better!" > when 80...95 > puts "Now that's acceptable" > when 95..100 > puts "That the best you can do? j/k" > else > puts "Didn't take the test?" > end No. > 45. Are all things objects in Python? Do all objects have built-in > iterators and the like? i.e. can I do this: > 3.times { print "Ho! " } > puts "Merry Christmas" Not everything has an iterator, though many does. Next time, read the damn documentation. - Josiah From jbors at mail.ru Tue Oct 5 02:08:20 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Mon, 4 Oct 2004 23:08:20 -0700 Subject: mp3/ogg player References: Message-ID: <10m4eil87rmcd22@corp.supernews.com> "Francis Lavoie" wrote in message news:mailman.4282.1096931463.5135.python-list at python.org... > Hi > > I looking to build a second program in python. I would like to code a > music player, which can play mp3 an ogg files. But every solution that I > find, seem over complicated or not multiplaform. > Is there a simple package of libraries that we only have to install > once, or plug it into the program that give mp3 and ogg playability like > a .jar file in java? Not sure if you tried pygame or pymedia( http://pymedia.org ) Dmitry/ From maxm at mxm.dk Thu Oct 7 10:17:50 2004 From: maxm at mxm.dk (Max M) Date: Thu, 07 Oct 2004 16:17:50 +0200 Subject: ctypes, error when calling function In-Reply-To: References: <4165275e$0$285$edfadb0f@dread12.news.tele.dk> Message-ID: <41654fd7$0$216$edfadb0f@dread12.news.tele.dk> Richie Hindle wrote: > [Max] > >>caps = MIDIOUTCAPS() >>[...] >>print winmm.midiOutGetDevCapsA(deviceID, caps, sizeof(caps)) >>[...] >>ValueError: Procedure probably called with too many arguments (60 bytes >>in excess) > > > You need to pass byref(caps) rather than caps. The API expects a > pointer to the structure, not the structure itself. Thanks. Yes I figured it out about the same time i read your reply. I guess it's been about 15 years since I have last coded in c, :-s so I'm a bit rusty. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From k04jg02 at kzoo.edu Sun Oct 24 15:22:48 2004 From: k04jg02 at kzoo.edu (dataangel) Date: Sun, 24 Oct 2004 15:22:48 -0400 Subject: how do i change from string to list In-Reply-To: References: <99ca2e2f.0410241005.39a4f1db@posting.google.com> <417bf196$0$771$3a628fcd@reader20.nntp.hccnet.nl> Message-ID: <417C0108.5000205@kzoo.edu> Michael Hoffman wrote: > Ivo Woltring wrote: > >> str='spot' >> >> lst = [] # declare the list first >> for letter in str: >> lst.append(letter) # append to the list >> >> print lst > > > I just would have used list("spot"). > >> result: ['s', 'p', 'o', 't'] > > > Same result but faster, more transparent, and with a lot less code. > > Also, please don't top-post. Also, if for some reason you didn't want to use list that would look more elegant as a list comprehension: >>> y = "Hello!" >>> [x for x in y] ['H', 'e', 'l', 'l', 'o', '!'] >>> From aahz at pythoncraft.com Tue Oct 5 12:38:24 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Oct 2004 12:38:24 -0400 Subject: OT: movie fluff (was Re: New to Python: Features) References: <4162185c$0$59860$a1866201@newsreader.visi.com> <41621efc$0$59533$a1866201@newsreader.visi.com> Message-ID: In article <41621efc$0$59533$a1866201 at newsreader.visi.com>, Grant Edwards wrote: > >Which one, the "Rude much?" crack or the "You've got to be kidding..." >crack? The latter isn't all that improper (especially not for Usenet). >The former is colloqial US English. More specifically it's "Valley >Speak" -- made popular outside "The Valley" by movies like "Valley >Girl", "Mall Rats", "Heathers", and just about any John Hughes movie >(especially Sixteen Candles). The first two are crap, but "Heathers" >is a good movie, and I still like "Sixteen Candles". _Heathers_ may be good, but I was unable to finish watching it. I find it too painful to watch people behaving stupidly for no good reason. Similarly, I was unable to finish watching _Bandits_. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ WiFi is the SCSI of the 21st Century -- there are fundamental technical reasons for sacrificing a goat. (with no apologies to John Woods) From mike at spindler.us Mon Oct 18 09:14:42 2004 From: mike at spindler.us (mikeSpindler) Date: 18 Oct 2004 06:14:42 -0700 Subject: execvp() on Solaris Message-ID: I've seen it addressed in searching, but not specifically what is recommended to get around it. On Linux where I did my development all was fine. But then going to Solaris for the target I found I couldn't resolve the errors wrt execvp(). It's apparently not syntax, but I could be wrong. Any other thoughts on how to get execvp() working and/or how to cat a file in a new window without bringing tkinter into the discussion? My example: os.system("xterm -geometry 120x20 -e \"tail -f ./logs/DATAFILE\"&") Thank you! Mike From aleaxit at yahoo.com Mon Oct 18 10:27:43 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 18 Oct 2004 16:27:43 +0200 Subject: Style question on recursive generators References: Message-ID: <1glv17s.hq00886bg9exN%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > Yes, that's a good point, and it's one of the reasons I tend to prefer > the generator now. But anyway, it's just me, or does the 'chained > yield' look ugly to someone else? It may be just a question of getting > used to it, but nevertheless it's bugging me... I'm not sure why it should look ugly to you. What alternatives would you consider non-ugly for the common (in any generator) idiom: for x in y: yield x ? Perhaps some syntax hack such as a new statement keyword 'yieldall' where the above idiom could be expressed as yieldall y ? Or some other syntax hack such as 'yield< I've put together a collection of links to Python 3D projects: http://www.vrplumber.com/py3d.py at the moment I only have 36 projects listed. I *know* there are more out there, but tracking them all down myself is rather time-consuming. So, if you have, or know of a project that isn't included in the list, please send me an email about it. Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From aleaxit at yahoo.com Thu Oct 7 15:13:56 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 7 Oct 2004 21:13:56 +0200 Subject: Parallelization on muli-CPU hardware? References: <6db3f637.0410042045.2171ad5f@posting.google.com> <6db3f637.0410052100.31bbe86f@posting.google.com> <1glatga.8upk9brifr2qN%aleaxit@yahoo.com> <1glawed.1e83ntp1ck15pvN%aleaxit@yahoo.com> Message-ID: <1glb1jy.1at6as41fab2t9N%aleaxit@yahoo.com> Aahz wrote: ... > >> still possible to use introspection to access thread-local data in > >> another thread. > > > >Is it...? Maybe I'm missing something...: > > If you look at the code for _threading_local, you'll see that it depends > on __getattribute__() to acquire a lock and patch in the current > thread's local state. IIRC from the various threads about securing > Python, there are ways to break __getattribute__(), but I don't remember > any off-hand (and don't have time to research). I believe you're thinking of the minimal portable version: I believe that for such systems as Windows and Linux (together probably 99% of Python users, and i speak as a Mac fan...!-) there are specific implementations that use faster and probably unbreakable approaches. Alex From adalke at mindspring.com Fri Oct 8 18:34:47 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 08 Oct 2004 22:34:47 GMT Subject: smtplib, capturing output from set_debuglevel ?? In-Reply-To: References: <00ab01c4ad2a$bfe9aa90$ccbefea9@twilliams> <41668EDD.8090808@holdenweb.com> Message-ID: Tim Williams > Yeah, I did wonder about changing the code (though it's not my first > choice. I've done it before and caught a crab later), or could I do it > with Subclassing? > > I'm still close to Newbie status, so I can't immediately imagine what I > could change the smptblib code to write to, or how to subclass to get > the behaviour I might need. It can't be done with subclassing. You'll need to copy smtplib to a new file. Call it 'smtplib2.py'. Edit it so the class constructor takes an output file object class SMTP: ... def __init__(self, host = '', port = 0, local_hostname = None, debugfile = sys.stderr): .... self.debugfile = debugfile This lets you attach an arbitrary file-like object to each SMTP instance. Then go through the class definition and change every place that looks like if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) into self.debugmsg('connect:', (host, port)) and create a new method named 'debugmsg' which looks like def debugmsg(self, *args): self.debugfile.write(" ".join(map(str, args))) + "\n") (Or the long way def debugmsg(self, *args): if args: self.debugfile.write(str(args[0])) for arg in args[1:]: self.debufile.write(" " + str(args[1])) self.debugfile.write("\n") Another option, if you decide to go this route, is that you can change the protocol and the debug messages. For example, if you want it to go to a list you can change this so as to use a 'debug_msgqueue = []' and so debugmsg appends the args to that list. You can also change the actual messages sent by the library. Andrew dalke at dalkescientific.com From greg at cosc.canterbury.ac.nz Wed Oct 20 22:48:10 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 21 Oct 2004 15:48:10 +1300 Subject: Python + Java knowledge In-Reply-To: References: <4175ed72$1@news.unimelb.edu.au> Message-ID: <2tombdF22ksv0U1@uni-berlin.de> Josiah Carlson wrote: > Most programming languages require in a natural language sense, a > grammatical knowledge of the programming language in order to understand > it. Ergo, those that do well with grammar, generally would do well with > learning new programming languages (API notwithstanding); as programming > languages are a basic grammar with a handful of vocabulary words and > punctuation thrown into the mix. Also, learning a programming language is usually a MUCH simpler affair than learning a natural language. The grammars of natural languages tend to be rather haphazard and require memorizing a large number of arbitrary rules. Programming languages are usually a lot simpler and more regular. I consider myself well acquainted with quite a number of programming languages, but despite studying French for a few years at school, English remains the only natural language in which I'm anywhere near fluent! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From peter at engcorp.com Fri Oct 1 09:14:40 2004 From: peter at engcorp.com (Peter L Hansen) Date: Fri, 01 Oct 2004 09:14:40 -0400 Subject: Python in Process Control? In-Reply-To: References: Message-ID: Wolfgang Keller wrote: > There seem to be some Python bits out there, for example MatPLC and > Lintouch use Python and some commercial products as well (PyDACHS), but > unfortunately there doesn't seem to be a more or less consistent library > for industrial automation or a coordinated effort to build up one. What, in your opinion, would it take to start one? I'm able to offer the use of a server to host a web site, and would be happy to register a domain name or something, but those are the easy bits. Some kind of core group to get it off the group is likely more important than a name, though sometimes threads in this group might lead one to suspect otherwise. ;-) -Peter From dave at pythonapocrypha.com Sat Oct 2 18:36:33 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 02 Oct 2004 16:36:33 -0600 Subject: python vs c# In-Reply-To: <0l7ul05ker0i9n039c0ut4pna3hh54dfou@4ax.com> References: <415CFA79.9070105@holdenweb.com> <0l7ul05ker0i9n039c0ut4pna3hh54dfou@4ax.com> Message-ID: <415F2D71.10909@pythonapocrypha.com> Tim Roberts wrote: > Sam Holden wrote: > >>Steve Holden wrote: >> >> >>>This particular pickle is a disagreement of number: since there is only >>>one village, the correct slogan should be "... is missing its idiot". If >>>you thought it was "... it's idiot" then take two demerits and refrain >>>from posting on c.l.py for 48 hours. >> >>Their isn't necessarily plural so that isn't a problem. Since arguing >>grammar isn't something I can do successfully, I'll instead resort >>to an appeal to authority and say that one of the authors of >>"The Cambridge Grammar of the English Language" agrees with me: [snip] > Second, "their" is allowed as a singular pronoun only in those cases where > a gender-specific pronoun is called for, but the gender is unclear or would > be sexist. Instead of "Everyone brought his Python manual," we are now > allowed to say "Everyone brought their Python manual." It's now correct to use "their" in that way now? Yay! I'm glad the way I've always used it is finally correct. Take THAT, my English teachers of days long gone! Now if I could only convince them to happily split infinitives... -Dave From claird at lairds.us Thu Oct 7 01:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Thu, 07 Oct 2004 05:08:03 GMT Subject: Suggestions for Python workshop References: Message-ID: In article , Fernando Perez wrote: >Yaroslav wrote: > >> Hi, I'm preparing a 2 hour workshop titled "Python for Scientific >> Computing", the goal of which is to introduce people to using Python >> for their Scientific Computing needs. If you have good examples that >> illustrate Python's power for scientific computing, please post them >> here. > >These aren't code snippets but full talks, but we're definitely using python >for 'real' research: > >http://amath.colorado.edu/faculty/fperez/talks/04_03_ams_athens.pdf >http://amath.colorado.edu/faculty/fperez/talks/04_09_scipy04_mwadap.pdf > >Here you'll also find other talks from the recent scipy'04: > >http://www.scipy.org/wikis/scipy04/ConferenceSchedule > >As far as code examples, I imagine all of scipy's code could be used :) . . . I have strong feelings on this subject, only a fraction of which I'll be able to articulate this week. First, follow everything Fernando says; he's doing great work. Second, I see a variety of approaches to Python-for-scientists, and I hope you're able to end up with a Pythonic one. There's low-level how-to-ing: "this is an implementation of a Rayleigh-Ritz algorithm for PDE solution; you can use this in hydrodynamics to ..." What *really* gets interesting, though, are comparing Python to other vehicles--Matlab, C++, Fortran-- and, if you're really good, opening the audience's eyes to the potential of a language which facilitates comprehension, collabor- ation, and experimentation. Most scientific listeners won't understand abstraction as it applies to software. Python-for- scientists represents a great opportunity. From thorsten at thorstenkampe.de Sun Oct 3 07:25:00 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 3 Oct 2004 13:25:00 +0200 Subject: File handling: The easy and the hard way References: Message-ID: <1vfpqxbsm1igk.dlg@thorstenkampe.de> * Hans-Joachim Widmaier (2004-09-30 15:56 +0200) > Handling files is an extremely frequent task in programming, so most > programming languages have an abstraction of the basic files offered by > the underlying operating system. This is indeed also true for our language > of choice, Python. Its file type allows some extraordinary convenient > access like: > > for line in open("blah"): > handle_line(line) > > While this is very handy for interactive usage or throw-away scripts, I'd > consider it a serious bug in a "production quality" software. Tracebacks > are fine for programmers, but end users really never should see any. Correct. Set sys.tracebacklimit to zero (and leave it at the default 1000 for "--debug'). > Especially not when the error is not in the program itself, but rather > just a mistyped filename. (Most of my helper scripts that we use to > develop software handle files this way. And even my co-workers don't > recognize 'file or directory not found' for what it is.) End users are > entitled to error messages they can easily understand like "I could not > open 'blaah' because there is no such file". Graceful error handling is > even more important when a program isn't just run on a command line but > with a GUI. > > Which means? Which means that all this convenient file handling that > Python offers really should not be used in programs you give away. When I > asked for a canonical file access pattern some months ago, this was the > result: > http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&threadm=pan.2003.12.30.21.32.37.195763%40web.de&rnum=1&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26q%3Dfile%2Bpattern%2Bcanonical%26btnG%3DSuche%26meta%3D > > Now I have some programs that read and write several files at once. And > the reading and writing is done all over the place. If I really wanted to > do it "right", my once clear and readily understandable code turns into a > nightmare. This doesn't look like the language I love for its clarity and > expressivness any more. I think the whole task is rather complicated. Python just passes the error message of the operating system through without interpreting it. Of course "no such file" is b***sh*t for an error message (because it's even lacking a verb) but can Python by itself be more sophisticated about these things than the OS? I don't think so. Think about "/foo/bar/baz/text.txt doesn't exist". There are multiple reasons 1. There is a directory /foo/bar/baz/ but no test.txt in it. 2. The whole path hierarchy is missing: there isn't even a /foo. 3. It was there, I know it because wrote to the file, but now I cannot access the directory anymore. Is the file deleted? The directory? Did I lose access to the network where the share is actually located? Now this is where the intelligence of the programmer comes in and they try to guess. They say: "Sorry, I'm not sitting in front of the machinem but this error message could mean this." And oftenly they are ridiciously wrong. If anyone ever made some kind of "error matrix" - meaning if error foo and bar but not baz then it's likely whatever, the whole community could profit. Thorsten From marketing at intekasia.com Thu Oct 7 10:04:56 2004 From: marketing at intekasia.com ( DD) Date: 7 Oct 2004 14:04:56 GMT Subject: Lolita in China Message-ID: An HTML attachment was scrubbed... URL: From corey.coughlin at attbi.com Wed Oct 6 17:19:19 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 6 Oct 2004 14:19:19 -0700 Subject: Social Analysis and Modeling for Python References: <415AD6A4.7000400@cloudthunder.com> <1096493975.1238.45.camel@emilio> Message-ID: Yeah, working with C made it pretty horrible, you had to use records and functions to try to simulate objects, and basically it meant that anytime someone made a change, there was often an unfortunate ripple effect. And the memory leaks, ugh. And my background was electrical engineering, so that didn't help too much, but I picked things up pretty quickly. I made a little knock off version of the program that, instead of simulating an entire population, took a single individual and did a monte carlo simulation of possible futures of that person. The results were a little more personal that way. But that was all a long time ago, I'm sure the state of the art is far beyond that now. -------- Corey Bishara Gabriel wrote in message news:... > Corey Coughlin wrote: > > >Actually, back in school, I worked for a sociology professor doing a > >human population simulator, where we had all these people objects and > >a set of functions that updated their attributes as time went on, but > >we were forced to do it in C to have in run on the campus > >supercomputer, so it wasn't what you'd call object oriented. I can > >see how using Python would make the modeling aspects a lot simpler. > >So, to sum, sounds cool, hope you have a lot of sucess with it. > > > > > > > C??? My, that isn't even C++. That must have been a real pain (mind > stretcher) I imagine. What is your area of specialty? > > Thanks for the encouragement. We also are hoping to have a lot of success! From bokr at oz.net Mon Oct 4 03:51:42 2004 From: bokr at oz.net (Bengt Richter) Date: 4 Oct 2004 07:51:42 GMT Subject: python vs c# References: <9j6ul0db19k6rrmfjbs6kgjar0ldagfoji@4ax.com> Message-ID: On Mon, 4 Oct 2004 10:23:58 +1100, Andrew Durdin wrote: >On Sat, 02 Oct 2004 14:31:05 -0700, Tim Roberts wrote: >> >> I was going to object to this statement. I went to my good friend "Google" >> to look up some references but "a number of" is very common and thus >> difficult to search for. > >Not at all: > >"+a number +of * have" -- about 1,280,000 results >"+a number +of * has" -- about 28,800 results Google seems to accept those quoted arguments, but I could not find '*' usage explained in the advanced search tips. Nor usage of special characters within quotes. Where did you find out about that? (And are you sure you need the +'s? The '*' does definitiely do something though.) Regards, Bengt Richter From jacek.generowicz at cern.ch Fri Oct 1 03:22:26 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Oct 2004 09:22:26 +0200 Subject: C API eqivalent of object.__new__ Message-ID: How would one write object._new__(SomeType) in the C API ? ... and what lies behind the following behaviour: >>> object.__new__(T) Traceback (most recent call last): File "", line 1, in ? TypeError: object.__new__(T) is not safe, use T.__new__() where T refers to almost any fundamental Python type ? From ralf at brainbot.com Mon Oct 4 14:23:58 2004 From: ralf at brainbot.com (Ralf Schmitt) Date: Mon, 04 Oct 2004 20:23:58 +0200 Subject: Comparing WSDL & SOAP libraries... References: Message-ID: <86vfdqpcjl.fsf@stronzo.brainbot.com> Brian Beck writes: > Hi again folks! > > I tried searching the newsgroup for this and nobody seemed to be > asking the questions I wanted. > > I'm trying to take advantage of the Google API using Python, and it > comes with a WSDL file in order to do so. Of course, I immediately > figured someone must have already written a WSDL parser in Python. > For your purposes there is a complete python package: http://pygoogle.sourceforge.net/ > It appears that I have a few options... > > SOAPy - http://soapy.sourceforge.net/ > wsdl4py - http://www-124.ibm.com/developerworks/projects/wsdl4py/ > ZSI - http://packages.debian.org/testing/python/python-zsi > > It also looked like there was a tutorial using a 'WebService' module, > but I couldn't immediately find a home page for this -- it may have > been the project that SOAPy is a part of. > > I'd simply like to know if someone has already done all the research > in this area and has come to a conclusion regarding which one of these > is the 'best'? Easiest to set up and use, fastest, frequently > updated, etc... > I once tried to use ZSI to implement a soap server. It's neither easy to set up and use, nor fast. In the end I wrote my own package to implement a soap server. - Ralf -- brainbot technologies ag boppstrasse 64 . 55118 mainz . germany fon +49 6131 211639-1 . fax +49 6131 211639-2 http://brainbot.com/ mailto:ralf at brainbot.com From golux at comcast.net Fri Oct 1 03:04:37 2004 From: golux at comcast.net (Stephen Waterbury) Date: Fri, 01 Oct 2004 03:04:37 -0400 Subject: python vs c# [gone OT] In-Reply-To: <415CFA79.9070105@holdenweb.com> References: <415CFA79.9070105@holdenweb.com> Message-ID: <415D0185.9070207@comcast.net> Ah, the joys of OT ... :) Steve Holden wrote: > Well, terrific. Now I get to talk about one of my pet peeves. A friend > just gave me a bumper sticker which, as a true (but hopefully liberal) > pedant I had real trouble with. It reads "Some village in Texas is > missing their idiot", and the reason for my perplexity was, while I feel > the sentiment it expresses is admirable (though perhaps mistaken: I only > wish George W Bush *were* as stupid as he manages to appear), I have to > take issue with the grammar used to express it. > > This particular pickle is a disagreement of number: since there is only > one village, the correct slogan should be "... is missing its idiot". Although I agree with you, interpreting the noun "village" as a collective noun (http://www.chompchomp.com/terms/collectivenoun.htm) is a correct usage; therefore, it can be used with a plural verb. Of course, that does kind of change the sense -- all those people thinking wistfully of the idiot they lost ... :) (Incidentally, one of the more extreme cases I've seen was in England, where I saw an "out-of-order" sign at the entrance to the an Underground station that began "The London Transport regret ...." I tried to imagine all the individual personnel of London Transport feeling regret that that particular station was closed. Gee, what a compassionate people! ;) Cheers, Steve From alexander.landgraf at gmx.net Wed Oct 20 17:56:48 2004 From: alexander.landgraf at gmx.net (Alexander Landgraf) Date: Wed, 20 Oct 2004 21:56:48 GMT Subject: Python 2.3.4 under AT&T MP RAS SVR4: ld: Symbol referencing errors. Message-ID: Hi group, I am not sure if this is the correct place for my question. If not, please tell me. I tried to compile Python 2.3.4 under AT&T MP RAS SVR4: $./configure --prefix=${HOME} --with-threads=no $make but make fails because each invocation of ld causes errors like: ... running build running build_ext building 'struct' extension cc -DNDEBUG -O -OPT:Olimit=0 -I. -I/home/q904958/src/python2_3_ 4/./Include -I/home/q904958/src/python2_3_4/Include - I/home/q904958/src/python2_3_4 -c /home/q904958/src/python2_3_ 4/Modules/structmodule.c -o build/temp.dwh1-4.0-3446-2.3/structmodule.o (cc:) Unknown optimization designation: -OPT:Olimit=0. Opt level 0 assumed. NCR High Performance C Compiler R3.0c (c) Copyright 1994-98, NCR Corporation (c) Copyright 1987-98, MetaWare Incorporated ld build/temp.dwh1-4.0-3446-2.3/structmodule.o -L/usr/local/lib -o build/lib.dwh1-4.0-3446-2.3/struct.so Undefined first referenced symbol in file strftime build/temp.dwh1-4.0-3446-2.3/structmodule.o __wcstok_ptr_ build/temp.dwh1-4.0-3446-2.3/structmodule.o PyLong_FromUnsignedLong build/temp.dwh1-4.0-3446-2.3/structmodule.o PyInt_Type build/temp.dwh1-4.0-3446-2.3/structmodule.o PyLong_Type build/temp.dwh1-4.0-3446-2.3/structmodule.o PyTuple_Type build/temp.dwh1-4.0-3446-2.3/structmodule.o ... UX:ld: ERROR: build/lib.dwh1-4.0-3446-2.3/struct.so: fatal error: Symbol referencing errors. No output written to build/lib.dwh1-4.0-3446- 2.3/struct.so ... My questions are: 1) Does that mean ld is unable to locate libraries? (Which libraries? strftime() is declared in time.h but I guess PyInt_Type is Python specific) 2) What is the correct way to specify library locations? (I tried ./configure --with-libs=-L/usr/lib but ld arguments did not change) Thank you for any hints. Alexander From fredrik at pythonware.com Sun Oct 10 03:28:15 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 10 Oct 2004 09:28:15 +0200 Subject: xml file structure for use with ElementTree? References: Message-ID: Andrew Dalke wrote: >> That's the ticket! Unfortunately at the moment when I run this code I >> get the following error:' >> ElementTree instance has no attribute 'remove' >> but I'll try to work through that. > > Perhaps you need a newer version of ElementTree? I don't > know when 'remove' was added. remove is available on Element instances. it's not available on ElementTree wrappers. From maxm at mxm.dk Thu Oct 7 07:25:44 2004 From: maxm at mxm.dk (Max M) Date: Thu, 07 Oct 2004 13:25:44 +0200 Subject: ctypes, error when calling function Message-ID: <4165275e$0$285$edfadb0f@dread12.news.tele.dk> Trying to write realtime midi in Windows I am using ctypes. So I have written a small wrapper for winmm.dll It partly works. I get this error when I try to run it: Traceback (most recent call last): File "E:\maxm\pys\MIDI-R~1\x.py", line 203, in ? print winmm.midiOutGetDevCaps(deviceID, caps, sizeof(caps)) File "E:\maxm\pys\MIDI-R~1\x.py", line 133, in __getattr__ return getattr(self._winmm, attr) File "C:\pytyons\Python23\Lib\site-packages\ctypes\__init__.py", line 316, in __getattr__ func = self._StdcallFuncPtr(name, self) AttributeError: function 'midiOutGetDevCaps' not found But the documentation says that the midiOutGetDevCaps() should exist in the dll. It calls the midiOutGetNumDevs() function in the dll nicely, wich is why I find it to be strange problem. Does anybody have a clue? It's my first try at ctypes, so I am a bit lost here. regards Max M #################################3 # The code from ctypes import * MAXPNAMELEN = 32 class MIDIOUTCAPS(Structure): _fields_ = [ ("wMid", c_int), # WORD ("wPid", c_int), # WORD ("vDriverVersion", c_long), # MMVERSION ("szPname", c_char * MAXPNAMELEN), # CHAR ("wTechnology", c_int), # WORD ("wVoices", c_int), # WORD ("wNotes", c_int), # WORD ("wChannelMask", c_int), # WORD ("dwSupport", c_long), # DWORD ] class Winmm: """A *very* thin wrapper over WINMM.DLL :-) """ def __init__(self): self._winmm = windll.WINMM def __getattr__(self, attr): return getattr(self._winmm, attr) if __name__ == '__main__': caps = MIDIOUTCAPS() winmm = Winmm() numDevs = winmm.midiOutGetNumDevs() for deviceID in range(-1, numDevs): print winmm.midiOutGetDevCaps(deviceID, caps, sizeof(caps)) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From aleaxit at yahoo.com Sun Oct 31 05:09:28 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 31 Oct 2004 12:09:28 +0200 Subject: Enumerate question: Inner looping like in Perl References: <4183d256$0$3665$39db0f71@news.song.fi> <4184bef5$0$19027$39db0f71@news.song.fi> Message-ID: <1gmis1r.khw0v1jpv8rzN%aleaxit@yahoo.com> Pekka Niiranen wrote: ... > ... try: > ... for i, char in itr: > ... print 'inner', i, char > ... if char == 'f': > ... break > ... except StopIteration: > ... print "f not found" ... > Not working: Iter() takes care of its own exceptions? Nope. Rather, the 'for' statement does not propagate the StopIteration exception that terminates it -- such a propagation would be extremely disruptive of 99% of Python's programs, and I'm astonished that you expected it! What you want is, I believe, among the Tutorial's examples...: for i, ch in itr: print 'inner', i, ch if ch == 'f': break else: print 'f not found' That's what the 'else' clause in a 'for' statement is for: it triggers when the loop terminates normally (as opposed to ending with a break or return or by propagating an exception). The ability to deal with a "not found" case, where the "found" cases exit by break, is the main use case of this 'else' clause. > This recurring feeling that writing REALLY correct programs in Python > is not easier than in lower level languages... :( I think that you can get all the info about Python you need for the purpose (and then some) from "Python in a Nutshell", but of course I'm biased...;-) Alex From jhefferon at smcvt.edu Wed Oct 27 10:44:09 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 27 Oct 2004 07:44:09 -0700 Subject: Becoming Unicode Aware References: <6f402501.0410270256.13cf5727@posting.google.com> Message-ID: <545cb8c2.0410270644.7aa2128d@posting.google.com> fuzzyman at gmail.com (Michael Foord) wrote ... > I'm trying to become 'unicode-aware'... *sigh*. What's that quote - 'a > native speaker of ascii will never learn to speak unicode like a > native'. The trouble is I think I've been a native speaker of latin-1 > without realising it. It *is* odd, IMHO, that my database connector spits out strings-like things that have 8-bit data so that when I "".join(array_of_database_strings) them, I get a failure. I've learned to by-hand them into unicode strings, but it is odd. Something like a pair (encoding,string) seems more natural to me, but probably I just don't get the issues. > > My main problem with udnerstanding unicode is what to do with > arbitrary text without an encoding specified. To the best of my > knowledge the technical term for this situation is 'buggered'. E.g. I > have a CGI guestbook script. Is the only way of knowing what encodign > the user is typing in, to ask them ? > I found this link https://bugzilla.mozilla.org/show_bug.cgi?id=18643#c12 useful. Jim From rff_rff at remove-yahoo.it Wed Oct 6 06:23:58 2004 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Wed, 06 Oct 2004 10:23:58 GMT Subject: Python Macros In-Reply-To: <1gl8cxp.1bwobhn1emgfx1N%aleaxit@yahoo.com> References: <41618797$0$69737$ed2619ec@ptn-nntp-reader01.plus.net> <416190BE.6080802@fastmail.fm> <5Wu8d.25573$H11.796921@twister1.libero.it> <1gl8cxp.1bwobhn1emgfx1N%aleaxit@yahoo.com> Message-ID: <2JP8d.26848$N45.697634@twister2.libero.it> Alex Martelli ha scritto: > > Please explain how this syntax choice "discriminates" anything > whatsoever? __getattr__ is called when some message isn't understood by > the "normal" mechanisms of the object, too. I actually meant __getattribute__ sorry. The point is that when you write x.foo(y) in py you're looking up foo, then calling it with y. Actually you can even store x.foo away and call it later f=x.foo in ST you can't cause you're not doing a dict lookup when you write x foo: y obviously you could send another message asking for x to give you a method foo: object Not that one is better than other just a subtle difference. From exarkun at divmod.com Fri Oct 15 14:06:02 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Fri, 15 Oct 2004 18:06:02 GMT Subject: [Web-SIG] WSGI async API In-Reply-To: <864d3709041015105131652057@mail.gmail.com> Message-ID: <20041015180602.4730.1637681532.divmod.quotient.123@ohm> On Fri, 15 Oct 2004 14:51:54 -0300, Carlos Ribeiro wrote: >On Fri, 15 Oct 2004 13:24:19 -0400, Peter Hunt wrote: > > Essentially, Twisted.Web gives you something like this: > > > > class MyResource(resource.Resource): > > def render(self, request): > > return "content here" # you could also do request.write("content here") > > > > If you do an async call, you have to use request.write() to write the > > data, return server.NOT_DONE_YET from the render() method, and call > > request.finish() to finish the request. > > Just curious, so forgive me from jumping into the middle of the > discussion. Isn't this one of the scenarios where output generators > are most useful? Assuming that Twisted supported it, you could yield > lines until there were nothing else to write. Did I get it right? > Only if you can also signal to the code which is iterating the generator that it should stop iterating it for a while, otherwise user code might be called upon for bytes before they are available. If I have understand the conversation on the matter then this caveat is a main stumbling block for the async wsgi api. Jp From james.frohnhofer at csfb.com Thu Oct 14 12:01:12 2004 From: james.frohnhofer at csfb.com (Frohnhofer, James) Date: Thu, 14 Oct 2004 17:01:12 +0100 Subject: question on list comprehensions Message-ID: <89D59C407D04D54AA82DC8BA312D430D10C616E9@enyc11p32001.corpny.csfb.com> I have to admit, I'm still not sure I understand the problem, but is this what you're trying to do? >>> res=[[0,1,2,3,4,5,6,7,8,9],[2,2,2,2,2,2,2,2,2,2],[0,-1,-2,-3,-4,-5,-6,-7,-8,-9]] where in reality rather than a list of 3 lists of 10 elements, res would be a list of 2500 lists of 2000 elements each. >>> map(lambda x: x*x, map(lambda tup: reduce(lambda x,y:x+y,tup), [ [res[i][j] for i in range(0,len(res))] for j in range(0,len(res[0])) ] ) ) [4, 4, 4, 4, 4, 4, 4, 4, 4, 4] If that's what you're trying to do. I have no idea about whether this is faster than other methods, although it certainly seems to me to be less clear. If you stored your data cross-sectionally, it would be much simpler. (Again, if this it what you're trying to do.) > -----Original Message----- > From: python-list-bounces+james.frohnhofer=csfb.com at python.org > [mailto:python-list-bounces+james.frohnhofer=csfb.com at python.org]On > Behalf Of Darren Dale > Sent: Thursday, October 14, 2004 11:16 AM > To: python-list at python.org > Subject: Re: question on list comprehensions > > > Roberto Antonio Ferreira De Almeida wrote: > > > Darren Dale wrote: > >> Hi, > >> > >> I need to replace the following loop with a list comprehension: > >> > >> res=[0] > >> for i in arange(10000): > >> res[0]=res[0]+i > > > > res[0] = (10000 * (10000-1))/2.0 ;-) > > > >> In practice, res is a complex 2D numarray. For this > reason, the regular > >> output of a list comprehension will not work: constructing > a list of > >> every intermediate result will result in huge hits in > speed and memory. > > > > Why do you *need* to replace the for loop with a listcomp? Could you > > give more details about what you're doing with the complex array? > > > > Roberto > > > OK. As usual, I am having trouble clearly expressing myself. > Sorry about > that. Prepare for some physics: > > I am simulating diffraction from an array of particles. I > have to calculate > a complex array for each particle, add up all these arrays, > and square the > magnitude of the result. If I do a for loop, it takes about > 6-8 seconds for > a 2000 element array added up over 250 particles. In reality, > I will have > 2500 particles, or even 2500x2500 particles. > > The list comprehension takes only 1.5 seconds for 250 > particles. Already, > that means the time has decreased from 40 hours to 10, and > that time can be > reduced further if python is not constantly requesting > additionaly memory > to grow the resulting list. > > I guess that means that I would like to avoid growing the > list and popping > the previous result if possible, and just over-write the > previous result. > -- > http://mail.python.org/mailman/listinfo/python-list > ============================================================================== This message is for the sole use of the intended recipient. If you received this message in error please delete it and notify us. If this message was misdirected, CSFB does not waive any confidentiality or privilege. CSFB retains and monitors electronic communications sent through its network. Instructions transmitted over this system are not binding on CSFB until they are confirmed by us. Message transmission is not guaranteed to be secure. ============================================================================== From parker at hiredatum.demon.co.uk Sat Oct 2 15:24:19 2004 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Sat, 2 Oct 2004 20:24:19 +0100 Subject: idiom for debug code? [1/1] References: <6tadnfHqDdcg9cHcRVn-hQ@rogers.com> Message-ID: <0DoHajVjBwXBFwhr@hiredatum.demon.co.uk> In message <6tadnfHqDdcg9cHcRVn-hQ at rogers.com>, Dan Perl writes >I was not thinking of actually removing code. The analogy to C++ >preprocessing was just an example. I am looking at something that can be >determined at run-time, not compile-time. > >And you're right, I'm not really concerned about the overhead of an "if" >because I will not use this extensively anyway. This problem occurred to me >when I decided to add an import for win32traceutil. I'm looking for a way >to have that permanently in the code and enabling/disabling it only at >run-time. > >I have thought of alternatives like an environment variable or a >configuration parameter, but I was looking for other ideas. I thought this >should be a common issue and that there could be an idiom for it. > >Dan > >PS: in the case of importing win32traceutil, I guess that checking the >environment would be necessary anyway, or the import should be in a try >statement, ignoring the exceptions. > >"Larry Bates" wrote in message >news:wfmdnXvIef4v1cHcRVn-vQ at comcast.com... >> Dan Perl wrote: >>> Is there a mechanism or an idiom for adding code for debugging so that it >>> can easily be removed in the production code? I am thinking of something >>> similar to the C/C++ preprocessor statements with which you can compile >>> an application with the debug code or without it (the default). >>> >>> Dan >> Personally I think you should consider NOT removing the debugging code. >> It never ceases to amaze me how many times I must have a client run >> the application with debug set so that the program logs details about >> the running process and intermediate results. The output logfile can >> then be easily emailed, faxed, etc. to me so that I can determine what >> is REALLY the problem. The overhead of these if _debug: "type" >> statements seems incredibly low compared to the ability to get this >> information when needed. Just some thoughts based on my experience >> of the last 30+ years. >> >> Larry Bates >> Syscon, Inc. > > I' use the following technique. I originally wrote it four years or so ago, so I'm sure it could be much improved. In fact looking at it now, I ma deeply embarrassed to post it, and know it could be dramatically improved both by using more modern features of Python, by better coding and by some comprehension of design. I have a utility.py module which contains my common functions and I import this in every module, plus a wrapper for the debug function: import utility debug = 0 def dprint( *args): """ print function toggled on or off by module debug variable """ global debug if debug: apply(utility._dprint,args) This allows me to scatter dprint functions throughout the module instead of print statements, and enable or suppress them by setting the global 'debug', e.g. def func(x): global total total += x dprint("total is currently",total) to get an output of something like: ! module.py:83 in func: total is currently 10 The relevant code from my utility.py is attached. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: utility debug.py URL: -------------- next part -------------- I would welcome rewrites of this code, of course. Regards Ian -- Ian Parker From vincent at visualtrans.de Thu Oct 28 04:55:16 2004 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 28 Oct 2004 10:55:16 +0200 Subject: Python utility convert Windows long file name into 8.3 DOS format In-Reply-To: References: <4C0gd.20216$R05.13225@attbi_s53> Message-ID: Simon Brunning wrote: > On Thu, 28 Oct 2004 06:47:28 GMT, Ben Kial wrote: > >>Is there a Python program to convert Windows long filename, like "c:\Program >>Files" into the old DOS 8.3 format, like "c:\Progra~1"? > > >>>>import win32api >>>>win32api.GetShortPathName('D:/share/from_roadwarrior/simon/python/RandomizeScreenSaver/RandomizeScreenSaver.pyw') > > 'D:/share/FROM_R~1/simon/python/RANDOM~1/RANDOM~1.PYW' > Just note that GetShortPathName expects a valid and accessible path in your file system. -- Vincent Wehren From claird at lairds.us Mon Oct 4 14:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Mon, 04 Oct 2004 18:08:03 GMT Subject: Python and C# References: <10m2la510rpeq86@corp.supernews.com> Message-ID: <5me832-qlt.ln1@lairds.us> In article , Larry Bates wrote: > > Looking for advice on this as a course of action. Obviously, >> I'm not doing this for fun, but for some reasons that are >> supported by base workaday considerations. Will this work? >> What are the biggest hassles in making it work? Any >> pitfalls? > >Sure this will work. You can call COM server code from Python >no matter what the COM server is written in. I've written >COM servers in Python and called from Python, VB, PowerBuilder, >etc. I've also called COM servers written in other languages. > >> >> If I get this to work well, next I want to make it easy for >> users to install and run the apps. I haven't tried to >> package any python apps in about a year. Which packaging >> package is better now for this -- py2exe, McMillan's, or >> something else? I want the end-users with no python on >> their Windows machine to run a simple and non-descript >> installer and then be up and running with my app, no >> problems. > >I like the combination of py2exe and Inno Setup. py2exe >create standalone code and Inno to create a distributable >installer. . . . 'Know what *I* think'll be the biggest surprise? 'Getting the run-time right for the C# part. You're developing the C# server under WinXP, right, but some users will try to run it under Win98? *That* might be a bit of an adventure ... From richardblackwood at cloudthunder.com Tue Oct 5 01:23:55 2004 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Tue, 05 Oct 2004 01:23:55 -0400 Subject: New to Python: Features In-Reply-To: <20041004203353.ECBC.JCARLSON@uci.edu> References: <416210AF.5060908@cloudthunder.com> <20041004203353.ECBC.JCARLSON@uci.edu> Message-ID: <41622FEB.1000300@cloudthunder.com> > > > code = "print 'hello world'" > glbls = {} > lcls = {} > > exec code, glbls, lcls > This is a cool language, I love code chunks!! > >10. Can I call an object's method as object:method(arg) and have that >>translate into object.method(object, arg) > > > class foo: > def goo(self, arg): > print self, arg > def bar(arg): > print arg > bar = staticmethod(bar) > > a = foo() > a.goo(arg) #will print information about the instance and argument > a.bar(arg) #will only print information about the argument > How come Python always complains when I don't include the self parameter in an object method? Your code doesn't work on my interpreter. > >>15. Proper Tail Call (otherwise known as Proper Tail Recursion) > > > No, it kills tracebacks. I know but that's a real bummer. No way around that? > > >>16. The ability to call a function without brackets > > > No. > So is the print statement ironed into the language and not a function? > >>17. Is the Python interpreter a JIT? Does it have a bytecode? Is it as >>fast as Java? > yes, you can write custom import hooks. > I guess I'll hit the docs with how to do this. > >>20. Date persistence and serialization > > > This can mean any one of a dozen things. > I'd like to store function and variables and of course objects in a form that can be easily read back into the program/script. > > >>21. May modules be stored in variables, passed to and produced from >>functions, and so forth? > > > Yes, though it isn't done very often. > Oh really?? Exciting, I'm glad of it. Hit the docs I must! > >>22. Is the self parameter hidden from me as a programmer? Can I >>hide/unhide it as I wish? > > > It is not hidden, in fact, you get to name it... > > class foo: > def goo(I_AM_SELF, arg): > pass > Cool! >>25. A fully implemented .NET counterpart (I should be able to write >>Python scripts for both with the same code) > > > Check IronPython and PythonNET > Not fully implemented, but I guess that will have to suffice. > >>26. How easily can other languages access it and vice versa? > > > C and C++ are easy. There is a TCL interface. > > Anything with C or C++ interfaces are arguably trivial to talk to. > I guess D should work then. > >>27. The option of mixing in static typing > > > Python has no static typing. > Argg! > >>28. Automatic type coercion > > > Certain kinds of things can do what is known as "type coercion" in other > languages. What kinds of coercion did you want to do. > I'd like to be able to use a string as an integer without an explicit coerion on my part for example. > >>29. Is Python designed in such a way that I may merely "plugin" a >>C/C++/Java/D module which will then allow for mixing their syntax and >>perhaps even access to their facilities within Python? > > > You can call C/C++ functions in Python (a large portion of the standard > library is implemented in C). > > Jython allows nearly transparent use of Python and Java. > > You don't get other language syntaxes, generally. > > >>30. Messaging syntax such as : [myColor setRed:0.0 green:0.5 blue:1.0] >>or [dog bring:paper to:me] and [[myAunt phone] setTo:[myUncle phone]] >><--- Nested messages and [dog perform:sel_get_uid("bark")] which is the >>same as [dog bark] > > > We don't do messaging syntax. Combining messaging and object-oriented > syntax would make for an ugly language. Ugly? I disagree, but hey, what do I know? Objective-C is OOP and messaging is awesome. I love Python though, a hybrid between the two would be great. > > >>31. Concepts of Protocols (whereby one may organize related methods into >>groups and check whether a particular object implements the methods >>within this protocol), or Interfaces similar to those in Java whereby >>classes or objects which implement the interface (sign the contract) >>must implement the methods and attributes as specified in the interface, >>and/or programming by contract such as in Eiffel (see: >>http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=595) > > > No. Test-driven development is the norm in Python. > That is quite a shame, no modules for this either huh? >>34. In pure Python, can I change and add new constructs to the Python >>syntax? > > > Yes, if you are willing to work for it. > I expect the docs will tell me how to do this. > >>35. May I modify the garbage collector? > > > If you really want, though it already works fine. > Oh, I just like to play with garbage collectors. It's a kind of fettish of mine. > >>37. Dynamic dispatch > > > This could mean a few different things. > Like virtual functions in C++ >>41. How easy is it to port my Python code to C/C++/C# or Java? > > > Depends on how experienced you are with those languages. > What I actually meant was are there any facilities (built-in or modules) which allow for automatic compilation to C/C++/C#/D. For example, particular Smalltalk distros compile to C as does ObjC. > >>42. The ability to assign a method(s) to a collection/group of objects >>[with a particular signature i.e.] > > > No. > That's no good. I wonder if I could implement this myself with minimum pain. > >>43. Embedding variables in strings like: print "Hello, World. Time: >>#{Time.now}" > > > t = time.asctime() > print "Hello World %(t)s"%{'t':t} > print "Hello World %(t)s"%locals() > That is messy, exactly why I wanted the kind of clear embedding I gave an example for. Oh well. > >>44. Case or Switch statements with functionality as such: >>case score >>when 0...40 >> puts "Horrible!" >>when 40...60 >> puts "Poor" >>when 60...80 >> puts "You can do better!" >>when 80...95 >> puts "Now that's acceptable" >>when 95..100 >> puts "That the best you can do? j/k" >>else >> puts "Didn't take the test?" >>end > > > No. > Really? Hmmmm, does anyone know of a bridge between Python and Ruby? ---------------- Thanks Josiah. I'm perusing the docs right now. From pcooke at philc.net Tue Oct 19 01:49:35 2004 From: pcooke at philc.net (PhilC) Date: Tue, 19 Oct 2004 01:49:35 -0400 Subject: Latest PIL installer failed to install. References: <5g68n0hgiiq80smabt3rdcn7j6ruv6rl6v@4ax.com> Message-ID: Its OK I got it :) Manually edited the registry. Needs the full path. Well DUH!!! I hear you say. Its all a learning process :)) PhilC From jerf at jerf.org Thu Oct 28 14:50:12 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 28 Oct 2004 18:50:12 GMT Subject: Data::Dumper for Python References: Message-ID: On Thu, 28 Oct 2004 18:06:12 +0000, Dave Benjamin wrote: > Take a look at the "pprint" module. Also, it's worth noting that the Python > interpreter prints representations of data structures all the time, no > library required: However, Python tries ***much*** less hard to make those representations actually evaluate back to equivalent objects. Based on my experiences but with no particular knowledge of the history of the two languages in this regard, this is because Python makes many manipulations easy that are hard to borderline impossible in Perl, and it is much harder to create such representations in general. As a result, repr of any but the most base classes is often used more for "debugging style" info, and str for a simple identification. It is not safe in general to eval(repr(obj)) and expect anything but a Syntax Error. Python shuffles that task off to the Pickle module, which is what you'd want to look up in the docs. That splits human representation off from computer-reproducable representation, and I believe overall this is superior; the two are not the same. In addition, we then get the Pickle protocol extensions which are frequently quite handy, especially when dealing with weakrefs. From vincent at visualtrans.de Wed Oct 27 11:01:09 2004 From: vincent at visualtrans.de (Vincent Wehren) Date: Wed, 27 Oct 2004 17:01:09 +0200 Subject: look further down sys.path for extension module Message-ID: Hi, Is it possible to have Python look further down sys.path for a C extension module when an ImportError is raised because of the "dynamic module not implementing init function"? The thing is, I have a case where the cwd of an application that embedds the Python interpreter needs to be inserted into sys.path at index. For the windows version there is a zlib.dll in the app's directory, which - naturally - gets "import precedence" over zlib.pyd from the DLLs directory. For the time being, I place copy zlib.pyd into he app's directory to solve the problem, but it would be nice if there was a way to avoid having to do this. Any thoughts much appreciated. -- Vincent Wehren From carribeiro at gmail.com Wed Oct 6 11:05:17 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 6 Oct 2004 12:05:17 -0300 Subject: Re-executing the code object from a class 'declaration' In-Reply-To: <1gl8lg2.axf8gd9hwlbmN%aleaxit@yahoo.com> References: <1gl8dkd.1mk43di1xi6v0dN%aleaxit@yahoo.com> <1gl8lg2.axf8gd9hwlbmN%aleaxit@yahoo.com> Message-ID: <864d370904100608058b60c8b@mail.gmail.com> On Wed, 6 Oct 2004 14:06:23 +0200, Alex Martelli wrote: > Urk. Ahem, I mean, interesting solution. I _think_ it poses certain, > ahem, problems, such as infinite recursion if a call to re_execute is in > the same code object as that where the 'class MyClass' is, for example > -- because basically you ARE re-executing the whole kaboodle. You're > not just re-executing the 'class' statement, but everything that comes > before or after it in the same containing codeobject. Your tests in an > interactive interpreter are tricky that way, because in that special > environment a code object is a tiny little thing. But stick this into a > module and place a dis.dis(dct['my_code']) in the metaclass's __new__ > and you'll see that basically MyClass.re_execute isn't very different > from a reload of the module. Isn't that a _bit_ too much in general? (repeating to myself: dis is your friend. dis is your friend). Well, it seems that I'm running out of options. I've checked dis, and done a few more tests. I found a way to find the correct code object for the _body_ of the class statement (or at least I think so), but this does not solve the problem, as it will be shown below: ------------- import inspect import dis import time import types class Meta(type): def __new__(klass, name, bases, dct): caller = inspect.stack(0)[1] caller_code = caller[0].f_code caller_filename = caller[1] caller_lineno = caller[2] print "Caller info: ", caller_filename, caller_lineno, caller_code print dis.dis(caller[0].f_code) for code in caller_code.co_consts: if isinstance(code, types.CodeType): if (code.co_filename == caller_filename) and \ (code.co_firstlineno == caller_lineno): print "found!", code.co_name dct['my_code'] = code return type(name, bases, dct) class MyClass(object): __metaclass__ = Meta creation_time = time.ctime() print "I'm inside my class definition!" def re_execute(klass): exec klass.my_code return MyClass re_execute = classmethod(re_execute) ------------- The code checks the filename and the line number to find the correct code object. It could also check the class name, just to make sure that everything matches. It isn't needed, as far as I know. But the problem is that the code block that is found refers to the class _body_ only. Checking dis.dis() helps to understand it: 27 64 LOAD_CONST 4 ('MyClass') 67 BUILD_TUPLE 0 70 LOAD_CONST 5 () 73 MAKE_FUNCTION 0 76 CALL_FUNCTION 0 79 BUILD_CLASS 80 STORE_NAME 7 (MyClass) There is not a single code block that does all the tasks related to the class statement, and only it. In fact, there are two different code objects to choose from, and neither really solves the problem. One is the module object; as you've pointed out, it's too generic and executes too much stuff, not just the class statement. The other one is the referred to in the dis() output above, that is the _body_ of the class statement. Calling it doesn't call the metaclass, and neither does the name binding 'magic': >>> exec MyClass.my_code I'm inside my class definition! # it does not print any of the debug messages in the metaclass, and it's obvious why It also doesn't take into account that the class may have base classes. For example, changing the statement to 'class MyClass(object)', the compiled code looks like this: 27 64 LOAD_CONST 4 ('MyClass') 67 LOAD_NAME 7 (object) 70 BUILD_TUPLE 1 >From this point, few options are left. What I need to execute is in fact a part of the module code object -- just one line of it, that's the code that wraps the entire class statement. Besides giving up (which is a reasonable option, given the constraints), what is left are some horrible hacks. (I'm don't feel like discussing it here; it's like Mordor Black Speech, if shall not be uttered in a public forum :-). BTW, the two code objects represent exactly the two alternative solutions that can be done using only pure Python code: 1) reload the entire module (which is nearly equivalent to calling the module code object, with the difference that it doesn't reload and recompile the actual source code) 2) enclose the class statement inside a def, and run the def to obtain the class template: def BuildTemplate(