dateutil 1.4
Version 1.4 of dateutil is out: http://labix.org/python-dateutil Changes since 1.3 - - Fixed another parser precision problem on conversion of decimal seconds to microseconds, as reported by Erik Brown. Now these issues are gone for real since it's not using floating point arithmetic anymore. - Fixed case where tzrange.utcoffset and tzrange.dst() might fail due to a date being used where a datetime was expected (reported and fixed by Lennart Regebro). - Prevent tzstr from introducing daylight timings in strings that didn't specify them (reported by Lennart Regebro). - Calls like gettz(GMT+3) and gettz(UTC-2) will now return the expected values, instead of the TZ variable behavior. - Fixed DST signal handling in zoneinfo files. Reported by Nicholas F. Fabry and John-Mark Gurney. What is it? --- The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. Features * Computing of relative deltas (next month, next year, next monday, last week of month, and a lot more); * Computing of relative deltas between two given date and/or datetime objects; * Computing of dates based on very flexible recurrence rules (every month, every week on Thursday and Friday, every Friday 13th, and a *LOT* more), using a superset of the iCalendar RFC specification. Parsing of RFC strings is supported as well. * Generic parsing of dates in almost any string format; * Timezone (tzinfo) implementations for tzfile(5) format files (/etc/localtime, /usr/share/zoneinfo, etc), TZ environment string (in all known formats), iCalendar format files, given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, UTC timezone, and Windows registry-based timezones. * Internal up-to-date world timezone information based on Olson's database. * Computing of Easter Sunday dates for any given year, using Western, Orthodox or Julian algorithms; * More than 400 test cases. -- Gustavo Niemeyer http://niemeyer.net -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ikaaro 0.20.4 released
This is a Content Management System built on Python itools, among other features ikaaro provides: - content and document management (indexsearch, metadata, etc.) - multilingual user interfaces and content - high level modules: wiki, forum, tracker, etc. This release brings a number of usability enhancements. Most important, the old HTML editor derived from Epoz [1] has been replaced by TinyMCE [2]. [1] http://iungo.org/products/Epoz/ [2] http://tinymce.moxiecode.com/ Resources - Download http://download.ikaaro.org/ikaaro/ikaaro-0.20.4.tar.gz Home http://www.ikaaro.org/ikaaro Mailing list http://mail.ikaaro.org/mailman/listinfo/itools Bug Tracker http://bugs.ikaaro.org/ -- J. David Ibáñez Itaapy http://www.itaapy.com Tel +33 (0)1 42 23 67 45 9 rue Darwin, 75018 Paris Fax +33 (0)1 53 28 27 88 -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Pythons Ladders
On Feb 28, 1:10 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 27 Feb 2008 19:18:27 -0800, Jeff Schwab wrote: Benoit wrote: I've been teaching myself the python language over the past few months using Mark Lutz' Learning Python, 3ed. Python is also the first programming language I've ever taken up. I find the language easy to learn and rather productive in relation to the introductory course on C ++ I'd begun in January for fun @ school (we're practicing dynamic arrays using pointers... kill me now). Get a better teacher, if you can. Please do me a personal favor: Don't hold the crappy course against C++. For the record, you should never have to manage dynamically allocated arrays manually, nor store pointers to them. Try the std::vector template, and post in comp.lang.c++ if have any trouble. Hey a flame bait. I'll bite. This a bit of an overreaction unless you know what the course was about. If the goal is to learn about the computer and that basically everything is a number in the end, then C is a good choice. More portable than assembler but nearly as close to the metal. To the OP: If you try C++, don't hold that crappy language against C#, D, or Java. ;-) Ciao, Marc 'BlackJack' Rintsch Welcome! This is the self-proclaimed 'impossible and useless' guy. Since you're in to TMLs, try escaping a text file with a small subset of characters, so that it's readable with a browser. Say by replacing all the ampersands with amp;, the line breaks with p, and maybe even a 'list' with lis. (That went easy, moderate, hard.) Then, for impossible, do it without (I repeat, WITHOUT) reading the whole file into memory, say only 32 characters at a time. Sadly, even at teenages, specializations you make affect your specializations later. There's no best specialization priority, and $$ $ned if I'm picking yours. Mine gets me here; that's all I can know. Electives or bust! Anyway, Marc is right. Python teaches you a lot about programming, but C teaches you a lot about computers. More generally, you can write in one line in one language what takes hundreds in another, but in one line in that one what's impossible in the first. It's -your- - day-; allegretto: meter's running. -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] writes: For implementing this in Python you have to carry an is allowed to be coerced to float flag with every integer object to decide at run time if it is an error to add it to a float or not. Yeah, I guess it's not workable in a dynamic language. Hmm. Well I could think of some crazy ways to do it. Or you make Python into a statically typed language like Haskell. But then it's not Python anymore IMHO. There are some languages like Boo, that are sort of halfway between Python and Haskell, so maybe that kind of idea could be used in them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Place n indistinguishable items into k distinguishable boxes
On Feb 27, 8:47 pm, Michael Robertson [EMAIL PROTECTED] wrote: Michael Robertson wrote the following on 02/27/2008 06:40 PM: Hi, I need a generator which produces all ways to place n indistinguishable items into k distinguishable boxes. My first thought was to generate all integer partitions of n, and then generate all permutations on k elements. So: Two more cents: 4 = 4 = 3 + 1 = 2 + 2 = 2 + 1 + 1 And if |x| k, discard it. For k= 1, you'd stop after 4 = 4. Reads below. Ah, you said that. Also make sure you stop at floor( k/ 2 ), so you don't get 4 = 1 + 3. Then for 4, generate all permutations of x=(4,0,0,..), |x|=k Then for 3,1 generate all permutations of x=(3,1,0,..), |x|=k Then for 2,2 generate all permutations of x=(2,2,0...), |x|=k ... Your only casualty here is all the zeroes in (4,0,0,..). You don't want to swap k_2 and k_3 in (4,0,0). (Is that what permutation means?) In addition to having to generate permutations for each integer partition, I'd have to ignore all integer partitions which had more than k parts...this seemed like a bad way to go (bad as in horribly inefficient). Better ideas are appreciated. Running time on my recursive was K** 2* N, counting the copy, I think. sum( 1..i )== i( i+ 1 )/ 2, O( i** 2 ). My iterative was slower, K** 3* N, unless you save a K or N in the small length of K early on, I think. Did anyone take this course that can tell me? -- http://mail.python.org/mailman/listinfo/python-list
Re: threading/Queue: join() and task_done() not working? (deadlock)
7stud bbxx789_05ss at yahoo.com writes: What is task_done()? The python docs don't list any such function. I'm using Python 2.5 and it's in the docs ... -- http://mail.python.org/mailman/listinfo/python-list
Re: threading/Queue: join() and task_done() not working? (deadlock)
Dennis Lee Bieber wlfraed at ix.netcom.com writes: I didn't even know Queue objects /had/ a join() method... The only .join() I'm familiar with is the one that waits for a thread to complete... G Well it's probably new in Python 2.5 although I'm not sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: is there enough information?
On Feb 28, 2:30 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote: It is time to show your cards or fold Here. Run it. Download Python 3.0a2. from thread import start_new_thread as launch from threading import Lock import time from functools import partial class WithObj: def __init__( self, enter, exit ): self.__enter__, self.__exit__= enter, exit class Step: def __init__( self ): self._index= 0 self._locks= {} self._opened= False self._oplock= Lock() def __getitem__( self, index ): with self._oplock: lock= self._locks.get( index, None ) if None is lock: lock= self._locks[ index ]= Lock() if index!= self._index: assert lock.acquire( False ) return WithObj( partial( self.ienter, index ), partial( self.iexit, index ) ) def ienter( self, index ): with self._oplock: if self._opened: return self lock= self._locks.get( index ) assert lock.acquire() with self._oplock: return self def iexit( self, index, *a ): with self._oplock: self._index+= 1 lock= self._locks.get( self._index ) if None is not lock: lock.acquire( False ) lock.release() def complete( self ): with self._oplock: self._index= 0 lock= self._locks.get( 0 ) if None is not lock: lock.acquire( False ) lock.release() def open( self ): with self._oplock: self._opened= True for lock in self._locks.values(): lock.acquire( False ) lock.release() class CustThread: count= 0 def __init__( self ): CustThread.count+= 1 self.id= CustThread.count self.step= Step() self.cont= True self.cmd= None self.ret= None def __repr__( self ): return 'CustThread %i'% self.id def thloop( thd ): while thd.cont: with thd.step[1]: if not thd.cont: break print( 'step 1', end= ' ' ) thd.ret= thd.cmd+ 1 with thd.step[3]: print( 'step 3' ) thd.ret= None thd.step.complete() def op100( thd ): with thd.step[0]: print( 'step 0', end= ' ' ) thd.cmd= 100 with thd.step[2]: print( 'step 2', end= ' ' ) ret1= thd.ret assert ret1== 101 def main( func ): if __name__== '__main__': func() @main def fmain(): class Case: def __init__( self ): self.th1= CustThread() while 1: print( '===' ) class Case1: case= Case() launch( thloop, ( case.th1, ) ) for _ in range( 10 ): case.th1.cmd= None case.th1.ret= None op100( case.th1 ) case.th1.cont= False case.th1.step.open() print( 'case complete' ) while 1: time.sleep( 1 ) What results do you get on your computer? -- http://mail.python.org/mailman/listinfo/python-list
Re: threading/Queue: join() and task_done() not working? (deadlock)
Raymond Hettinger python at rcn.com writes: Does the problem persist with a queue size of 2? Raymond Unfortunately yes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about PyPI and 'easy_install'
makoto kuwata wrote: Your patch shows that both project name (Tenjin) and package name (pyTenjin) should be the same name. And, I'm afraid that your patch seems to require user to install setuptools. I want Tenjin to be install not only with easy_install but also without setuptools. You should be able to just change the name and not need to use setuptools in the setup.py Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IRC Zork
Kris Davidson wrote: If this has been done before in another language could someone please tell me, if not I was wondering is its possible and what the easier way is to create an IRC bot that allows you to play Zork: I was thinking of just creating a simple Python IRC bot or finding an existing one then have it run Zork and read/write from stdout/stdin. Is that possible? Is there a better or easier way to do it? Are there any existing programs that do something similar? Or just really anything else people have to say on the subject. The easiest way would be to start with a standalone Z-code interpreter that does just basic stdin/stdout transactions, get a licensed copy of the Zork data set, and hook it up via a subprocess -- in other words, just what you suggest. I haven't done recent surveys, but there are _many_ portable Z machine interpreters such that I'm sure one or two would suffice. (You'd also have to play buffering/fcntl games to make sure that it doesn't block, but those are in the details.) The bigger picture would be writing a full Z machine in Python, which is something I embarked on for my own amusement a while back but never got far enough to do anything useful at all, given the size of the task. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM, Y!M erikmaxfrancis Wyrd has swept all my kin / all the brave chiefs away! / Now I must follow them! -- Beowulf -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
Marc 'BlackJack' Rintsch wrote: On Wed, 27 Feb 2008 19:18:27 -0800, Jeff Schwab wrote: Benoit wrote: I've been teaching myself the python language over the past few months using Mark Lutz' Learning Python, 3ed. Python is also the first programming language I've ever taken up. I find the language easy to learn and rather productive in relation to the introductory course on C ++ I'd begun in January for fun @ school (we're practicing dynamic arrays using pointers... kill me now). Get a better teacher, if you can. Please do me a personal favor: Don't hold the crappy course against C++. For the record, you should never have to manage dynamically allocated arrays manually, nor store pointers to them. Try the std::vector template, and post in comp.lang.c++ if have any trouble. Hey a flame bait. I'll bite. This a bit of an overreaction unless you know what the course was about. If the goal is to learn about the computer and that basically everything is a number in the end, then C is a good choice. More portable than assembler but nearly as close to the metal. To the OP: If you try C++, don't hold that crappy language against C#, D, or Java. ;-) He was talking about C++, not C. Jeff has quite a good point; teaching C++ as C is not terribly useful. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM, Y!M erikmaxfrancis Wyrd has swept all my kin / all the brave chiefs away! / Now I must follow them! -- Beowulf -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 00:30:11 -0800, Dennis Lee Bieber wrote: On Thu, 28 Feb 2008 01:25:32 -, Steven D'Aprano [EMAIL PROTECTED] declaimed the following in comp.lang.python: When it comes to mixed arithmetic, it's just too darn inconvenient to forbid automatic conversions. Otherwise you end up either forbidding things like 1 + 1.0 on the basis that it isn't clear whether the programmer wants an int result or a float result, or else even more complex rules (if the left operator is an int, and the result of the addition has a zero floating-point part, then the result is an int, otherwise it's an error, but if the left operator is a float, the result is always a float). Or a proliferation of operators, with integer and floating point versions of everything. Automatic conversions, okay... but converting a result when all inputs are of one time, NO... What? How does that make any sense? By that logic, we should see this: len(a string) '8' len([2, 4, 6]) [3] len({'key': 'value'}) {1: None} The only rule needed is very simple: promote simpler types to the more complex type involved in the current expression (with expression defined as value operator value -- so (1/2) * 3.0 is INTEGER 1/2, resultant 0 then promoted to float 0.0 to be compatible with 3.0). Very simple rule, used by very many traditional programming languages. And rightly rejected by many other programming languages, including modern Python, not to mention calculators, real mathematics and common sense. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Place n indistinguishable items into k distinguishable boxes
[EMAIL PROTECTED] wrote the following on 02/28/2008 12:36 AM: On Feb 27, 8:47 pm, Michael Robertson [EMAIL PROTECTED] wrote: Your only casualty here is all the zeroes in (4,0,0,..). You don't want to swap k_2 and k_3 in (4,0,0). (Is that what permutation means?) Correct. Though by 'permutation', I meant 'permutations with repetitions'---so the algorithm would have handled that. In addition to having to generate permutations for each integer partition, I'd have to ignore all integer partitions which had more than k parts...this seemed like a bad way to go (bad as in horribly inefficient). Better ideas are appreciated. Running time on my recursive was K** 2* N, counting the copy, I think. sum( 1..i )== i( i+ 1 )/ 2, O( i** 2 ). My iterative was slower, K** 3* N, unless you save a K or N in the small length of K early on, I think. Did anyone take this course that can tell me? Thanks again for your efforts here. This particular problem didn't appear in any course I took...certainly similar problems did. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Thanks so much Gabriel. -- http://mail.python.org/mailman/listinfo/python-list
more pythonic
Hello. There is a Django application, i need to place all its data into Access mdb file and send it to user. It seems to me that params filling for statement could be expressed in a more beautiful way. Since i'm very new to Python, i don't feel that, though. Could you tell your opinion on that snippet? code sql = insert into salesmanager (employeeid, name, officelocation, departmentname, salary) values (?, ?, ?, ?, ?); params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) curs.executemany(sql, params) /code -- http://mail.python.org/mailman/listinfo/python-list
Re: threading/Queue: join() and task_done() not working? (deadlock)
On Feb 28, 1:47 am, Gal Aviel [EMAIL PROTECTED] wrote: 7stud bbxx789_05ss at yahoo.com writes: What is task_done()? The python docs don't list any such function. I'm using Python 2.5 and it's in the docs ... According to the docs, join() unblocks only after you call task_done() for every item that was entered into the Queue. However, just because the Queue size is 1 doesn't mean there aren't other items waiting to be added to the Queue. With one item in the Queue, presumably the task-count is 1. But, if you get() an item out of the Queue and another item is waiting to be added to the Queue, then it seems likely that the task_count will jump to 2 immediately after calling get(). Thereafter, a call to task_done() will decrement the task_count to 1, which means join() will continue blocking. Please recognize that it is very difficult to debug imaginary code. If you want some help that is more relevant, then post a short example that demonstrates your problem. Do not post some lengthy program with cryptic variable names. -- http://mail.python.org/mailman/listinfo/python-list
Re: more pythonic
On Feb 28, 4:40 am, Temoto [EMAIL PROTECTED] wrote: Hello. There is a Django application, i need to place all its data into Access mdb file and send it to user. It seems to me that params filling for statement could be expressed in a more beautiful way. Since i'm very new to Python, i don't feel that, though. Could you tell your opinion on that snippet? code sql = insert into salesmanager (employeeid, name, officelocation, departmentname, salary) values (?, ?, ?, ?, ?); params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) curs.executemany(sql, params) /code It's my understanding that the way you insert arguments into queries has to be done in a db specific way. If done in that way, your queries will be protected against sql injection attacks, AND the query strings will be constructed in a more efficient manner. -- http://mail.python.org/mailman/listinfo/python-list
Re: more pythonic
On Feb 28, 4:48 am, 7stud [EMAIL PROTECTED] wrote: It's my understanding that the way you insert arguments into queries has to be done in a db specific way. Rather: It's my understanding that the way you insert arguments into queries *should* be done in a db specific way. -- http://mail.python.org/mailman/listinfo/python-list
Re: Official IRC channel for Python?
I saw bad guys on IRC a few days ago, but it was not a problem because Ignore user function in IRC client makes his/her messages invisible. BTW,who's the maintainer of the channel? On 27 Feb 2008 11:34:54 -0800, Paul Rubin http://phr.cx@nospam.invalid wrote: Guilherme Polo [EMAIL PROTECTED] writes: I can join #perl, #php, #ruby, #mysql, #postgres without registration. What advantage does it have? and the advantage really worth? The direct benefit is a probability of having less spam, and things like that. I don't remember ever seeing irc spam on freenode. I see it once in a while on undernet. This is a non-problem. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: more pythonic
On Feb 28, 5:40 am, Temoto [EMAIL PROTECTED] wrote: Hello. There is a Django application, i need to place all its data into Access mdb file and send it to user. It seems to me that params filling for statement could be expressed in a more beautiful way. Since i'm very new to Python, i don't feel that, though. Could you tell your opinion on that snippet? code sql = insert into salesmanager (employeeid, name, officelocation, departmentname, salary) values (?, ?, ?, ?, ?); params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) curs.executemany(sql, params) /code Replace: params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) With this list comprehension: params = [ (mgr.id, mgr.name, mgr.office, mgr.department, mgr.salary) for mgr in Manager.objects.all() ] But the technique you are using, of creating a params list instead of doing explicit string construction, IS the safe SQL-injection- resistant way to do this. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
URLlib2?
Hi, Probably a silly question but I am writing a CGI script which need to check the referring URL, can anyone provide any pointers? I have looked at URLLib2 and a couple of other libraries, but am slightly confused. Thanks in advance, rod -- http://mail.python.org/mailman/listinfo/python-list
Re: URLlib2?
rodmc napisał(a): Probably a silly question but I am writing a CGI script which need to check the referring URL, can anyone provide any pointers? I have looked at URLLib2 and a couple of other libraries, but am slightly confused. Using httplib you can issue HEAD request to check if it does not return 404 response, but this works only with HTTP/HTTPS urls. -- Jarek Zgoda Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101 We read Knuth so you don't have to. (Tim Peters) -- http://mail.python.org/mailman/listinfo/python-list
Re: call by reference howto????
[EMAIL PROTECTED] wrote: On Feb 27, 10:38 pm, Dan Bishop [EMAIL PROTECTED] wrote: What exactly are you wanting to do? I'm having a hard time considering your question in the general case. I'm thinking of too many cases, the details of which are relevant to the answer, to even subdivide them. My specialty is specific application; I know ten tricks that apply 10% of the time each. I can show you all of them but not at once! When you have nothing to say it's normally best not to say it. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Nested module import clutters package namespace?
Hi! I'd be grateful for help with a problem of package and module namespaces. The behaviour I observe is unexpected (to me), and I couldn't find the answer in the docs, the tutorial, or the mailing list archive. So here we go: I have a package named 'pack'. Apart from the '__init__.py' file the directory contains two modules 'x.py' and 'y.py': pack/ __init__.py x.py y.py The files have the following contents: __init__.py import x = x.py === import y = y.py === pass = I then do import pack This (1) introduces variable 'x' bound to module 'pack.x' in pack's namespace (expected) (2) introduces variable 'q' bound to module 'pack.y' in x's namespace (expected) but also (3) introduces variable 'y' bound to module 'pack.y' in pack's namespace (*totally unexpected*) The problem is so bad as to even overwrite any variable 'y' that might have existed in pack's namespace before the import. I created verbose versions of the three files above to illustrate what happens (see below.) The do exactly the same as above, but print out what they do. This is the output: -snip--- import pack pack: Here is pack. pack: I now assign y='hello'. pack: My y is now: 'hello' pack: I now 'import x' which in turn does 'import y as q'. x: Here is x. x: I now 'import y as q'. y: Here is y. pack: My y is now: module 'pack.y' from 'pack/y.pyc' pack: Why? snip- I know that any import creates an entry in sys.modules. So 'pack', 'pack.x' and 'pack.y' get created in sys.modules. That's fine. Apart from that, an import statement should act equivalent to an assignment: it should introduce entries to the local namespace of th emodule it appears in. The 'import y as q' appears in x.py, so it should add entries to x's namespace *only*. But why is variable 'y' in pack's namespace overwritten by the import in x? Thank you very much in advance, Best, Rüdiger P.S.: These are the files that produce the verbose output: __init__.py print pack: Here is pack. print pack: I now assign y='hello'. y=hello print pack: My y is now:, repr(y) print pack: I now 'import x' which in turn does 'import y as q'. import x print pack: My y is now:, repr(y) print pack: Why? = x.py === print ' x: Here is x.' print x: I now 'import y as q'. import y as q = y.py === print 'y: Here is y.' = -- Dr. Rüdiger Kupper Honda Research Institute Europe GmbH Carl-Legien-Straße 30 D-63073 Offenbach/Main, Germany Phone : +049 (0)69-890 11-725 Fax : +049 (0)69-890 11-749 E-Mail: [EMAIL PROTECTED] PGP ID: C2303358 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IRC Zork
The bigger picture would be writing a full Z machine in Python, which is something I embarked on for my own amusement a while back but never got far enough to do anything useful at all, given the size of the task. Might be worth trying that or setting up a project somewhere, do any exist? Have you posted what code you had somewhere? -- http://mail.python.org/mailman/listinfo/python-list
Re: URLlib2?
Jarek Zgoda wrote: rodmc napisał(a): Probably a silly question but I am writing a CGI script which need to check the referring URL, can anyone provide any pointers? I have looked at URLLib2 and a couple of other libraries, but am slightly confused. Using httplib you can issue HEAD request to check if it does not return 404 response, but this works only with HTTP/HTTPS urls. It's unlikely that any other type of URL would result in the browser sending a Referer: header. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
RE: anydbm safe for simultaneous writes?
Chris wrote: I need simple data persistence for a cgi application that will be used potentially by multiple clients simultaneously. So I need something that can handle locking among writes. Sqlite probably does this, but I am using Python 2.4.4, which does not include sqlite. The dbm-style modules would probably be fine, but I have no idea if they are write safe (I have no experience with the underlying unix stuff). Any tips appreciated. No, you cannot assume that this will work without locking. Locking is not trivial to do in Python. And, even with a working locking mechanism, you still have to invalidate the in-memory caches any time a write to the database is done. Futher, most dbm modules do not have ACID properties. I suggest intalling the pysqlite module and using it, regardless of your version of CPython. According to pysqlite developer, the version of pysqlite included in CPython 2.5 is old. - Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: non-sequitur: Re: Python-URL! - weekly Python news and links (Feb 18)
Dennis Lee Bieber wrote: On Wed, 27 Feb 2008 13:38:59 +0100, Peter Otten [EMAIL PROTECTED] declaimed the following in comp.lang.python: My google is better than yours then: Why am I visualizing a face off in a super cheap martial arts movie? Python-style kung fu? And the winner is ... http://google-fight.com/index.php?lang=en_GBword1=Piet+van+Oostrumword2=Peter+Otten regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: URLlib2?
Steve Holden napisał(a): Probably a silly question but I am writing a CGI script which need to check the referring URL, can anyone provide any pointers? I have looked at URLLib2 and a couple of other libraries, but am slightly confused. Using httplib you can issue HEAD request to check if it does not return 404 response, but this works only with HTTP/HTTPS urls. It's unlikely that any other type of URL would result in the browser sending a Referer: header. Right, perfectly valid assumption. ;) I am bit too defensive today. -- Jarek Zgoda Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101 We read Knuth so you don't have to. (Tim Peters) -- http://mail.python.org/mailman/listinfo/python-list
message entry box at center
from Tkinter import * def callback(): print e.get() master=Tk() e=Entry(master) e.pack(anchor=CENTER) e.focus_set() b=Button(master,text=get,width=10,command=callback) b.pack(anchor=CENTER) master.mainloop() i want to show the entry button at the center of the window. How is it possible ?? -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentation and optional delimiters
On Feb 28, 12:46 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: By the way bearophile... the readability of your posts will increase a LOT if you break it up into paragraphs, rather than use one or two giant run-on paragraphs. My comments follow. On Tue, 26 Feb 2008 15:22:16 -0800, bearophileHUGS wrote: Steven D'Aprano: Usability for beginners is a good thing, but not at the expense of teaching them the right way to do things. Insisting on explicit requests before copying data is a *good* thing. If it's a gotcha for newbies, that's just a sign that newbies don't know the Right Way from the Wrong Way yet. The solution is to teach them, not to compromise on the Wrong Way. I don't want to write code where the following is possible: ... ... suddenly my code hits an unexpected performance drop ... as gigabytes of data get duplicated I understand your point of view, and I tend to agree. But let me express my other point of view. Computer languages are a way to ask a machine to do some job. As time passes, computers become faster, But never fast enough, because as they get faster, we demand more from them. and people find that it becomes possible to create languages that are higher level, that is often more distant from how the CPU actually performs the job, allowing the human to express the job in a way closer to how less trained humans talk to each other and perform jobs. Yes, but in practice, there is always a gap between what we say and what we mean. The discipline of having to write down precisely what we mean is not something that will ever go away -- all we can do is use bigger concepts, and thus change the places where we have to be precise. e.g. the difference between writing index = 0 while index len(seq): do_something_with(seq[index]) index += 1 and for x in seq: do_something_with(x) is that iterating over an object is, in some sense, a bigger concept than merely indexing into an array. If seq happens to be an appropriately- written tree structure, the same for-loop will work, while the while loop probably won't. Probably many years ago a language like Python was too much costly in terms of CPU, making it of little use for most non-toy purposes. But there's a need for higher level computer languages. Today Ruby is a bit higher-level than Python (despite being rather close). So my mostly alternative answers to your problem are: 1) The code goes slow if you try to perform that operation? It means the JIT is broken, and we have to find a smarter JIT (and the user will look for a better language). [...] Of course I expect that languages will continue to get smarter, but there will always be a gap between Do What I Say and Do What I Mean. It may also turn out that, in the future, I won't care about Python4000 copying ten gigabytes of data unexpectedly, because copying 10GB will be a trivial operation. But I will care about it copying 100 petabytes of data unexpectedly, and complain that Python4000 is slower than G. The thing is, make-another-copy and make-another-reference are semantically different things: they mean something different. Expecting the compiler to tell whether I want x = y to make a copy or to make another reference is never going to work, not without running import telepathy first. All you can do is shift the Gotcha! moment around. You should read this article: http://www.joelonsoftware.com/articles/fog000319.html It specifically talks about C, but it's relevant to Python, and all hypothetical future languages. Think about string concatenation in Python. A higher level language means that the user is more free to ignore what's under the hood, the user just cares that the machine will perform the job, regardless how, the user focuses the mind on what job to do, the low level details regarding how to do it are left to the machine. More free, yes. Completely free, no. Despite that I think today lot of people that have a 3GHZ CPU that may accept to use a language 5 times slower than Python, that for example uses base-10 floating point numbers (they are different from Python Decimal numbers). Almost every day on the Python newsgroup a newbie asks if the round() is broken seeing this: round(1/3.0, 2) 0.33002 A higher level language (like Mathematica) must be designed to give more numerically correct answers, even if it may require more CPU. But such language isn't just for newbies: if I write a 10 lines program that has to print 100 lines of numbers I want it to reduce my coding time, avoiding me to think about base-2 floating point numbers. Sure. But all you're doing is moving the Gotcha around. Now newbies will start asking why (2**0.5)**2 doesn't give 2 exactly when (2*0.5)*2 does. And if you fix that by creating a surd data type, at more performance cost, you'll create a different Gotcha
Re: How about adding rational fraction to Python?
On Feb 28, 3:30 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote: Automatic conversions, okay... but converting a result when all inputs are of one time, NO... People, this is so cognitive dissonance it's not even funny. There is absolutely nothing obvious about 1/2 returning a number that isn't at least approximately equal to one half. There is nothing self- evident about operations maintaining types. You people can't tell the difference between obvious and learned conventions that came about because in limitations in the hardware at the time. Nobody would have come up with a silly rule like x op y must always have the same type as x and y if computer hardware had been up to the task when these languages were created. Very simple rule, used by very many traditional programming languages. I'd be interested in hearing what languages those are. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Implemented all your suggestions, with two exceptions. Changed file read to readlines(), but not open(...).readlines(). I love to say file.close(). Gives me a feeling of security. (We could discuss RAM waste v. I/O speed but this input file is just 10KB, so neither matters.) Removed one of the three globals, but left the other two. Couldn't see any real advantage to passing poor 'ofile' from hand to hand (writeHTML() to writeBody() to writeEntries() ...) as opposed to letting him rest easy in his chair, doing a little writing when called. Also changed the opening doc comment to give you appropriate credit. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On 2008-02-28, Carl Banks [EMAIL PROTECTED] wrote: Automatic conversions, okay... but converting a result when all inputs are of one time, NO... People, this is so cognitive dissonance it's not even funny. There is absolutely nothing obvious about 1/2 returning a number that isn't at least approximately equal to one half. I guess obviousness is in the eye of the beholder. To me it's obvious that 1 and 2 are integers, and it's also obvious that 2 goes into 1 zero times. There is nothing self-evident about operations maintaining types. By that logic, there's no reason for 1 + two shouldn't convert one operand or the other. You people can't tell the difference between obvious and learned conventions that came about because in limitations in the hardware at the time. It seems to me that the expectation that 1/2 yield 0.5 is just as much a convention as that it yield 0 or a true rational. -- Grant Edwards grante Yow! I am covered with at pure vegetable oil and I am visi.comwriting a best seller! -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentation and optional delimiters
Steven D'Aprano: the readability of your posts will increase a LOT if you break it up into paragraphs, You are right, I'll try to do it (when I go in flux state I write quickly, but I tend to produce long paragraphs). The thing is, make-another-copy and make-another-reference are semantically different things: they mean something different. Expecting the compiler to tell whether I want x = y to make a copy or to make another reference is never going to work, But the default behavior may become the true copy, that seems simpler for a newbie to grasp. The language then may give a tool to use references too (like passing arrays to functions in Pascal, you can use var for pass-by-reference reference). It specifically talks about C, but it's relevant to Python, and all hypothetical future languages. Think about string concatenation in Python. It's a nice article, and it says many things. (The D language manages strings in a good enough way, they are represented below the hood as stack allocated structs of [pointer_begin, length] in UTF8/16/32 (C strings are available too, static arrays of chars too, etc) that point to a block on the GC-ected heap. Such representation may change into a [pointer_begin, pointer_end] in the future, to speed up iterations. But it lacks still a good way to do a reserve() like in STL C++ Vector, that requires a third value in the struct). I presume you have linked me that article because it essentially explains the concept of leaking abstractions, that is even if your system allows you to manage it through high-level abstractions, you often have to know what's under the cover anyway, because the behavior of such subsystems may have a large impact on the performance of the high-level operations you try to perform. If this is why you have pointed me that article, then I have the following comments: 1) That's why when I have started learning Python I was asking here about the computational complexity of various operations done by Python, like the string methods. Later I have found that the best strategy is to just perform thousands of little benchmarks. Even later I have started to just read the C sources of Python :-) 2) The language I was talking about isn't meant to replace C or Java, it's meant for newbies, students, and to be used on small problems. If the problem is small enough, you can survive even if you ignore the subsystems of the system you are using. So if you have 10 small strings that you want to join once in a Python program you can use the + too, without wasting too much running time. If you want more speed or you want to solve bigger problems you can use different languages. 3) Subsystems may have a different degree of subsystem insulation: 3a) One subsystem that exists when I run a Python program is its GC, but in most situations I can just ignore it, it works in a transparent way, the abstraction doesn't leak much. Only in rare situations I may have to disable it during a very fast creation of a complex data structure, so it doesn't slow down that too much. When I do even more complex things, with complex classes that use __del__ I may have to think about the GC even more, but in most small programs the Python GC is transparent. 3b) On the other hand, when I use the D language in a simple way I can ignore its GC, using D almost as Java. But often I have to use D at a lower level (because otherwise I prefer to use Python), I have to manually allocate and deallocate data from the C heap or from the GC heap, and in such cases the situation becomes hairy quickly, because I don't know how exactly the GC will interact with my manual memory management (that Python disallows). So often in D the GC is an almost mysterious subsystem, and a very leaking abstraction (if you do complex windows programming in C++, with smart pointers, etc, you may have similar problems, so it's not a problem limited to D). They're different from the numbers you can't express exactly in base 2 numbers, and different from the numbers you can't express exactly as rationals, but they're there, waiting to trip you up: If you want to become a CS student, a programmer, you have to know something about IEEE 754, or even you have to study What Every Computer Scientist Should Know About Floating-Point Arithmetic. But for a person that doesn't want to spend so much time to solve a small and not important problem, and doesn't want to hire a programmer to solve that problem do that for him/her, a very high level language may offer ways to the same mathematical operations without too much problems. If you use an old HP 48 calculator you have to be careful, but often it gives you good answers :-) Thank you, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: URLlib2?
rodmc wrote: Probably a silly question but I am writing a CGI script which need to check the referring URL, can anyone provide any pointers? I have looked at URLLib2 and a couple of other libraries, but am slightly confused. When you say, check the referring URL, what are checking about it? Do you just want to know from where your users came? C.l.p is one of Usenet's more helpful groups, but you have to clear and exact, or we're likely to correctly answer the wrong question. There are many plausible checks one might apply to the referring URL. Some are trivial, some subtle. One reason that web servers check referring URL's is to try to ensure that clients go through the intended path. Perhaps the site simply wants to make sure users see teh terms-and-conditions, but more commonly it wants to stop other sites from deep linking, or thwart so-called bandwidth theft. In these cases, checking the referrer is a weak solution; the better method is based on cookies. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
Benoit wrote: Give me something to do! Help to improve one of the experimental writers for docutils. IIRC, the ODT writer does not yet support figures and tables. http://www.rexx.com/~dkuhlman/odtwriter.html The rst2wordml writer appears to be getting its features in place, but when I last used it, some tinkering was required. You could work on adding features. http://docutils.sourceforge.net/sandbox/rst2wordml/readme.html If you get good enough a docutils, provide an option to have the number for the note be superscripted, like the note reference can be. fwiw, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: message entry box at center
asit wrote: i want to show the entry button at the center of the window. How is it possible ?? from Tkinter import * def callback(): print e.get() master=Tk() e=Entry(master) e.pack(expand=True) e.focus_set() b=Button(master,text=get,width=10,command=callback) b.pack(anchor=CENTER) master.mainloop() For more complex layouts have a look at the grid geometry manager. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: more pythonic
On 28 фев, 15:42, Paul McGuire [EMAIL PROTECTED] wrote: On Feb 28, 5:40 am, Temoto [EMAIL PROTECTED] wrote: Hello. There is a Django application, i need to place all its data into Access mdb file and send it to user. It seems to me that params filling for statement could be expressed in a more beautiful way. Since i'm very new to Python, i don't feel that, though. Could you tell your opinion on that snippet? code sql = insert into salesmanager (employeeid, name, officelocation, departmentname, salary) values (?, ?, ?, ?, ?); params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) curs.executemany(sql, params) /code Replace: params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) With this list comprehension: params = [ (mgr.id, mgr.name, mgr.office, mgr.department, mgr.salary) for mgr in Manager.objects.all() ] But the technique you are using, of creating a params list instead of doing explicit string construction, IS the safe SQL-injection- resistant way to do this. -- Paul Thanks a lot. I've been actually waiting for a list comprehension. -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Hallöchen! Grant Edwards writes: [...] You people can't tell the difference between obvious and learned conventions that came about because in limitations in the hardware at the time. It seems to me that the expectation that 1/2 yield 0.5 is just as much a convention as that it yield 0 or a true rational. Should be set up a poll? Do you really think that less than 90% of the voters would enter something else than 0.5 in the result edit field? Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 28, 9:36 am, Grant Edwards [EMAIL PROTECTED] wrote: On 2008-02-28, Carl Banks [EMAIL PROTECTED] wrote: Automatic conversions, okay... but converting a result when all inputs are of one time, NO... People, this is so cognitive dissonance it's not even funny. There is absolutely nothing obvious about 1/2 returning a number that isn't at least approximately equal to one half. I guess obviousness is in the eye of the beholder. To me it's obvious that 1 and 2 are integers, and it's also obvious that 2 goes into 1 zero times. 2 goes into 1 0.5 times. There is nothing self-evident about operations maintaining types. By that logic, there's no reason for 1 + two shouldn't convert one operand or the other. False dilemma, chief. That preserving type is not self-evident doesn't make all operations that don't preserve type a good idea. You people can't tell the difference between obvious and learned conventions that came about because in limitations in the hardware at the time. It seems to me that the expectation that 1/2 yield 0.5 is just as much a convention as that it yield 0 or a true rational. Sure it is, but unlike the old convention, it's the obvious one. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentation and optional delimiters
On Feb 28, 8:40 am, [EMAIL PROTECTED] wrote: But the default behavior may become the true copy, that seems simpler for a newbie to grasp. The language then may give a tool to use references too (like passing arrays to functions in Pascal, you can use var for pass-by-reference reference). Do you want all the power? Do you want to take students in a specific direction? If you're preparing them for the language of tomorrow, the ask the people who foresaw C++ from C. And visionaries are good resources-- the person who designed it might cut it too. It sounds like you want to give them control of pretty much every aspect if they choose, but can wave hands at a very high level too (But -this- is important-style). But that's what Python does! Write your own structure in C, and the program in Python. Perhaps maybe for extra credit, you can have students tweak a 10% running time by upgrading their structure to a... ahem... lower language. Last but not least, try lopping off a few parentheses: if obj exists: - if obj.exists() if hasattr( obj, 'exists' ) if exists( obj ) if os.path.exists is imported, or callable( exists ) in general - RuntimeAmbiguityError if both are true. What do you think? -- http://mail.python.org/mailman/listinfo/python-list
Re: more pythonic
On Feb 28, 8:58 am, Temoto [EMAIL PROTECTED] wrote: On 28 ÆÅ×, 15:42, Paul McGuire [EMAIL PROTECTED] wrote: On Feb 28, 5:40 am, Temoto [EMAIL PROTECTED] wrote: Hello. There is a Django application, i need to place all its data into Access mdb file and send it to user. It seems to me that params filling for statement could be expressed in a more beautiful way. Since i'm very new to Python, i don't feel that, though. Could you tell your opinion on that snippet? code sql = insert into salesmanager (employeeid, name, officelocation, departmentname, salary) values (?, ?, ?, ?, ?); params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) curs.executemany(sql, params) /code Replace: params = [] for manager in Manager.objects.all(): params.append( (manager.id, manager.name, manager.office, manager.department, manager.salary) ) With this list comprehension: params = [ (mgr.id, mgr.name, mgr.office, mgr.department, mgr.salary) for mgr in Manager.objects.all() ] But the technique you are using, of creating a params list instead of doing explicit string construction, IS the safe SQL-injection- resistant way to do this. -- Paul Thanks a lot. I've been actually waiting for a list comprehension.- Hide quoted text - - Show quoted text - In general, whenever you have: someNewList = [] for smthg in someSequence: if condition(smthg): someNewList.append( elementDerivedFrom(smthg) ) replace it with: someNewList = [ elementDerivedFrom(smthg) for smthg in someSequence if condition(smthg) ] -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Place n indistinguishable items into k distinguishable boxes
On Feb 28, 5:02 am, Michael Robertson [EMAIL PROTECTED] wrote: Thanks again for your efforts here. This particular problem didn't appear in any course I took...certainly similar problems did. And here's the obligatory not-very-obfuscated one-liner: from itertools import combinations as c; boxings=lambda n,k:([s[i +1]+~s[i] for i in range(k)] for s in [[-1]+list(t)+[n-~k] for t in c(range(n-~k),k-1)]) You'll need to check out and compile the latest svn sources to make it work, though. And it doesn't work when k == 0. Mark -- http://mail.python.org/mailman/listinfo/python-list
feedback requested
I have a data structure I think would be very useful. It passes a few test cases, but one attempt to optimize it failed, so that may indicate a bug. Will anyone help me debug it, verify it, or clean it? It pertains to multi-threading and is a synchro. structure. If it is not an interest of yours, please let it be someone else's. It's an augmented Lock that I described a few weeks ago (different from the FlowStep structure I was developing with Mr. Bieber). My goal is to return Deadlock from acquire() if its blocking would directly create deadlock. Basic example: thread-1 acquires lockA thread-2 acquires lockB thread-1 calls to acquire lockB and blocks thread-2 calls to acquire lockA and blocks and neither can ever continue. There is enough information to deny thread-2's request, and return at once with failure. The method is already somewhat treated in other structures, but I did not find one for Python. thread-2 calls to acquire lockA and returns Deadlock flag. I would appreciate a half-hour and a thought or observation you make, bugs you spot, c. It lacks a blocking argument to acquire; CustThread and Trylock should garbage collect themselves (note the set of all); Trylock().lock should be an RLock; and I shouldn't need the CustThread class at all, if anyone's going to publish this, but it can be used for free right now. It's runs in Python 3.0 and 2.5. The current test consists of 6 threads randomly acquiring 20 locks and infinitely looping. Thanks in advance. from __future__ import with_statement import threading import thread from time import sleep from collections import deque class CustThread: count= 0 all= {} def __init__( self, threadid ): assert threadid not in CustThread.all CustThread.count+= 1 self.id= CustThread.count self.has= set() self.waits= set() def __repr__( self ): return 'CustThread %i'% self.id def s( self ): return self, 'has', self.has, 'waits', self.waits try: from collections import namedtuple Pair= namedtuple( Pair, thread lock ) except: class Pair: def __init__( self, thread, lock ): self.thread, self.lock= thread, lock Acquires, Blocks, Deadlocks= object(), object(), object() resultdict= { Acquires: 'Acquires', Blocks: 'Blocks', Deadlocks: 'Deadlocks' } class Trylock: count= 0 locks= set() _threads= {} _goplock= threading.Lock() def __init__( self, *ar, **kwar ): #self.lock= threading.RLock() self.lock= threading.Lock() self._oplock= threading.Lock() Trylock.locks.add( self ) self.id= Trylock.count Trylock.count+= 1 def __repr__( self ): return 'Trylock %i'% self.id def acquire( self ): callerid= thread.get_ident() with Trylock._goplock: caller= Trylock._threads.get( callerid ) if caller is None: caller= CustThread( callerid ) Trylock._threads[ callerid ]= caller with Trylock._goplock: if self._cycles(): return Deadlocks caller.waits.add( self ) ret= self.lock.acquire() with Trylock._goplock: caller.waits.remove( self ) caller.has.add( self ) return Acquires def release( self ): with self._oplock: has= [ th for th in Trylock._threads.values() if self in th.has ] assert len( has )== 1 has[0].has.remove( self ) self.lock.release() def __enter__( self ): if not self.acquire(): raise Exception( 'Deadlock' ) def __exit__( self, t, v, tb ): self.release() def _cycles( self ): inth= Trylock._threads[ thread.get_ident() ] inlock= self edges= [ Pair( th, ck ) for th in Trylock._threads.values() for ck in th.has| th.waits ] inpair= Pair( inth, inlock ) edges.append( inpair ) d= deque( [ e for e in edges if e.lock is inlock ] ) while d: cur= d.popleft() locks= [ e.lock for e in edges if e.thread is cur.thread and e.lock is not cur.lock ] for ck in locks: nexts= [ e for e in edges if ck is e.lock and e.thread is not cur.thread ] if inpair in nexts: return True d.extend( nexts ) return False def main( func ): if __name__== '__main__': func() @main def fmain(): import random locks= [ Trylock() for _ in range( 20 ) ] def th1( i ): while 1: lock= random.choice( locks ) ret= lock.acquire() if ret is not Acquires: continue print( '%i th lock %s acquire\n'% ( i, lock ) ), sleep( .0001 ) lock2= random.choice( locks ) if lock2 is lock: pass elif lock2.acquire() is Acquires: print( '%i th lock2 %s
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 10:39:51 - Steven D'Aprano [EMAIL PROTECTED] wrote: On Thu, 28 Feb 2008 00:30:11 -0800, Dennis Lee Bieber wrote: Automatic conversions, okay... but converting a result when all inputs are of one time, NO... What? How does that make any sense? By that logic, we should see this: len(a string) '8' len([2, 4, 6]) [3] len({'key': 'value'}) {1: None} I think that you have to show your work here. How does the above statement about operators imply that the len method should return the type of its argument? The only rule needed is very simple: promote simpler types to the more complex type involved in the current expression (with expression defined as value operator value -- so (1/2) * 3.0 is INTEGER 1/2, resultant 0 then promoted to float 0.0 to be compatible with 3.0). Very simple rule, used by very many traditional programming languages. And rightly rejected by many other programming languages, including modern Python, not to mention calculators, real mathematics and common sense. Lost me again. I was not aware that calculators, real mathematics and common sense were programming languages. Check out the definition in http://en.wikipedia.org/wiki/Programming_language and others if you are unclear. PLs are designed to communicate with machines. Even a calculator is an application, not a language. This is an important difference. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
En Thu, 28 Feb 2008 12:33:33 -0200, [EMAIL PROTECTED] escribi�: Implemented all your suggestions, with two exceptions. Changed file read to readlines(), but not open(...).readlines(). I love to say file.close(). Gives me a feeling of security. (We could discuss RAM waste v. I/O speed but this input file is just 10KB, so neither matters.) Ok, what about this? with open(...) as f: for line in f: ...do something with each line... The with statement guarantees that close (implicit) is always called. Removed one of the three globals, but left the other two. Couldn't see any real advantage to passing poor 'ofile' from hand to hand (writeHTML() to writeBody() to writeEntries() ...) as opposed to letting him rest easy in his chair, doing a little writing when called. Perhaps not in this small script, but as a design principle, having a global `ofile` object doesn't look good... Also changed the opening doc comment to give you appropriate credit. No need for that. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 06:10:13 -0800 (PST) Carl Banks [EMAIL PROTECTED] wrote: On Feb 28, 3:30 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote: Automatic conversions, okay... but converting a result when all inputs are of one time, NO... People, this is so cognitive dissonance it's not even funny. I'll say. There is absolutely nothing obvious about 1/2 returning a number that isn't at least approximately equal to one half. There is nothing self- evident about operations maintaining types. Not obvious to you. You are using subjective perception as if it was a law of nature. If obvious was the criteria then I would argue that the only proper result of integer division is (int, int). Give me the result and the remainder and let me figure it out. You people can't tell the difference between obvious and learned conventions that came about because in limitations in the hardware at the time. Nobody would have come up with a silly rule like x op y must always have the same type as x and y if computer hardware had been up to the task when these languages were created. What makes you say they weren't? Calculating machines that handled floating point are older than Python by far. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Raising exception on STDIN read
On 2008-02-27, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark [EMAIL PROTECTED] escribi�: On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote: Hi, I would like to raise an exception any time a subprocess tries to read from STDIN: latexprocess = subprocess.Popen( \ 'pdflatex' + \ + 'test' + 21, \ shell=True, \ cwd=os.getcwd(), \ env=os.environ, \ stdin=StdinCatcher() # any ideas here? ) An exception should be raised whenever the pdflatex process reads from STDIN... and I have no idea how to do it. Any suggestions? How about with a file-like object? I haven't tested this with subprocess so you might want to read the manual on files if it doesn't work[1]. Won't work for an external process, as pdflatex (and the OS) knows nothing about Python objects. The arguments to subprocess.Popen must be actual files having real OS file descriptors. Taken from the subprocess documentation (emphasis mine). [1] stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), *an existing file object*, and None. The following peice of code works fine for me with the subprocess module. NOTE: the only difference from this and the last I posted is that I set fileno() to _error(). import sys import subprocess class ErrorFile(object): def _error(self, *args, **kwargs): raise AssertionError(Illegal Access) def _noop(self, *args, **kwargs): pass close = flush = seek = tell = _noop next = read = readline = readlines = xreadlines = tuncate = _error truncate = write = writelines = fileno = _error # ^^ proc = subprocess.Popen(cat -, shell=True, stdin=ErrorFile()) ret = proc.wait() print return, ret Ian [1] http://docs.python.org/lib/node528.html -- http://mail.python.org/mailman/listinfo/python-list
TypeError: only length-1 arrays can be converted to Python scalars.
Hi All, Could anybody tell me what is the problem with the following sequence with which I always get the above error message. I use Numeric and Python 2.4 x=array([1,2,3,4]) y=exp(x) Nure -- http://mail.python.org/mailman/listinfo/python-list
Re: Place n indistinguishable items into k distinguishable boxes
On Feb 28, 2:40 am, Michael Robertson [EMAIL PROTECTED] wrote: Hi, I need a generator which produces all ways to place n indistinguishable items into k distinguishable boxes. For n=4, k=3, there are (4+3-1)!/(3-1)!/4! = 15 ways. (0,0,4) [...] Here is my little function: --- from itertools import chain from operator import sub def boxings(n, k): boxings(n, k) - iterator Generate all ways to place n indistiguishable items into k distinguishable boxes seq = [n] * (k-1) while True: yield map(sub, chain(seq, [n]), chain([0], seq)) for i, x in enumerate(seq): if x: seq[:i+1] = [x-1] * (i+1) break else: return --- It is purely iterative. I think it is not too wasteful but I haven't tried to optimise it in any way. In the function, 'seq' iterates over all increasing sequences of length k-1 over {0,1,..n}. Example: for b in boxings(4, 3): print b ... [4, 0, 0] [3, 1, 0] [2, 2, 0] [1, 3, 0] [0, 4, 0] [3, 0, 1] [2, 1, 1] [1, 2, 1] [0, 3, 1] [2, 0, 2] [1, 1, 2] [0, 2, 2] [1, 0, 3] [0, 1, 3] [0, 0, 4] ... here is another attempt on the same principle: --- def boxings(n, k): boxings(n, k) - iterator Generate all ways to place n indistiguishable items into k distinguishable boxes seq = [n]*k + [0] while True: yield tuple(seq[i] - seq[i+1] for i in xrange(k)) i = seq.index(0) - 1 if i = 1: seq[i:k] = [seq[i] - 1] * (k - i) else: return -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Raising exception on STDIN read
En Thu, 28 Feb 2008 14:29:04 -0200, Ian Clark [EMAIL PROTECTED] escribió: On 2008-02-27, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark [EMAIL PROTECTED] escribi�: On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote: Hi, I would like to raise an exception any time a subprocess tries to read from STDIN: latexprocess = subprocess.Popen( \ 'pdflatex' + \ + 'test' + 21, \ shell=True, \ cwd=os.getcwd(), \ env=os.environ, \ stdin=StdinCatcher() # any ideas here? ) An exception should be raised whenever the pdflatex process reads from STDIN... and I have no idea how to do it. Any suggestions? How about with a file-like object? I haven't tested this with subprocess so you might want to read the manual on files if it doesn't work[1]. Won't work for an external process, as pdflatex (and the OS) knows nothing about Python objects. The arguments to subprocess.Popen must be actual files having real OS file descriptors. Taken from the subprocess documentation (emphasis mine). [1] stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), *an existing file object*, and None. The following peice of code works fine for me with the subprocess module. NOTE: the only difference from this and the last I posted is that I set fileno() to _error(). import sys import subprocess class ErrorFile(object): def _error(self, *args, **kwargs): raise AssertionError(Illegal Access) def _noop(self, *args, **kwargs): pass close = flush = seek = tell = _noop next = read = readline = readlines = xreadlines = tuncate = _error truncate = write = writelines = fileno = _error # ^^ proc = subprocess.Popen(cat -, shell=True, stdin=ErrorFile()) ret = proc.wait() print return, ret I don't see how this could ever work. The shell knows nothing about your ErrorFile objects. If subprocess.Popen doesn't reject that ErrorFile instance, it's a bug. An ErrorFile instance is not an existing file object. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Place n indistinguishable items into k distinguishable boxes
On Feb 28, 4:44 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: ... here is another attempt on the same principle: --- def boxings(n, k): boxings(n, k) - iterator Generate all ways to place n indistiguishable items into k distinguishable boxes seq = [n]*k + [0] while True: yield tuple(seq[i] - seq[i+1] for i in xrange(k)) i = seq.index(0) - 1 if i = 1: seq[i:k] = [seq[i] - 1] * (k - i) else: return Actually this is better as it handles k=0 correctly: def boxings(n, k): seq, i = [n]*k + [0], k while i: yield tuple(seq[i] - seq[i+1] for i in xrange(k)) i = seq.index(0) - 1 seq[i:k] = [seq[i] - 1] * (k-i) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: anydbm safe for simultaneous writes?
On Feb 28, 7:47 am, Brian Smith [EMAIL PROTECTED] wrote: Chris wrote: I need simple data persistence for a cgi application that will be used potentially by multiple clients simultaneously. So I need something that can handle locking among writes. Sqlite probably does this, but I am using Python 2.4.4, which does not include sqlite. The dbm-style modules would probably be fine, but I have no idea if they are write safe (I have no experience with the underlying unix stuff). Any tips appreciated. No, you cannot assume that this will work without locking. Locking is not trivial to do in Python. And, even with a working locking mechanism, you still have to invalidate the in-memory caches any time a write to the database is done. Futher, most dbm modules do not have ACID properties. I suggest intalling the pysqlite module and using it, regardless of your version of CPython. According to pysqlite developer, the version of pysqlite included in CPython 2.5 is old. - Brian Thanks for the info. In response to Dennis's question--the system is controlled by a tyrannical system administrator, so I was hoping to not have to ask him to install anything extra. But it sounds like sqlite (or mysql) is the way to go, so I will pursue that path. Thanks, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Raising exception on STDIN read
On 2008-02-28, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 28 Feb 2008 14:29:04 -0200, Ian Clark [EMAIL PROTECTED] escribió: On 2008-02-27, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark [EMAIL PROTECTED] escribi�: On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote: Hi, I would like to raise an exception any time a subprocess tries to read from STDIN: latexprocess = subprocess.Popen( \ 'pdflatex' + \ + 'test' + 21, \ shell=True, \ cwd=os.getcwd(), \ env=os.environ, \ stdin=StdinCatcher() # any ideas here? ) An exception should be raised whenever the pdflatex process reads from STDIN... and I have no idea how to do it. Any suggestions? How about with a file-like object? I haven't tested this with subprocess so you might want to read the manual on files if it doesn't work[1]. Won't work for an external process, as pdflatex (and the OS) knows nothing about Python objects. The arguments to subprocess.Popen must be actual files having real OS file descriptors. Taken from the subprocess documentation (emphasis mine). [1] stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), *an existing file object*, and None. The following peice of code works fine for me with the subprocess module. NOTE: the only difference from this and the last I posted is that I set fileno() to _error(). import sys import subprocess class ErrorFile(object): def _error(self, *args, **kwargs): raise AssertionError(Illegal Access) def _noop(self, *args, **kwargs): pass close = flush = seek = tell = _noop next = read = readline = readlines = xreadlines = tuncate = _error truncate = write = writelines = fileno = _error # ^^ proc = subprocess.Popen(cat -, shell=True, stdin=ErrorFile()) ret = proc.wait() print return, ret I don't see how this could ever work. The shell knows nothing about your ErrorFile objects. If subprocess.Popen doesn't reject that ErrorFile instance, it's a bug. An ErrorFile instance is not an existing file object. Could you please explain why this won't work. ErrorFile exposes most all attributes of file objects, so I don't understand why it wouldn't be considered a file object. Did you try running the code by any chance? It works fine for me on 2.5.1 on Linux. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: message entry box at center
On Feb 28, 7:53 pm, Peter Otten [EMAIL PROTECTED] wrote: asit wrote: i want to show the entry button at the center of the window. How is it possible ?? from Tkinter import * def callback(): print e.get() master=Tk() e=Entry(master) e.pack(expand=True) e.focus_set() b=Button(master,text=get,width=10,command=callback) b.pack(anchor=CENTER) master.mainloop() For more complex layouts have a look at the grid geometry manager. Peter but here there is another problem. there is a huge gap between get button and message entry button when maximized. pl z help. !! -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 2008-02-28 at 11:22 -0500, D'Arcy J.M. Cain wrote: Not obvious to you. You are using subjective perception as if it was a law of nature. If obvious was the criteria then I would argue that the only proper result of integer division is (int, int). Give me the result and the remainder and let me figure it out. I'd like to point out that now you are talking about int OP int returning a tuple, not an int. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
Marc 'BlackJack' Rintsch wrote: On Wed, 27 Feb 2008 19:18:27 -0800, Jeff Schwab wrote: Benoit wrote: I've been teaching myself the python language over the past few months using Mark Lutz' Learning Python, 3ed. Python is also the first programming language I've ever taken up. I find the language easy to learn and rather productive in relation to the introductory course on C ++ I'd begun in January for fun @ school (we're practicing dynamic arrays using pointers... kill me now). Get a better teacher, if you can. Please do me a personal favor: Don't hold the crappy course against C++. For the record, you should never have to manage dynamically allocated arrays manually, nor store pointers to them. Try the std::vector template, and post in comp.lang.c++ if have any trouble. Hey a flame bait. I'll bite. Excuse me? Somebody posts about an introductory course on C++ covering dynamic arrays using pointers and literally says kill me now, and I'm the flamer for asking him not to hold the language responsible for the bad course? This a bit of an overreaction unless you know what the course was about. It's supposed to be about C++, according to the OP. If the goal is to learn about the computer and that basically everything is a number in the end, then C is a good choice. More portable than assembler but nearly as close to the metal. And a better choice than C++ would be. To the OP: If you try C++, don't hold that crappy language against C#, D, or Java. ;-) What's the relevance of C#, D, or Java to the OP's post? -- http://mail.python.org/mailman/listinfo/python-list
Re: message entry box at center
asit wrote: On Feb 28, 7:53 pm, Peter Otten [EMAIL PROTECTED] wrote: asit wrote: i want to show the entry button at the center of the window. How is it possible ?? from Tkinter import * def callback(): print e.get() master=Tk() e=Entry(master) e.pack(expand=True) e.focus_set() b=Button(master,text=get,width=10,command=callback) b.pack(anchor=CENTER) master.mainloop() For more complex layouts have a look at the grid geometry manager. but here there is another problem. there is a huge gap between get button and message entry button when maximized. Here are two more variants: # large Entry widget from Tkinter import * master = Tk() e = Entry(master) e.pack(expand=1, fill=BOTH) b = Button(master, text=get) b.pack() master.mainloop() # nested Frame widget from Tkinter import * master = Tk() panel = Frame(master) panel.pack(expand=1) e = Entry(panel) e.pack() b = Button(panel, text=get) b.pack() master.mainloop() Peter -- http://mail.python.org/mailman/listinfo/python-list
Decorators and buffer flushing
Hi, all. I apologize for what is perhaps a newb question. I'm in the process of transitioning our testing framework from Perl to Python. While that alone probably sets off some red flags, I'm afraid it's what I'm stuck with. I'm modeling a test with five operations: build, execute, validate, publish, and clean. The main loop might look something like this: with Test(...) as t: t.build() t.execute() t.validate() t.publish() At each run, I want to output a '.' to denote completion of that test step. I've been able to do this, sort of, using the following decorator (edited for brevity): def report(f): def new(self): stat = f(self); if stat is True: sys.stdout.write ('.') else: ... sys.stdout.flush() return new (Each one of the test functions returns True or False depending on its completion status.) The problem is that rather than outputting a period after each step is completed, it outputs all four of them at once. Instead of seeing progress as it happens, I get it when it's finished, even though I'm flushing the output buffer. Any thoughts? Best, Ethan ([EMAIL PROTECTED]) http://uppertank.net/ethanm/ -- http://mail.python.org/mailman/listinfo/python-list
Re: first time use of swig, python and c++ .. it's a mess ... please advice
On Feb 27, 9:44 pm, Bronner, Gregory [EMAIL PROTECTED] wrote: The operator= stuff is usually innocuous. The compiler died because it couldn't find 'vector', which is reasonable, since it thought it was compiling a C file. Probably because you swigged the file without the magic -c++ option -- I'm not sure how distutils passes arguments to swig, but if you do it from the command line, you'll do something like swig -c++ -python -Ipath to python file and it will generate a .cpp file and a .py file, which will (hopefully) compile. I'd focus on doing it manually, then getting distutils to work properly. -Original Message- From: Hyuga [mailto:[EMAIL PROTECTED] Sent: Wednesday, February 27, 2008 10:01 AM To: [EMAIL PROTECTED] Subject: Re: first time use of swig, python and c++ .. it's a mess ... please advice On Feb 26, 3:38 pm, Eric von Horst [EMAIL PROTECTED] wrote: Hi, we have a third-party product that has a C++ api on HP-UX. I would like be able to use the API in Python (as I remember Python is good at doing this). I have no experience with this so I Googled and tried to find some info on what I had to do. So, I installed Python 2.4.4 and Swig 1.3.33 The header file to the library is '/opt/OV/include/opcsvcapi.h'. I created a SWIG file with the following content: %module opcsvcapi %{ /* Includes the header in the wrapper code */ #include /opt/OV/include/opcsvcapi.h %} /* Parse the header file to generate wrappers */ %include /opt/OV/include/opcsvcapi.h Then I ran the cmd: # swig -c++ -python opcsvcapi.i with output: /opt/OV/include/opcsvcapi.h:41: Warning(362): operator= ignored /opt/OV/include/opcsvcapi.h:46: Warning(503): Can't wrap 'operator Type' unless renamed to a valid identifier. The result are two files: opcsvcapi.py opcsvcapi_wrap.cxx I created a 'setup.py' file with the following content: import distutils from distutils.core import setup, Extension setup(name = opcsvcapi, version = 1.0, ext_modules = [Extension(_opcsvcapi, [opcsvcapi.i,opcsvcapi.cxx])]) Then I run: python setup.py build This results in an extra file: opcsvcapi_wrap.c and a 'build' directory and the following errors: running build running build_ext building '_opcsvcapi' extension swigging opcsvcapi.i to opcsvcapi_wrap.c swig -python -o opcsvcapi_wrap.c opcsvcapi.i creating build creating build/temp.hp-ux-B.11.11-9000-800-2.4 gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -fPIC -I/usr/local/include/python2.4 -c opcsvcapi_wrap.c -o build/temp.hp-ux-B.11.11-9000-800-2.4/opcsvcapi_wrap.o In file included from /usr/local/include/python2.4/Python.h:8, from opcsvcapi_wrap.c:118: /usr/local/include/python2.4/pyconfig.h:851:1: warning: _POSIX_C_SOURCE redefined command line:1:1: warning: this is the location of the previous definition In file included from opcsvcapi_wrap.c:2490: /opt/OV/include/opcsvcapi.h:12:18: error: vector: No such file or directory In file included from opcsvcapi_wrap.c:2490: /opt/OV/include/opcsvcapi.h:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'SvcAPI' opcsvcapi_wrap.c: In function 'Swig_var_SvcAPI_set': opcsvcapi_wrap.c:2505: error: 'SvcAPI' undeclared (first use in this function) opcsvcapi_wrap.c:2505: error: (Each undeclared identifier is reported only once opcsvcapi_wrap.c:2505: error: for each function it appears in.) opcsvcapi_wrap.c:2505: error: 'namespace' undeclared (first use in this function) opcsvcapi_wrap.c:2505: error: expected expression before ')' token opcsvcapi_wrap.c: In function 'init_opcsvcapi': opcsvcapi_wrap.c:3064: error: 'Swig_var_SvcAPI_get' undeclared (first use in this function) error: command 'gcc' failed with exit status 1 and that's it. Any idea what I am doing wrong? Any help much appreciated Kris Well, the errors you got from the compiler are just confusing to me, but I suspect it goes back to the warning you got from SWIG. Some class in there is overriding the = operator, but since that can't be done in Python, you need to give it some special instructions on how to handle that. For example, if you have Foo::operator=, in your SWIG header include a line like: %rename(assign) Foo::operator= Then in the Python module, the Foo class will have an assign method. Hyuga - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation
Re: Decorators and buffer flushing
On Feb 28, 11:49 am, Ethan Metsger [EMAIL PROTECTED] wrote: Hi, all. I apologize for what is perhaps a newb question. I'm in the process of transitioning our testing framework from Perl to Python. While that alone probably sets off some red flags, I'm afraid it's what I'm stuck with. I'm modeling a test with five operations: build, execute, validate, publish, and clean. The main loop might look something like this: with Test(...) as t: t.build() t.execute() t.validate() t.publish() At each run, I want to output a '.' to denote completion of that test step. I've been able to do this, sort of, using the following decorator (edited for brevity): def report(f): def new(self): stat = f(self); if stat is True: sys.stdout.write ('.') else: ... sys.stdout.flush() return new (Each one of the test functions returns True or False depending on its completion status.) The problem is that rather than outputting a period after each step is completed, it outputs all four of them at once. Instead of seeing progress as it happens, I get it when it's finished, even though I'm flushing the output buffer. Any thoughts? Best, Ethan ([EMAIL PROTECTED])http://uppertank.net/ethanm/ Can you reproduce the bug on the console? Or, try starting with a new line in the output. Or, try a input(). -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
D'Arcy J.M. Cain wrote: Not obvious to you. You are using subjective perception as if it was a law of nature. If obvious was the criteria then I would argue that the only proper result of integer division is (int, int). Give me the result and the remainder and let me figure it out. J. Cliff Dyer [EMAIL PROTECTED] wrote: I'd like to point out that now you are talking about int OP int returning a tuple, not an int. No, D'Arcy's point was that obvious isn't the criteria because it would lead to behaviour that no one wants. No one is going to win this argument by using words like natural or obvious. You're just going to have to accept that there that there is no concensus on this issue and there never was. In the end only one person's opinion of what was natural and obvious really matters. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] [EMAIL PROTECTED] -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: only length-1 arrays can be converted to Python scalars.
[EMAIL PROTECTED] wrote: Hi All, Could anybody tell me what is the problem with the following sequence with which I always get the above error message. I use Numeric and Python 2.4 x=array([1,2,3,4]) y=exp(x) Presumably, you are using exp() from the builtin module math, which knows nothing about Numeric. Use Numeric.exp() instead. I do recommend upgrading to numpy and asking further questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists When reporting an error, please include the smallest *complete* snippet of code that demonstrates the problem, as well as the complete traceback. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: call by reference howto????
On Feb 27, 6:02 pm, Tamer Higazi [EMAIL PROTECTED] wrote: Hi! Can somebody of you make me a sample how to define a function based on call by reference ??? I am a python newbie and I am not getting smart how to define functions, that should modify the variable I passed by reference. thanks in advance Tamer If it's a mutable object, avoid the pitfalls of rebinding the parameter, and just modify the object. BAD: def f( a ): a= { 'this': 'that' } GOOD: def f( a ): a.clear() a[ 'this' ]= 'that' -- http://mail.python.org/mailman/listinfo/python-list
Re: Place n indistinguishable items into k distinguishable boxes
On Feb 28, 10:07 am, Mark Dickinson [EMAIL PROTECTED] wrote: On Feb 28, 5:02 am, Michael Robertson [EMAIL PROTECTED] wrote: Thanks again for your efforts here. This particular problem didn't appear in any course I took...certainly similar problems did. And here's the obligatory not-very-obfuscated one-liner: from itertools import combinations as c; boxings=lambda n,k:([s[i +1]+~s[i] for i in range(k)] for s in [[-1]+list(t)+[n-~k] for t in c(range(n-~k),k-1)]) This calls for an obfuscation metric, several books, and two personal references. What is ~k doing in there twice? (Aside: throw in an obligatority one too. Sigh.) -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 13:32:06 -0500 J. Cliff Dyer [EMAIL PROTECTED] wrote: On Thu, 2008-02-28 at 11:22 -0500, D'Arcy J.M. Cain wrote: Not obvious to you. You are using subjective perception as if it was a law of nature. If obvious was the criteria then I would argue that the only proper result of integer division is (int, int). Give me the result and the remainder and let me figure it out. I'd like to point out that now you are talking about int OP int returning a tuple, not an int. Which would be stupid. Good thing I don't think that obvious should be the criteria. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
[EMAIL PROTECTED] wrote: Implemented all your suggestions, with two exceptions. Changed file read to readlines(), but not open(...).readlines(). I love to say file.close(). Gives me a feeling of security. (We could discuss RAM waste v. I/O speed but this input file is just 10KB, so neither matters.) Removed one of the three globals, but left the other two. Couldn't see any real advantage to passing poor 'ofile' from hand to hand (writeHTML() to writeBody() to writeEntries() ...) as opposed to letting him rest easy in his chair, doing a little writing when called. Note that if you call the parameter to the function ofile as well, you don't need to change *any* other code to get correct behavior. But in general terms it's a practice you should adopt as early as possible, because it gets very tedious very quickly to have to trace the use of global variables in programs of any size. Avoiding the use of globals is just good program hygiene. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
On Feb 28, 12:34 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Marc 'BlackJack' Rintsch wrote: Hey a flame bait. I'll bite. [ redirected to OP ] OP.flamebait= 1.0. bait.bite() Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'FlameBait' object has no attribute 'bite' Excuse me? Somebody posts about an introductory course on C++ covering dynamic arrays using pointers and literally says kill me now, and I'm the flamer for asking him not to hold the language responsible for the bad course? This a bit of an overreaction unless you know what the course was about. It's supposed to be about C++, according to the OP. If the goal is to learn about the computer and that basically everything is a number in the end, then C is a good choice. More portable than assembler but nearly as close to the metal. And a better choice than C++ would be. To the OP: If you try C++, don't hold that crappy language against C#, D, or Java. ;-) What's the relevance of C#, D, or Java to the OP's post? public static void synchronized flamewar() {} virtual void flamewar() {} def flamewar(): pass [ castironpi has changed the newsgroup to comp.lang.flamewar ] Programming is very hard. And on that note! -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
Forgive my language concerning C++ as its turned the thread into something I did not intend. I merely wished to point out that Python was easier for me to learn than C++. To Schwab, its likely that Mark Lutz is simply a better instructor than my professor. -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: only length-1 arrays can be converted to Python scalars.
[EMAIL PROTECTED] wrote: Hi All, Could anybody tell me what is the problem with the following sequence with which I always get the above error message. I use Numeric and Python 2.4 x=array([1,2,3,4]) y=exp(x) The meaning of the error message is fairly obvious - exp() can't operate on arrays. I presume Numeric has its own exp(), and that you need to use that instead. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
D'Arcy J.M. Cain [EMAIL PROTECTED] writes: I'd like to point out that now you are talking about int OP int returning a tuple, not an int. Which would be stupid. Good thing I don't think that obvious should be the criteria. We already have that function (divmod) and it is very useful. -- http://mail.python.org/mailman/listinfo/python-list
rstrip error python2.4.3 not in 2.5.1?
Hi, I wrote some python code that retrieves urls from a txt file. In this code I use .rstrip() for removing the '\n' at the end of every url. While this code works on my mac (leopard) with python 2.5.1, this same code fails to work on an ubuntu server with python 2.4.3 I was wondering if there is a problem with .rstrip() in that python version? error : Traceback (most recent call last): File delgraph.py, line 62, in ? url_metadata = d.get_url(site.rstrip()) -- http://mail.python.org/mailman/listinfo/python-list
Re: XML expat error
On 28 feb, 08:18, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 27 Feb 2008 14:02:25 -0800, dirkheld wrote: Something strange here. The xml file causing the problem has only 361 lines. Isn't there a way to catch this error, ignore it and continu with the rest of the other files? Yes of course: handle the exception instead of letting it propagate to the top level and ending the program. Ciao, Marc 'BlackJack' Rintsch Ehm, maybe a stupid question... how. I'm rather new to python and I never user error handling. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML expat error
dirkheld wrote: On 28 feb, 08:18, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 27 Feb 2008 14:02:25 -0800, dirkheld wrote: Something strange here. The xml file causing the problem has only 361 lines. Isn't there a way to catch this error, ignore it and continu with the rest of the other files? Yes of course: handle the exception instead of letting it propagate to the top level and ending the program. Ciao, Marc 'BlackJack' Rintsch Ehm, maybe a stupid question... how. I'm rather new to python and I never user error handling. Care to read the tutorial? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On 28 Feb 2008 12:25:14 -0800 Paul Rubin http://phr.cx@NOSPAM.invalid wrote: D'Arcy J.M. Cain [EMAIL PROTECTED] writes: I'd like to point out that now you are talking about int OP int returning a tuple, not an int. Which would be stupid. Good thing I don't think that obvious should be the criteria. We already have that function (divmod) and it is very useful. Yes it is and has nothing to do with this discussion. I don't think that anyone here has suggested that methods should return the type of their arguments although there have been a few suggestions that the suggestions were made. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
On Thu, 28 Feb 2008 10:34:45 -0800, Jeff Schwab wrote: Hey a flame bait. I'll bite. Excuse me? Somebody posts about an introductory course on C++ covering dynamic arrays using pointers and literally says kill me now, and I'm the flamer for asking him not to hold the language responsible for the bad course? This a bit of an overreaction unless you know what the course was about. It's supposed to be about C++, according to the OP. Yeah, sorry I've read C. Actually it's about a language called C ++ according to the OP. To the OP: If you try C++, don't hold that crappy language against C#, D, or Java. ;-) What's the relevance of C#, D, or Java to the OP's post? The same as C++ to the OP's post if he would have talked about C. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorators and buffer flushing
On Thu, 28 Feb 2008 14:48:55 -0500, [EMAIL PROTECTED] wrote: Can you reproduce the bug on the console? Or, try starting with a new line in the output. Or, try a input(). I can reproduce the issue in the console. I'm not convinced it's actually a bug, unless for some reason the interpreter is preventing a buffer flush. The new line in the output also doesn't work (and isn't desirable anyway), and neither does adding input. Could the problem be that I'm using a with statement? I have output flushed in __enter__: def __enter__(self): Ensures that the test begins appropriately. In particular, this method will enter the directory specified in the instance. self.pardir = os.getcwd() os.chdir(self.path) sys.stdout.write (%s % (self.name.ljust(30),)) sys.stdout.flush() return self Is it possible that flushing is prohibited until __exit__ is called? Best, Ethan ([EMAIL PROTECTED]) http://uppertank.net/ethanm/ -- http://mail.python.org/mailman/listinfo/python-list
Re: XML expat error
On Thu, 28 Feb 2008 12:37:10 -0800, dirkheld wrote: Yes of course: handle the exception instead of letting it propagate to the top level and ending the program. Ehm, maybe a stupid question... how. I'm rather new to python and I never user error handling. Then you should work through the tutorial in the docs, at least until section 8.3 Handling Exceptions: http://docs.python.org/tut/node10.html#SECTION001030 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythons Ladders
On 28 Feb, 21:08, Benoit [EMAIL PROTECTED] wrote: Forgive my language concerning C++ as its turned the thread into something I did not intend. I merely wished to point out that Python was easier for me to learn than C++. To Schwab, its likely that Mark Lutz is simply a better instructor than my professor. I think the remark about C++ just hit a nerve with certain people, and then you're likely to get all sorts of low quality remarks from perpetual bystanders. Returning to your original enquiry, however... Perhaps you would benefit from looking at this page: http://wiki.python.org/moin/BeginnersGuide/Programmers If you feel that you need more practical experience, the following page has some suggestions, although it's rather focused on people mucking in and fixing things around Python rather than pure recreation: http://wiki.python.org/moin/CodingProjectIdeas And the volunteers page is possibly a bit formal for someone just wanting to improve their skills: http://wiki.python.org/moin/VolunteerOpportunities Paul P.S. There's another remark that could be made about the project ideas page, editing practices, and an insufficiently publicised mailing list, but I'll leave that for another time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentation and optional delimiters
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | But the default behavior may become the true copy, that seems | simpler for a newbie to grasp. To me, it is the opposite. If I say gvr = Guido_van_Russum # or any natural language equivalent do you really think a copy is made? Copying is much more work than defining an alias or nickname. -- http://mail.python.org/mailman/listinfo/python-list
Re: rstrip error python2.4.3 not in 2.5.1?
dirkheld [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Hi, | | I wrote some python code that retrieves urls from a txt file. In this | code I use .rstrip() for removing the '\n' at the end of every url. | While this code works on my mac (leopard) with python 2.5.1, this same | code fails to work on an ubuntu server with python 2.4.3 | | I was wondering if there is a problem with .rstrip() in that python | version? | | error : | Traceback (most recent call last): | File delgraph.py, line 62, in ? |url_metadata = d.get_url(site.rstrip()) | -- What is the actual error message [SyntaxError, NameError? etc] that you clipped? -- http://mail.python.org/mailman/listinfo/python-list
Re: rstrip error python2.4.3 not in 2.5.1?
rstrip() works fine in python 2.4.3. May be the problem lies in somewhere else. I tried it in FC6 with Python 2.4.3: url = abc.com\n url.rstrip() 'abc.com' regards, Subeen. http://love-python.blogspot.com/ On Feb 29, 2:30 am, dirkheld [EMAIL PROTECTED] wrote: Hi, I wrote some python code that retrieves urls from a txt file. In this code I use .rstrip() for removing the '\n' at the end of every url. While this code works on my mac (leopard) with python 2.5.1, this same code fails to work on an ubuntu server with python 2.4.3 I was wondering if there is a problem with .rstrip() in that python version? error : Traceback (most recent call last): File delgraph.py, line 62, in ? url_metadata = d.get_url(site.rstrip()) -- http://mail.python.org/mailman/listinfo/python-list
Permission to use Mac OS 'rocketship' dock icon?
Hi all, The image of a rocket with the Python logo that occasionally shows up in the dock would make part of a nice logo for PyMC, an open-source Python Bayesian statistics package. Anyone know who we would have to ask to get permission to use it? Thanks, Anand -- http://mail.python.org/mailman/listinfo/python-list
You have to see this - http://ilaarijs.blogspot.com/ :D
You have to see this - http://ilaarijs.blogspot.com/ :D -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 11:13:27 -0500, D'Arcy J.M. Cain wrote: Automatic conversions, okay... but converting a result when all inputs are of one time, NO... What? How does that make any sense? By that logic, we should see this: len(a string) '8' len([2, 4, 6]) [3] len({'key': 'value'}) {1: None} I think that you have to show your work here. How does the above statement about operators imply that the len method should return the type of its argument? Consider the argument list to the function call len(a string). args = [a string] # all the arguments all(type(arg) == str for arg in args) True So therefore all the arguments to len() in this case are of a single type, namely str, and by Dennis' assertion, converting a result when all inputs are of one [type], NO..., should return the same type as all the arguments. Which for the avoidance of all doubt is str. Similarly for the case len([2, 4, 6]), except this time all the arguments (all one of them) are lists, and therefore len() should return a list. Naturally it's a crazy argument. Which is my point. Operators are merely a different syntax for functions of two arguments, and any restriction that functions must return the same type as all its arguments is just crazy. And rightly rejected by many other programming languages, including modern Python, not to mention calculators, real mathematics and common sense. Lost me again. I was not aware that calculators, real mathematics and common sense were programming languages. I didn't say they were. Please parse my sentence again. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 11:22:43 -0500, D'Arcy J.M. Cain wrote: Calculating machines that handled floating point are older than Python by far. Yes, and they almost universally give the result 1/2 - 0.5. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Thu, 28 Feb 2008 14:41:56 -0500, Ross Ridge wrote: You're just going to have to accept that there that there is no concensus on this issue and there never was. But that's not true. The consensus, across the majority of people (both programmers and non-programmers alike) is that 1/2 should return 0.5. There's a small minority that argue for a rational result, and a bigger minority who argue for 0. The interesting case is -1/2. According to the argument that 2 doesn't go into 1, -1/2 should also return 0. But that's not what Python returns, so it looks like the int division camp is screwed no matter whether Python keeps the status quo or the other status quo. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Running test01.py under Windows (basic level)
I have v2.5.2 installed and i've composed a source code i'm sure everybody will be impressed by. It goes like this. def bloppA (): print a very advanced piece of code What i get to work is to make it run from the the snakes shell. Then, i realised that such a masterpiece needs storing in a file. So i saved it in a file called great.py but when i executed: exec c:\loj\python\great.py i got errors and the pointer showed the colon claiming it's invalid syntax. Of course, everybody will agree it's right syntax and that the computer is stupid. But let's pretend it has won and try to make it happy. How? (Background: I'm a programmer since a few years back but it's mostly Java/C/C++/C# and Python way is very new to me.) -- Regards Konrad Viltersten sleep- a substitute for coffee for the poor ambition - lack of sense to be lazy -- http://mail.python.org/mailman/listinfo/python-list
Odd handling of type.__init__ bases
I encountered an oddity in attempting to use a metaclass to perform mix-in inheritance for classes. I've attached a small demonstration file. Have I misunderstood the bases argument for type.__init__ or should this be submitted as a bug? Python 2.5 (r25:51908, Feb 22 2007, 19:05:27) [GCC 4.1.2] on linux2 -KQ - This mail sent through IMP: http://horde.org/imp/ pyclass.py Description: Binary data -- http://mail.python.org/mailman/listinfo/python-list
convert string number to real number - ValueError: invalid literal for int() with base 10: '2'
i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of numbers and add up the totals for each number. on the bill, each line has a few fields,one field containing the phone number, another field containing the number of minutes on that call. the bill is comma delimited. here is the function i wrote to get one number at a time's total talktime. def getsinglenumbertalktime(number,talktime): for line in file[0:-2]: if number in line: li=line.split(',') if len(li)==6 and li[5]!=Minutes : print talktime type: + str(type (talktime)) #li[5]=fpformat.fix(li[5],0) print li[5] + li[5] type: + str(type(li[5])) newvar = int(li[5]) print (type(newvar)) print li[5] talktime = talktime + li[5] return talktime here is the output with error that i get back. talktime type: type 'int' 2li[5] type: type 'str' Traceback (most recent call last): File stdin, line 1, in module File c:\path\inprog\all_t_mob_nums.py, line 74, in module getsinglenumbertalktime('800-218-2644',talktime) File c:\path\inprog\all_t_mob_nums.py, line 66, in getsinglenumbertalktime newvar = int(li[5]) ValueError: invalid literal for int() with base 10: '2' here is the question: How can i convert a string number like 2 to a true number that can be added. I have tried using pfformat, float(), and int() - all with no good results. this seems like is should be simple, but it just plain isn't. I actually found a good solution. basically, take each entry and add it to a list. then iterate through the list , converting each item to int(). then add them to sum them all up. FINAL SOLUTION: def getsinglenumbertalktime(number,talktime): num_of_calls=0 num_mins=[] for line in file[0:-2]: #print LINE: + line #print number in line if number in line: num_of_calls += 1 #print number,num_of_calls li=line.strip(\n) #print stripped: + line li=li.split(',') #print split: + str(li) #print len of li: + str(len(li)) + str(num_of_calls) if len(li)==7 and li[5]!=Minutes : #print talktime type: + str(type (talktime)) #print li[4] + li[4] type: + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print len 7: + str(type(li[6])) num_mins.append(li[6]) #talktime = talktime + int(a) if len(li)==6 and li[5]!=Minutes : #print talktime type: + str(type (talktime)) #print li[5] + li[5] type: + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print len 6: + str(type(li[5])) num_mins.append(li[5]) #talktime = talktime + int(a) #return talktime , num_of_calls x=0 #print this + str(number) + str(num_mins) for a in num_mins: b=int(a) x=x+b print str(number), str(x), str(type(x)) output should look like this (parts of script are not included) 555-555- replaced the innocent :P): 555-555- 19 type 'int' 555-555- 6 type 'int' 555-555- 3 type 'int' 555-555- 3 type 'int' 555-555- 2 type 'int' 555-555- 52 type 'int' -- http://mail.python.org/mailman/listinfo/python-list
Windows gzip problem
Hello, I am having a problem with gzip. The code worked fine under linux but when I moved it over to windows it is getting stuck unzipping a gz file. -- snippet -- fileObj = gzip.GzipFile(iceGetter.file.localFileName, 'rb') uncompressedFileName = iceGetter.file.localFileName[:-3] output = open(uncompressedFileName, 'wb') output.write(fileObj.read()) output.close() fileObj.close() -- snippet -- typing python autoIce.py gets this error: --error-- Traceback(most recent call last): File runAuto.py, line 17 in ? output.write(fileObj.read()) File C:\Python24\lib\gzip.py. line 217 in read self._read(readsize) File C:\Python24\lib\gzip.py, line 276 in _read uncompress.decompress.decompress(buf) Memory Error --end error-- I tried playing around with the wb/rb when writing and unzipping, like this post [http://groups.google.com/group/comp.lang.python/ browse_thread/thread/96651e3cd2dc6070/e94ae3b22fc78a1b?lnk=gstq=gzip +windows#e94ae3b22fc78a1b] suggested and that did not seem to change anything. I would really appreciate any assistance on this. Thanks John -- http://mail.python.org/mailman/listinfo/python-list
Python app at startup!
Hy. I create simple application. Yust an windows and compile it with py2exe. I add registry value reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v MyApp /t REG_SZ /d C:\myapp.exe /f' And it wont start. When i use console instead od window in py2exe i get console opend but it closes. Help please! -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Steven D'Aprano [EMAIL PROTECTED] writes: any restriction that functions must return the same type as all its arguments is just crazy. I don't think anyone is saying that they should necessarily do that in general. Just in some specific cases. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '2'
On Thu, 28 Feb 2008 14:56:10 -0800 (PST) davidj411 [EMAIL PROTECTED] wrote: ValueError: invalid literal for int() with base 10: '2' here is the question: How can i convert a string number like 2 to a true number that can be added. You have to get rid of the double quotes first. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Steven D'Aprano [EMAIL PROTECTED] writes: Calculating machines that handled floating point are older than Python by far. Yes, and they almost universally give the result 1/2 - 0.5. Can you name an example of a calculating machine that both: 1) represents the integer 1 and the real number 1.0 as distinct objects; and 2) says 1/2 = 0.5 ? -- http://mail.python.org/mailman/listinfo/python-list
How to configure Python in Windows
Hi Folks, I just downloaded precompiled Python for Windows, and it runs. Now I have got the command line coding. However, I can't run my python scripts. My python script, foo.py, is located in C:\\\pydir, and I have set the python interpreter on the directory. When I run os.listdir(), I found my script of foo.py is right in the pydir. But, when I tried to run command-line python foo.py, to compile it, I got Syntax error: invalid syntax. I guess the interpreter did not find my script foo.py. In the past, I worked python on unix/linux, and I knew how set the path, and I ran my python scripts smoothly. I wonder anybody can help me to configure the python interpreter? Thanks! Muddy Coder -- http://mail.python.org/mailman/listinfo/python-list
Re: Raising exception on STDIN read
En Thu, 28 Feb 2008 15:22:21 -0200, Ian Clark [EMAIL PROTECTED] escribió: On 2008-02-28, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 28 Feb 2008 14:29:04 -0200, Ian Clark [EMAIL PROTECTED] escribió: On 2008-02-27, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark [EMAIL PROTECTED] escribi�: On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote: Hi, I would like to raise an exception any time a subprocess tries to read from STDIN: latexprocess = subprocess.Popen( \ 'pdflatex' + \ + 'test' + 21, \ shell=True, \ cwd=os.getcwd(), \ env=os.environ, \ stdin=StdinCatcher() # any ideas here? ) An exception should be raised whenever the pdflatex process reads from STDIN... and I have no idea how to do it. Any suggestions? How about with a file-like object? I haven't tested this with subprocess so you might want to read the manual on files if it doesn't work[1]. Won't work for an external process, as pdflatex (and the OS) knows nothing about Python objects. The arguments to subprocess.Popen must be actual files having real OS file descriptors. Taken from the subprocess documentation (emphasis mine). [1] stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), *an existing file object*, and None. The following peice of code works fine for me with the subprocess module. NOTE: the only difference from this and the last I posted is that I set fileno() to _error(). import sys import subprocess class ErrorFile(object): def _error(self, *args, **kwargs): raise AssertionError(Illegal Access) def _noop(self, *args, **kwargs): pass close = flush = seek = tell = _noop next = read = readline = readlines = xreadlines = tuncate = _error truncate = write = writelines = fileno = _error # ^^ proc = subprocess.Popen(cat -, shell=True, stdin=ErrorFile()) ret = proc.wait() print return, ret I don't see how this could ever work. The shell knows nothing about your ErrorFile objects. If subprocess.Popen doesn't reject that ErrorFile instance, it's a bug. An ErrorFile instance is not an existing file object. Could you please explain why this won't work. ErrorFile exposes most all attributes of file objects, so I don't understand why it wouldn't be considered a file object. Did you try running the code by any chance? It works fine for me on 2.5.1 on Linux. Define works fine. I bet you get an exception - but *before* the child process starts (and no, I didn't try the code, but certainly I would be greatly surprised if it actually worked) Consider the following: The child process may be anything, totally unaware of Python objects. As any other process, it reads from standard input, writes to standard output and maybe to standard error too. Those are predefined file descriptors (0, 1, 2) provided by the operating system itself. When the child process calls write(1, hello\n) it isn't calling the write method of a Python object, it's calling a C runtime function (or system function). Note that `write` requires a *file descriptor*, an OS concept, not a Python object. This is why the documentation for subprocess states that those parameters must be: an integer --that is, a file descriptor-- which is used as it is; an *actual* file object having a fileno() method (it is used to get the file descriptor); the PIPE marker (an OS pipe is created and its two descriptors are used on parent and child); or None. I hope it's more clear now. Python objects are only meaningful *inside* a Python program, but an *external* program can't use them directly. A simple example: import subprocess import sys print One sys.stdout = open(out.txt,w) print Two subprocess.call(ls, shell=True) print Three Try to guess where each output line, and the ls outout, will appear. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd handling of type.__init__ bases
On Feb 28, 10:50 pm, [EMAIL PROTECTED] wrote: I encountered an oddity in attempting to use a metaclass to perform mix-in inheritance for classes. I've attached a small demonstration file. Have I misunderstood the bases argument for type.__init__ or should this be submitted as a bug? After a quick look at your example: * you are mixing classic classes (abase) and new-style classes (A and B), which often creates problems. * type.__init__ does not set the base classes, type.__new__ does this. What you want to achieve could be done with: class meta3(type): def __new__(cls, name, bases, dict): bases += (abase,) return type.__new__(cls, name, bases, dict) HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list