Wing IDE 3.2.1 released
Hi, Wingware has released version 3.2.1 of Wing IDE, our integrated development environment for the Python programming language. This bug fix release includes the following: * Improved support for Snow Leopard (OS X 10.6) * Support for x86_64 Python 2.4+ on OS X * Support for Stackless Python 3.0 and 3.1 * Fixed Stackless Python support on 64-bit Linux * Several other bug fixes; See the change log for details: http://wingware.com/pub/wingide/3.2.1/CHANGELOG.txt *Wing 3.2 Highlights* Version 3.2 of Wing IDE includes the following new features not present in Wing IDE 3.1: * Support for Python 3.0 and 3.1 * Rewritten version control integration with support for Subversion, CVS, Bazaar, git, Mercurial, and Perforce (*) * Added 64-bit Debian, RPM, and tar file installers for Linux * File management in Project view (**) * Auto-completion in the editor obtains completion data from live runtime when the debugger is active (**) * Perspectives: Create and save named GUI layouts and optionally automatically transition when debugging is started (*) * Improved support for Cython and Pyrex (*.pyx files) * Added key binding documentation to the manual * Added Restart Debugging item in Debug menu and tool bar (**) (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal and Professional only. The release also contains many other minor features and bug fixes; see the change log for details: http://wingware.com/pub/wingide/3.2.1/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.1http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.1 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.1http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, version control, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.2 supports Python versions 2.0.x through 3.1.x. *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license:https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[ANN] Intro+Intermediate Python course, San Francisco, Nov 2009
(COMPREHENSIVE) INTRO+INTERMEDIATE PYTHON Mon-Wed, 2009 Nov 9-11, 9AM - 5PM If you have been in the Python community for some time, you may be familiar with my introductory (and advanced) courses. Many new Python intro courses have been added over the past few years, so aren't all classes the same? Most introductory courses focus on teaching you the syntax and giving you an idea of a language's flow control and data types. However, this can only get your so far. Although our course may appear to be for those new to Python, it is also perfect for those who have tinkered with it and want to fill in the gaps or desire more in-depth formal training. It combines the best of both an introduction to the language as well as covering intermediate language fundamentals that can make you more effective, even as a beginner. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. Daily hands-on labs will help hammer the concepts home. Come join me, Wesley Chun, author of Prentice-Hall's bestseller Core Python Programming, for a comprehensive course coming up this Fall in beautiful Northern California to get up-to-speed with Python as quickly and as in-depth as possible! WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA INFO: http://cyberwebconsulting.com (click Python Training) FLYER: http://starship.python.net/crew/wesc/flyerPP1nov09.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites FREE PREVIEW: at the website below, you will find (and can download) a video clip of a live lesson that was delivered recently to get an idea of the lecture style and interactive classroom environment. FREE PREVIEW 2: Partnering with O'Reilly and Pearson, I delivered a one-hour introductory webcast at Safari Books Online earlier this year called BIWhat is Python?/I/B. You will get both my lecture style as well as an overview of the material covered in the course. http://www.safaribooksonline.com/events/WhatIsPython.html (event announcement) http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcastInfo.php?page=WhatIsPython (free download with registration) See website for costs, venue info, and registration; various discounts available. Hope to see you there! - wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Core Python Programming, Prentice Hall, (c)2007, 2001 Python Fundamentals DVD, Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[ANN] argparse 1.0.1 - Command-line parsing library
= Announcing argparse 1.0.1 = The argparse module provides an easy, declarative interface for creating command line tools, which knows how to: * parse the arguments and flags from sys.argv * convert arg strings into objects for your program * format and print informative help messages * and much more... The argparse module improves on the standard library optparse module in a number of ways including: * handling positional arguments * supporting sub-commands * allowing alternative option prefixes like + and / * handling zero-or-more and one-or-more style arguments * producing more informative usage messages * providing a much simpler interface for custom types and actions Download argparse = The argparse homepage has links for source, MSI and single file distributions of argparse: http://code.google.com/p/argparse/ About this release == This is a bugfix release. Various small bugs were squashed, most notably the silencing of the Python 2.6 buggy Exception.message warnings. See the news file for detailed information: http://argparse.googlecode.com/svn/tags/r101/NEWS.txt -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: Odd/Weird errors with FTPLib
On Sep 15, 1:32 am, MRAB pyt...@mrabarnett.plus.com wrote: Bakes wrote: On Sep 13, 11:47 pm, MRAB pyt...@mrabarnett.plus.com wrote: Bakes wrote: On 13 Sep, 22:41, Chris Rebert c...@rebertia.com wrote: On Sun, Sep 13, 2009 at 2:34 PM, Bakes ba...@ymail.com wrote: I am using a simple python script to download my logfiles. This is on a while loop, the logfile grows rapidly, so it is necessary for python to start downloading the new script as soon as it has finished the old. It works fine (for about 20 minutes), then crashes. I have removed a couple of excepts, and have narrowed the error down to a 'error_perm: 550 logfile.log: The data is invalid.' error. Does anyone know what the problem might be regarding this, and what I might do to fix it? Including an actual code snippet and the full error traceback would help a lot. According tohttp://en.wikipedia.org/wiki/List_of_FTP_server_return_codes, error code 550 translates to: Requested action not taken. File unavailable (e.g., file not found, no access). Does the logfile get rotated or something, thus causing it to briefly not exist? It might also help if you explain how your logfile system works. Cheers, Chris --http://blog.rebertia.com It's a cod4 gameserver logfile, being downloaded for a python bot to parse. The logfile is downloaded using this try/except while loop. while True: try: if ftp == False: self.debug('FTP connection not active, attempting to (re)connect') ftp = self.ftpconnect() size=os.path.getsize('games_mp.log') ftp.retrbinary('RETR ' + os.path.basename(self.ftpconfig ['path']), handleDownload, rest=size) if self.console._paused: self.console.unpause() except: print error self.debug('Lost connection to server, pausing until updated properly, Sleeping 10 seconds') self.console.pause() try: ftp.close() self.debug('FTP Connection Closed') except: self.debug('FTP does not appear to be open, so not closed') ftp = False time.sleep(10) I can only assume that occasionally, the logfile is being written to by the gameserver at the same time that it's downloading. If this was the case, do you think a try: download except: sleep 900msec then download loop would work? Bare excepts are almost always a bad idea because they'll catch _all_ exceptions, both those you expect could happen and those you don't. Catch only those you expect. For example, if the file 'games_mp.log' doesn't exist then os.path.getsize('games_mp.log') will raise an exception, and if you forgot to import the os module then that will raise a NameError exception. Anyway, I can't see how you leave the loop; I'd expect something like a 'break' statement. And as a matter of style, I'd prefer None to False to indicate when there's no FTP connection (and if not ftp instead of if ftp == False). I removed the try/except and saw when it failed. I'll change those things, games_mp.log is guaranteed to be there (file made in another script), os is imported correctly. So, what do you think the error could be? How does control leave the while loop? If you're running on Windows and you're opening the file 'games_mp.log' with mode 'w' then there'll be the issue of the line-endings. If the log file on the server uses '\n' for the line endings and you're using '\r\n' then os.path.getsize('games_mp.log') will return a larger size then you expect. In that case, could ftp.retrbinary() be complaining because it's given you the entire file and then you're trying to download from an offset that's beyond the end? For example, suppose the file on the server contains just foo\n (4 bytes): 1. You open a file locally in text mode ('w'). 2. You download the entire file, foo\n. 3. You write out the data, but because you've opened in text mode it writes foo\r\n to the file. The local file size is now 5 bytes. 4. The loop means that you then try to download from offset 5, which is beyond the end of the file on the server. 5. Error? It opens it in append mode, and if it errors with that message, the ending is different. I have come across that problem before, and it has been fixed (download in binary is the fix, mostly). -- http://mail.python.org/mailman/listinfo/python-list
[ANN] argparse 1.0.1 - Command-line parsing library
= Announcing argparse 1.0.1 = The argparse module provides an easy, declarative interface for creating command line tools, which knows how to: * parse the arguments and flags from sys.argv * convert arg strings into objects for your program * format and print informative help messages * and much more... The argparse module improves on the standard library optparse module in a number of ways including: * handling positional arguments * supporting sub-commands * allowing alternative option prefixes like + and / * handling zero-or-more and one-or-more style arguments * producing more informative usage messages * providing a much simpler interface for custom types and actions Download argparse = The argparse homepage has links for source, MSI and single file distributions of argparse: http://code.google.com/p/argparse/ About this release == This is a bugfix release. Various small bugs were squashed, most notably the silencing of the Python 2.6 buggy Exception.message warnings. See the news file for detailed information: http://argparse.googlecode.com/svn/tags/r101/NEWS.txt -- http://mail.python.org/mailman/listinfo/python-list
Re: list as an instance attribute
Robin Becker wrote: Python is often put forward as a as a finger friendly language, but we have capitals encouraged for user class names and for some common values eg None, True, False these are required. And I'm glad it is, or else I'll get a finger-sore and an eye-sore -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Code Jam language usage
(If you see any error in what I have written here, please tell me.) So far I've never done a Google Code Jam. There are 12 problems there (G.C.Jam 2009), and the best solutions are 9 in C++ and 3 in C (I think they are the best solutions, but I am not sure). The code of all such best solutions is tidy, well formatted, and written in a quite compact style, with little extra space, few lines of code, and short variable names (often 1 or 2 chars long). The C++ code by TripleM shows he/she is also a topcoder, such code is written in an aggressive style: they show a standard header where all data structures from C++ STL are imported, plus some handy and common templates/functions (with vector, matrix, etc, operations). I think it may be positive to add similar handy templates/functions/data structures to Boost or the STL. For example I've lost count of how many times I have seen reimplemented a vector class/struct with dot products, etc. Generally in such contests programs are not that similar to real-world ones, for example inputs ranges/sizes are perfectly known. But probably this makes such contests better. The plots show that Python programmers seem to produce a higher percentage of working programs compared to C ones, curiously Pascal programmers have an higher percentage still. As usual Haskell programmers look smart. In other similar contests Python often doesn't allow to produce the best solutions because it's too much slow at runtime, even using Psyco. For example in the Code Jam the large problems may require lot of processing. But experience shows that even for such algorithmic problems the choice of language isn't the most important thing. The most important is the choice of a good algorithm, the choice of good data structures, the use of as little dynamic memory allocations as possible, and then only now the language becomes important for the running time. Problems in such contests are often designed with well defined input ranges/sizes, and dynamic allocations are one of the slower things in such programs. So when possible it's better to use static memory, for example a statically allocated matrix in C. Python encourages the programmer to use a programming style where dynamic allocations of memory are very common, but when performance matters it's better to reduce them to the minimun in the inner loops. For example this is (I think) the best Python program for the Welcome to Code Jam qualification problem: # By ZIBADA import sys import psyco psyco.full() def isset(a, b): return ((a b) 1) != 0 def dbg(a): sys.stderr.write(str(a)) def readint(): return int(raw_input()) def readfloat(): return float(raw_input()) def readarray(foo): return [foo(x) for x in raw_input().split()] def doit(i, j): if (i, j) in mem: return mem[(i, j)] if (j = len(b)): return 1 if (i = len(a)): return 0 res = doit(i + 1, j) if (a[i] == b[j]): res += doit(i + 1, j + 1) res %= 1 mem[(i, j)] = res return res def run_test(test): #dbg(Test %d\n % (test + 1)) global a, b, mem a = raw_input() b = welcome to code jam mem = {} print Case #%d: %04d % (test + 1, doit(0, 0)) for test in range(readint()): run_test(test) It uses dynamic allocation and recursive calls. It processes the large input in 0.56 s on my old PC. The following is instead the starting part of (I think) the best overall solution, that is in C (the algorithm used is a basic and well known one, no recursions used. Run time is very fast, I can't time it): // By LayCurse char a[512]; char b[32] = welcome to code jam; int d[512][32]; int main() { ... for (t = 1;t = tc; t++) { fgets(a, 505, fp); memset(d, 0, sizeof(d)); ... It uses a static matrix, and the number of columns is 32 instead of 19 (= len(welcome to code jam)) so the compiler can use just a shift to find the right row start. One memset clears the whole matrix for each input string. This is the same C code by LayCurse translated (with few small improvements) to Python+Psyco, it runs in about 0.14 seconds here on the same dataset. Using the right algorithm, right data structures, and minimizing memory allocations, with Psyco you can often go fast enough: from array import array def main(): b = welcome to code jam len_b = len(b) d = [array('l', [0]) * len_b for _ in xrange(512)] for t in xrange(int(raw_input())): a = raw_input() for row in d: # set d to 0 for j in xrange(len_b): row[j] = 0 if a[0] == b[0]: d[0][0] = 1 for i in xrange(1, len(a)): d[i][0] += d[i - 1][0] if b[0] == a[i]: d[i][0] += 1 for j in xrange(1, len_b): d[i][j] += d[i - 1][j] if b[j] == a[i]: d[i][j] += d[i - 1][j - 1] d[i][j] %= 1 print Case
Re: python decimals
On Sep 15, 2:27 am, Andrew Svetlov andrew.svet...@gmail.com wrote: Is there some kind of python binding for decNumber library? Standard decimal.Decimal is good enough, but very slow. My current project toughly coupled with 'currency' operations and we have performance problems related to decimal calculations. From my perspective decNumber is fast and has well wide domain to represent and process all required set of numbers - we don't need to work with 'almost infinite numbers' as python decimal can. I tried to google for desired binding - but found nothing. gmpy is interesting project, but supported types is not exactly what we need - rationals and big floats is not decimals in fixed point notation. My team discussed about making own python binding of decNumber - but before we start this task I like to ask python community: is there existing implementation? I don't want to invent the wheel again. As far as I know, no such bindings exist. There have been various efforts to rewrite the decimal module in C, but (again as far as I know) none of those efforts have come to fruition yet. -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: VT100 in Python
On 2009-09-14, Wolfgang Rohdewald wolfg...@rohdewald.de wrote: that should be easy using regular expressions And they say irony doesn't work well on Usenet! -- Grant Edwards grante Yow! My nose feels like a at bad Ronald Reagan movie ... visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
Robin Becker ro...@reportlab.com writes: well allegedly, the medium is the message so we also need to take account of language in addition to the meaning of communications. I don't believe all languages are equivalent in the meanings that they can encode or convey. Our mathematics is heavily biassed towards continuous differential systems and as a result we end up with many physical theories that have smooth equilibrium descriptions, we may literally be unable to get at other theories of the physical world because our languages fall short. This is the old Sapir-Whorf hypothesis, which fell out of favour among linguists half a century ago already. 1) Language does not constrain human thought, and 2) any two human languages are both capable of expressing the same things, though one may already have a convenient lexeme for the topic at hand while the other uses circumlocution. -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Sep 14, 1:24 pm, Terry Reedy tjre...@udel.edu wrote: r wrote: So how many letters do we need? 50, 100, 1000? From Wikipedia IPA article: Occasionally symbols are added, removed, or modified by the International Phonetic Association. As of 2008, there are 107 distinct letters, 52 diacritics, and four prosody marks in the IPA proper. HaHa! and here is my favorite paragraph from that article.. The IPA is designed to represent only those qualities of speech that are distinctive in spoken language: phonemes, intonation, and the separation of words and syllables.[1] To represent additional qualities of speech such as tooth gnashing, lisping, and sounds made with a cleft palate, an extended set of symbols called the Extensions to the IPA is used.[2] LOL! (a smilie just would not have sufficed!) -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy NaN, not surviving pickle/unpickle?
On Sep 14, 4:05 pm, Scott David Daniels scott.dani...@acm.org wrote: Steven D'Aprano wrote: On Sun, 13 Sep 2009 17:58:14 -0500, Robert Kern wrote: Exactly -- there are 2**53 distinct floats on most IEEE systems, the vast majority of which might as well be random. What's the point of caching numbers like 2.5209481723210079? Chances are it will never come up again in a calculation. You are missing a few orders of magnitude here; there are approx. 2 ** 64 distinct floats. 2 ** 53 is the mantissa of regular floats. There are 2**52 floats X where 1.0 = X 2.0. The number of normal floats is 2 ** 64 - 2 ** 52 + 1. Since we're being picky here: Don't you mean 2 ** 64 - 2 ** 54 + 1? :) -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
On Tuesday 15 September 2009 03:08:59 Oltmans wrote: match=[1,2,3,4,5] def elementsPresent(aList): result=False if not aList: return False for e in aList: if e in match: result=True else: result = False return result elementsPresent([6,7,8,9,5]) # should return True because 5 is present in list named match. What are you trying to do? Your code will only work if the last item in aList is in the match global. Is this what you want? or do you want: (i) a True if All the elements in match are in aList, else False? (ii) a True if any one or more of the members of match are in aList? (iii) Something else? - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove empty strings from list
Helvin a écrit : Hi, Sorry I did not want to bother the group, but I really do not understand this seeming trivial problem. I am reading from a textfile, where each line has 2 values, with spaces before and between the values. I would like to read in these values, but of course, I don't want the whitespaces between them. I have looked at documentation, and how strings and lists work, but I cannot understand the behaviour of the following: line = f.readline() line = line.lstrip() # take away whitespace at the beginning of the readline. file.readline returns the line with the ending newline character (which is considered whitespace by the str.strip method), so you may want to use line.strip instead of line.lstrip list = line.split(' ') Slightly OT but : don't use builtin types or functions names as identifiers - this shadows the builtin object. Also, the default behaviour of str.split is to split on whitespaces and remove the delimiter. You would have better results not specifying the delimiters here: a a a a .split(' ') ['', 'a', '', 'a', '', 'a', '', 'a', ''] a a a a .split() ['a', 'a', 'a', 'a'] # the list has empty strings in it, so now, remove these empty strings A problem you could have avoided right from the start !-) for item in list: if item is ' ': Don't use identity comparison when you want to test for equality. It happens to kind of work in your above example but only because CPython implements a cache for _some_ small strings, but you should _never_ rely on such implementation details. A string containing accented characters would not have been cached: s = 'ééé' s is 'ééé' False Also, this is surely not your actual code : ' ' is not an empty string, it's a string with a single space character. The empty string is ''. And FWIW, empty strings (like most empty sequences and collections, all numerical zeros, and the None object) have a false value in a boolean context, so you can just test the string directly: for s in ['', 0, 0.0, [], {}, (), None]: if not s: print '%s' is empty, so it's false % str(s) print 'discard these: ',item index = list.index(item) del list[index] # remove this item from the list And then you do have a big problem : the internal pointer used by the iterator is not in sync with the list anymore, so the next iteration will skip one item. As general rule : *don't* add / remove elements to/from a sequence while iterating over it. If you really need to modify the sequence while iterating over it, do a reverse iteration - but there are usually better solutions. else: print 'keep this: ',item The problem is, Make it a plural - there's more than 1 problem here !-) when my list is : ['44', '', '', '', '', '', '0.0\n'] The output is: len of list: 7 keep this: 44 discard these: discard these: discard these: So finally the list is: ['44', '', '', '0.0\n'] The code above removes all the empty strings in the middle, all except two. My code seems to miss two of the empty strings. Would you know why this is occuring? cf above... and below: alist = ['44', '', '', '', '', '', '0.0'] for i, it in enumerate(alist): ... print 'i : %s - it : %s' % (i, it) ... if not it: ... del alist[idx] ... print alist is now %s % alist ... i : 0 - it : 44 alist is now ['44', '', '', '', '', '', '0.0'] i : 1 - it : alist is now ['44', '', '', '', '', '0.0'] i : 2 - it : alist is now ['44', '', '', '', '0.0'] i : 3 - it : alist is now ['44', '', '', '0.0'] Ok, now for practical answers: 1/ in the above case, use line.strip().split(), you'll have no more problem !-) 2/ as a general rule, if you need to filter a sequence, don't try to do it in place (unless it's a *very* big sequence and you run into memory problems but then there are probably better solutions). The common idioms for filtering a sequence are: * filter(predicate, sequence): the 'predicate' param is callback function which takes an item from the sequence and returns a boolean value (True to keep the item, False to discard it). The following example will filter out even integers: def is_odd(n): return n % 2 alist = range(10) odds = filter(is_odd, alist) print alist print odds Alternatively, filter() can take None as it's first param, in which case it will filter out items that have a false value in a boolean context, ie: alist = ['', 'a', 0, 1, [], [1], None, object, False, True] result = filter(None, alist) print result * list comprehensions Here you directly build the result list: alist = range(10) odds = [n for n in alist if n % 2] alist = ['', 'a', 0, 1, [], [1], None, object, False, True] result = [item for item in alist if item] print result HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Incremental project based programming guide
On Tuesday 15 September 2009 04:43:46 bouncy...@gmail.com wrote: I was wondering if anyone had actually designed their programming text around incremental parts of a project and then taken the results of the project at each chapter and created something of value. specifically in referwnce to python however other examples. ALl of education was around pointless and unapplicable theory texts for which I am reaping nothing. Surely someone has seen this in actiom to whit: ch1 design of problem ch2 design taken out of ch1 then done in ch2 to take input/ output for a smaller part ch3 take info from chs 1...@2 to craft an answer that is from the same problemto a theoretical chapter say 30 with a gui or some such. deitel and associates were unfortunately part of some of my worst exampes--drills applenty with little to no application. much appreciated towards python application and thanks in advance I cannot parse this. I get the idea that you are talking about a teaching text with certain characteristics. I cannot figure out if you are: (i) for the idea. (ii) against it. (ii) looking for something like it. Please elucidate. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Monday 14 September 2009 14:06:36 Christopher Culver wrote: This is the old Sapir-Whorf hypothesis, which fell out of favour among linguists half a century ago already. 1) Language does not constrain human thought, and 2) any two human languages are both capable of expressing the same things, though one may already have a convenient lexeme for the topic at hand while the other uses circumlocution. 1) Is an assumption, not a proven fact. falling out of favour is merely fashion amongst people who are dabbling in fuzzy areas where the hard discipline of the scientific method is inapplicable, because it is kind of hard to prove or disprove that my thinking and yours differ because my first language is different to yours. - we end up talking about our beliefs, after telling war stories. 2) Is about as useful as stating that any Turing complete language and processor pair is capable of solving any computable problem, given enough time. So why are we not all programming in brainfuck? Or speaking the language of the people who wrote linear B? When a language lacks a word for a concept like window, then (I believe :-) ), it kind of puts a crimp in the style of thinking that a person will do, growing up with only that language. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove empty strings from list
Dave Angel a écrit : (snip) As Chris says, you're modifying the list while you're iterating through it, and that's undefined behavior. Why not do the following? mylist = line.strip().split(' ') mylist = [item for item in mylist if item] Mmmm... because the second line is plain useless when calling str.split() without a delimiter ?-) mylist = line.strip().split() will already do the RightThing(tm). -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove empty strings from list
Dennis Lee Bieber a écrit : (snip) All of which can be condensed into a simple for ln in f: wrds = ln.strip() # do something with the words -- no whitespace to be seen I assume you meant: wrds = ln.strip().split() ?-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Retracing your steps in an interactive python env
On Sep 14, 9:52 pm, Jack Norton j...@0x6a.com wrote: Anyway, I have created a function using def, and well, I like the way it is working, however... I have already filled the command line history buffer (the com.exe buffer?) so _what_ I actually filled this def with is lost. Now, it isn't that complicated, and I can easily re-write the function off the top of my head, however it would be really nice to be able to _ask_ python what makes up a def. IPython has it's own history. Accessible using the %hist magic command, the default is 1000 lines but can be changed in the ipythonrc file. There are many other magic commands which are very useful for interactive development. For example there's a %log command that enables logging of your session in a file. Another example is %save to store parts of your history into a file and %edit to launch an external editor to edit a bunch of commands from the history or enter longer blocks of code. Take a look at the documentation of the magic commands by entering %magic. Bernhard -- http://mail.python.org/mailman/listinfo/python-list
PyQT Qthread stuck main app
Hi everybody, I've got a simple GUI app written in python and pyqt. I'm having 2 buttons - start and stop start calls a function that start a thread and stop stops it. my problem is that when start is pusshed the entire window stuck and it's impossible to push the STOP button and even when it looks like it's been pushed it actually don't do anything. any idea how to fix it? Thanks Dave class myThread(QtCore.QThread): def__init__(self): self.alive = 1 def run(self): while self.alive: print Alive print Not Alive def stop(self): print stop pushed self.alive = 0 class GUI(QtGui.QMainWindow): def __init__(self): # all kind of initialization @QtCore.pyqtSignature(start) def on_start_clicked(self): self.cThread = myThread() self.cThread.start() @QtCore.pyqtSignature(stop) def on_stop_clicked(self): self.cThread.stop() -- http://mail.python.org/mailman/listinfo/python-list
How to define a class that can act as dictionary key?
Hi, I'd like to define a class to use it as a dictionary key: class dict_entry: def __init__(self, term = , doc_freq = 0): self.term = term self.doc_freq = doc_freq def __cmp__(self, entry): return isinstance(entry, dict_entry) and cmp(self.term, entry.term) def __str__(self): return term + , + str(docid) And later... entry = dict_entry(term, len(index[term])) self.index[entry] = [] When I run it, it says TypeError: unhashable instance It looks like I can't use the new class object as the dictionary key. What should I do? -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Code Jam language usage
(There can be ways to speed up this Python code, I have not tried to use a 1D matrix with shifts to find the right starting of the rows as in C, and often in such dynamic programming algorithms you can just keep 2 rows to avoid storing the whole dynamic matrix, this saves memory and speed up code because there are less cache misses. It was easy to do, running time about 0.13 seconds: from array import array def main(): b = welcome to code jam len_b = len(b) di = array('l', [0]) * len_b dim1 = array('l', [0]) * len_b for t in xrange(int(raw_input())): a = raw_input() for j in xrange(len_b): # set to 0 di[j] = 0 dim1[j] = 0 if a[0] == b[0]: dim1[0] = 1 for i in xrange(1, len(a)): for j in xrange(len_b): # set to 0 di[j] = 0 di[0] += dim1[0] if b[0] == a[i]: di[0] += 1 for j in xrange(1, len_b): di[j] += dim1[j] if b[j] == a[i]: di[j] += dim1[j - 1] di[j] %= 1 di, dim1 = dim1, di print Case #%d: %04d % (t+1, dim1[len_b - 1]) import psyco; psyco.full() main() Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: How to define a class that can act as dictionary key?
Lambda stephenh...@gmail.com writes: When I run it, it says TypeError: unhashable instance It looks like I can't use the new class object as the dictionary key. What should I do? You have to add a __hash__ method. Untested: def __hash__(self): return (self.term, self.doc_freq) is probably the easiest. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to define a class that can act as dictionary key?
On Tue, Sep 15, 2009 at 9:47 PM, Lambda stephenh...@gmail.com wrote: When I run it, it says TypeError: unhashable instance I believe you need to implement __hash__() for the class. Make sure your class returns a unique identifier for a certain value. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to define a class that can act as dictionary key?
Paul Rubin schrieb: Lambda stephenh...@gmail.com writes: When I run it, it says TypeError: unhashable instance It looks like I can't use the new class object as the dictionary key. What should I do? You have to add a __hash__ method. Untested: def __hash__(self): return (self.term, self.doc_freq) is probably the easiest. The __hash__ function must return an integer: class Hash(object): ... def __hash__(self): ... return (1, 2) ... hash(Hash()) Traceback (most recent call last): File stdin, line 1, in module TypeError: an integer is required class Hash(object): ... def __hash__(self): ... return hash((1, 2)) ... hash(Hash()) 3713081631934410656 Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: VTK install
On Sep 15, 6:29 am, Gib gib.bo...@gmail.com wrote: As part of the MayaVi install, I need to install VTK. ... Since VTK appears to be installed, I'm guessing that either the path setting is wrong, or python is not using PYTHONPATH. How can I check that PYTHONPATH is being used? The paths in PYTHONPATH should show un sys.path python variable. So just do from a python prompt import sys; sys.path and check if the VTK directories are listed. You colòud aslo tentatively append your path to sys.path and then try again import vtk to see if it is a path problem or something else ... Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to define a class that can act as dictionary key?
Christian Heimes li...@cheimes.de writes: def __hash__(self): return (self.term, self.doc_freq) is probably the easiest. The __hash__ function must return an integer: Oh oops. Try: def __hash__(self): return hash((self.term, self.doc_freq)) -- http://mail.python.org/mailman/listinfo/python-list
str.split() with empty separator
Hi! 'abc'.split('') gives me a ValueError: empty separator. However, ''.join(['a', 'b', 'c']) gives me 'abc'. Why this asymmetry? I was under the impression that the two would be complementary. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQT Qthread stuck main app
On Tue Sep 15 12:59:35 CEST 2009, daved170 wrote: my problem is that when start is pusshed the entire window stuck and it's impossible to push the STOP button and even when it looks like it's been pushed it actually don't do anything. any idea how to fix it? Does adding a call to the base class's __init__() method help? class myThread(QtCore.QThread): def__init__(self): QtCore.QThread.__init__(self) self.alive = 1 David -- http://mail.python.org/mailman/listinfo/python-list
Re: How to define a class that can act as dictionary key?
Lambda a écrit : Hi, I'd like to define a class to use it as a dictionary key: Others already answered (define the __hash__ method). Just one point: the value returned by the __hash__ method should not change for the lifetime of the object. So if you use instance attributes to compute the hash, make sure these attributes won't change, else you may have a surprise: class Foo(object): ...def __init__(self, a, b): ...self.a = a; self.b = b ...def __hash__(self): ...return hash((self.a, self.b)) ... f = Foo(un, deux) d = {f:un deux} d[f] un deux f.a = zero d[f] Traceback (most recent call last): File stdin, line 1, in module KeyError: __main__.Foo object at 0x9d04b2c HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: str.split() with empty separator
On Tue, Sep 15, 2009 at 10:31 PM, Ulrich Eckhardt eckha...@satorlaser.comwrote: 'abc'.split('') gives me a ValueError: empty separator. However, ''.join(['a', 'b', 'c']) gives me 'abc'. Why this asymmetry? I was under the impression that the two would be complementary. I'm not sure about asymmetry, but how would you implement a split method with an empty delimiter to begin with? It doesn't make much sense anyway. If you feel strongly to make it do what you want it to do, it might be a good idea to submit it to Python-ideas mailing list, or such. Otherwise, it doesn't hurt to iterate over the string and make use of them, right? ;) Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
preferred way to set encoding for print
hi folks, i am doing my first steps in the wonderful world of python 3. some things are good. some things have to be relearned. some things drive me crazy. sadly, i'm working on a windows box. which, in germany, entails that python thinks it to be a good idea to take cp1252 as the default encoding. so just coz i got my box in germany means i can never print out a chinese character? say what? i have no troubles with people configuring their python installation to use any encoding in the world, but wouldn't it have been less of a surprise to just assume utf-8 for any file in/output? after all, it is already the default for python source files as far as i understand. someone might think they're clever to sniff into the system and make the somehwat educated guess that this dude's using cp1252 for his files. but they would be wrong. so: how can i tell python, in a configuration or using a setting in sitecustomize.py, or similar, to use utf-8 as a default encoding? there used to be a trick to say `reload(sys);sys.setdefaultencoding ('utf-8')`, but that has no effect in py3.0.1. also, i cannot set `sys.stdout.encoding`; is there a way to re-open that stream with a different encoding? in all, i believe it is quite unsettling to me to see that, on my py3 installation, sys.getdefaultencoding() == 'utf-8' sys.stdout.encoding == 'cp1252' locale.getlocale() == (None, None) locale.getdefaultlocale() == ('de_DE', 'cp1252') which to me makes as much sense as a blackcurrant tart thrown into space. worse, locale.setlocale( locale.LC_ALL, locale.getdefaultlocale() ) results in locale.Error: unsupported locale setting this bloody thing doesn't accept its *own* output. attempts to feed that locale beast with anything but the empty string or 'C' were all doomed. it would take a very patient and eloquent person to explain that in a credible fashion to me. my word for this is, 'broken'. i would very much like to rid myself of these considerations. just say it's all utf-8, wash'n'go. my attempts of changing python's mind using the locale module have failed so far. otherwise, i for one don't want to touch that locale thing with a very long pole. as far as i can see, it does not work as documented. the platform dependencies are also a clear OFF LIMITS sign to me. any suggestions? cheers, ~flow -- http://mail.python.org/mailman/listinfo/python-list
Re: str.split() with empty separator
Ulrich Eckhardt wrote: Hi! 'abc'.split('') gives me a ValueError: empty separator. However, ''.join(['a', 'b', 'c']) gives me 'abc'. Why this asymmetry? I was under the impression that the two would be complementary. Uli I think the problem is that join() is lossy; if you try .join(['a', 'bcd', 'e']) then there's no way to reconstruct the original list with split(). Now that can be true even with actual separators, but perhaps this was the reasoning. Anyway, if you want to turn a string into a list of single-character strings, then use list(abcde) DaveA -- http://mail.python.org/mailman/listinfo/python-list
LinkedIn Messages, 9/15/2009
LinkedIn REMINDERS: Invitation Reminders: * View Invitation from Tim Heath http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/blk/I287618177_3/0PnPsTcjwNdzsUcAALqnpPbOYWrSlI/svi/ * View Invitation from Navneet Khanna http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/blk/I309673816_3/0PnPoNe3cTdzAMcQALqnpPbOYWrSlI/svi/ * View Invitation from Abhishek Wadhava http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/blk/I301742673_3/0PnPcTdz8QdP4McQALqnpPbOYWrSlI/svi/ PENDING MESSAGES: There are a total of 10 messages awaiting your response. Visit your InBox now: http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/inb/ -- Don't want to receive email notifications? Adjust your message settings: https://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/prv/ LinkedIn values your privacy. At no time has LinkedIn made your email address available to any other LinkedIn user without your permission. (c) 2009, LinkedIn Corporation. -- http://mail.python.org/mailman/listinfo/python-list
ANN: OpenOpt 0.25 - free Python-written numerical optimization framework with automatic differentiation
OpenOpt is cross-platform (Windows, Linux, Mac OS etc) Python-written framework. If you have a model written in FuncDesigner (http:// openopt.org/FuncDesigner), you can get 1st derivatives via automatic differentiation (http://en.wikipedia.org/wiki/ Automatic_differentiation) (some examples here: http://openopt.org/NumericalOptimizationForFuncDesignerModels). License BSD allows to use it in both open- and closed-code soft. For more details see http://openopt.org/ http://forum.openopt.org/viewtopic.php?id=141 Regards, D. -- http://mail.python.org/mailman/listinfo/python-list
ANN: FuncDesigner 0.15 - free Python-written framework with automatic differentiation
FuncDesigner is cross-platform (Windows, Linux, Mac OS etc) Python- written framework with automatic differentiation (http:// en.wikipedia.org/wiki/Automatic_differentiation). License BSD allows to use it in both open- and closed-code soft. It has been extracted from OpenOpt framework as a stand-alone package, still you can easily optimize models written in FuncDesigner by OpenOpt (some examples here: http://openopt.org/NumericalOptimizationForFuncDesignerModels) For more details see http://openopt.org/FuncDesigner http://forum.openopt.org/viewtopic.php?id=141 Regards, D. -- http://mail.python.org/mailman/listinfo/python-list
Re: Incremental project based programming guide
On Tue, Sep 15, 2009 at 2:22 AM, Hendrik van Rooyen hend...@microcorp.co.za wrote: On Tuesday 15 September 2009 04:43:46 bouncy...@gmail.com wrote: I was wondering if anyone had actually designed their programming text around incremental parts of a project and then taken the results of the project at each chapter and created something of value. specifically in referwnce to python however other examples. ALl of education was around pointless and unapplicable theory texts for which I am reaping nothing. Surely someone has seen this in actiom to whit: ch1 design of problem ch2 design taken out of ch1 then done in ch2 to take input/ output for a smaller part ch3 take info from chs 1...@2 to craft an answer that is from the same problemto a theoretical chapter say 30 with a gui or some such. deitel and associates were unfortunately part of some of my worst exampes--drills applenty with little to no application. much appreciated towards python application and thanks in advance I cannot parse this. I get the idea that you are talking about a teaching text with certain characteristics. I cannot figure out if you are: (i) for the idea. (ii) against it. (ii) looking for something like it. Please elucidate. Certaintly I am looking for options (i) and (iii) thanks :) mobile wap browsers don't make the best of composition platforms. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: overrideredirect vs. text entry etc. widget
On Sep 14, 10:43 pm, kernus ker...@gmail.com wrote: I just googled this post: http://mail.python.org/pipermail/python-list/2006-September/575832.html something like: from Tkinter import * root = Tk() Entry(root).pack() Button(root, text='Quit', command=sys.exit).pack() root.overrideredirect(1) root.mainloop() the button works boths under linux(debian) and windows, but the entry widget only works on windows, any idea? I am making a skinnalbe music player, so the issue must be solved. Whats interesting is that if you call overrideredirect from a button command, it works as expected. Well, at least the text entry field behaves for me on Ubuntu... from Tkinter import * root = Tk() def override(): if root.overrideredirect(): root.overrideredirect(False) else: root.overrideredirect(True) root.withdraw() root.deiconify() Entry(root).pack() Button(root, text='Override', command=override).pack() root.mainloop() ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: MayaVi install
On 2009-09-14 23:07 PM, Gib wrote: I am trying to follow the instructions for installing MayaVi given on the Enthought site: http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/installation.html I'm following the step-by-step instructions to install with eggs under Windows. When I get to this point: easy_install Sphinx EnvisageCore EnvisagePlugins configobj Sphinx 0.6.3 is installed OK, but when envisagecore 3.1.1 is being installed, after doing a few steps it fails with the message: error: Setup script exited with error: Unable to find vcvarsall.bat A search showed that vcvarsall.bat is where you might expect to find it, in C:\Program Files\Microsoft Visual Studio 8\VC I'm not sure what to do now. Probably put that directory on your PATH. You will get better Mayavi support on the enthought-dev mailing list: https://mail.enthought.com/mailman/listinfo/enthought-dev -- 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: PyQT Qthread stuck main app
daved170 wrote: On Sep 15, 2:54 pm, David Boddie dbod...@trolltech.com wrote: On Tue Sep 15 12:59:35 CEST 2009, daved170 wrote: my problem is that when start is pusshed the entire window stuck and it's impossible to push the STOP button and even when it looks like it's been pushed it actually don't do anything. any idea how to fix it? Does adding a call to the base class's __init__() method help? class myThread(QtCore.QThread): def__init__(self): QtCore.QThread.__init__(self) self.alive = David Hi David, I did write that line. I forgot copying it to my code here. The problem still happens. When I kill the app only then I see the message stopped pushed. any other idead? thanks Dave I hesitated to respond, since I don't know/use Qt. But maybe I can help. I suspect your problem is that the background thread is hogging all the time. The GIL (Global Interpreter Lock) doesn't handle background threads well that are CPU bound, especially if you have multiple processor cores on your system. Try adding a time.sleep(1) after each print in the background thread. And actually, I suspect that even a time.sleep(.001) would do it. DaveA -- http://mail.python.org/mailman/listinfo/python-list
cx_Oracle problem
It's time for another round of stump-the-geek. (thats what we call it in my office) If actual code is needed I can provide but lets start off small for this one... I've got a Python script that uses cx_Oracle to access an Oracle DB. running the script from command line runs perfect running the script as a cron job produces Unable to acquire Oracle environment handle in log. In both cases it is running as the same user, in the same environment. any ideas??? -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle problem
On Sep 15, 9:45 am, Squid ossto...@gmail.com wrote: It's time for another round of stump-the-geek. (thats what we call it in my office) If actual code is needed I can provide but lets start off small for this one... I've got a Python script that uses cx_Oracle to access an Oracle DB. running the script from command line runs perfect running the script as a cron job produces Unable to acquire Oracle environment handle in log. In both cases it is running as the same user, in the same environment. any ideas??? nevermind, I should have searched before posting... -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
def are_elements_present(sourceList, searchList):for e in searchList: if e not in sourceList: return False return True Using set: def are_elements_present(sourceList, searchList): return len(set(sourceList).intersection(set(searchList)) == len(searchList) On Tue, Sep 15, 2009 at 11:11 AM, Oltmans rolf.oltm...@gmail.com wrote: On Sep 15, 1:13 pm, Hendrik van Rooyen hend...@microcorp.co.za wrote: (i) a True if All the elements in match are in aList, else False? (ii) a True if any one or more of the members of match are in aList? (iii) Something else? That's a good question because I failed miserably in explaining my problem clearly. My original question isn't what I'm trying to solve. My apologies. I will try to explain here clearly. I'm using a 3rd- party library named Selenium (used for web-automation) and it has a method named is_element_present(ele) i.e. takes one element and return true if it finds this element in the page's HTML and returns false otherwise. Given this, I'm just trying to write a method are_elements_present(aList) whose job is to return True if and only if all elements in aList are present in page's HTML. So here is how are_elements_present() looks like def are_elements_present(eleLocators): elePresent=False if not eleLocators: return False for ele in eleLocators: if selenium.is_element_present(ele): elePresent=True else: elePresent=False print 'cannot find this element= '+str(ele) break return elePresent Now suppose page HTML contains with these IDs ( ID is an attribute like input id=inp1 /) = div1,div2,div3,div4,div5,inp1,inp2 and if I call the above method this way are_elements_present ([div1,div2,inp1,inp2]) then it should return True. If I call like are_elements_present([div1,div2,div10,inp1]) it should return False. So I hope I've explained myself. Now all I'm looking for is to write are_elements_presents() in a more Pythonic way. So please let me know if I can write are_elements_present() in more smart/shorter way. Thanks a lot for your help, in advance. Best regards, Oltmans -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
Sol Toure wrote: def are_elements_present(sourceList, searchList):for e in searchList: if e not in sourceList: return False return True Using set: def are_elements_present(sourceList, searchList): return len(set(sourceList).intersection(set(searchList)) == len(searchList) Unless I'm missing something, (and I didn't bother to read the original code so I may be) that's a subset test: set (searchList) = set (searchList) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
Tim Golden wrote: Unless I'm missing something, (and I didn't bother to read the original code so I may be) that's a subset test: set (searchList) = set (searchList) (cough) or, rather: set (searchList) = set (sourceList) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
Hendrik van Rooyen hend...@microcorp.co.za writes: 2) Is about as useful as stating that any Turing complete language and processor pair is capable of solving any computable problem, given enough time. So why are we not all programming in brainfuck? Except the amount of circumlocution one language might happen to use over another is quite limited. Or speaking the language of the people who wrote linear B? You mean Mycenaean Greek? There's still a few million people in Europe who speak a descendent of that very language. When a language lacks a word for a concept like window, then (I believe :-) ), it kind of puts a crimp in the style of thinking that a person will do, growing up with only that language. Window goes back to an Anglo-Saxon compound windeye. Even if a word does not already exist in a given language for whatever novel item, the language is capable of creating from its own resources. -- http://mail.python.org/mailman/listinfo/python-list
Re: str.split() with empty separator
Vlastimil Brom wrote: 2009/9/15 Ulrich Eckhardt eckha...@satorlaser.com: Hi! 'abc'.split('') gives me a ValueError: empty separator. However, ''.join(['a', 'b', 'c']) gives me 'abc'. Why this asymmetry? I was under the impression that the two would be complementary. Uli maybe it isn't quite obvious, what the behaviour in this case should be; re.split also works with empty delimiter (and returns the original string) re.split(, abcde) ['abcde'] If you need to split the string into the list of single characters like in your example, list() is the possible way: list(abcde) ['a', 'b', 'c', 'd', 'e'] I'd prefer it to split into characters. As for re.split, there are times when it would be nice to be able to split on a zero-width match such as r\b (word boundary). -- http://mail.python.org/mailman/listinfo/python-list
Re: weird str error
daved170 wrote: Hi everybody, I'm using SPE 0.8.3.c as my python editor. I'm using the str() function and i got a very odd error. I'm trying to do this: print str(HI) When i'm writing this line in the shell it prints: HI When it's in my code (it's the only line) i'm getting the following error: file c:\Python25\lib\local.py line 242, in str return format(%.12g,val) file c:\Python25\lib\local.py line 145, in format formatted = percent % value TypeError, float argument required any idea? It's worked for the entire day and unfortunately when i started my testing it raised this erroe/ local.py or locale.py? If the latter you are probably doing a star import: from locale import * This will replace the builtin str() with locale.str() which indeed requires a float: str(HI) 'HI' from locale import * str(HI) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib/python2.5/locale.py, line 244, in str return format(%.12g, val) File /usr/lib/python2.5/locale.py, line 147, in format formatted = percent % value TypeError: float argument required As a general rule use the standard import import locale and then invoke the module's functions with an explicit prefix: locale.setlocale(...) It's a bit more to type, but it will save you a lot of trouble. Peter PS: When str() is the builtin str(HI) converts a string into a string which does not make much sense. -- http://mail.python.org/mailman/listinfo/python-list
Re: weird str error
daved170 wrote: Hi everybody, I'm using SPE 0.8.3.c as my python editor. I'm using the str() function and i got a very odd error. I'm trying to do this: print str(HI) When i'm writing this line in the shell it prints: HI When it's in my code (it's the only line) i'm getting the following error: file c:\Python25\lib\local.py line 242, in str return format(%.12g,val) file c:\Python25\lib\local.py line 145, in format formatted = percent % value TypeError, float argument required any idea? It's worked for the entire day and unfortunately when i started my testing it raised this erroe/ I should start by asking why you're using using str() on a string literal? It would seem to just be a waste of time to convert a string to a string. Next, I'll have to insist that you copy/paste your error messages to the email; by retyping it you got the wrong file name. The file with that line in it is locale.py So now, you have a *locale* problem. Somebody other than I will have to help. And all the effort I put in before noticing your typo is wasted. You'd better describe your environment more thoroughly. Python version, OS, locale, and just how you're running this script. You said it's the only line so are you omitting the shebang line? Perhaps you're running on Windows? If so, you can copy from a cmd window using right-click-drag, at least if Quick-Edit is on. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: How to improve this code?
Oltmans wrote: On Sep 15, 1:13 pm, Hendrik van Rooyen hend...@microcorp.co.za wrote: (i) a True if All the elements in match are in aList, else False? (ii) a True if any one or more of the members of match are in aList? (iii) Something else? That's a good question because I failed miserably in explaining my problem clearly. My original question isn't what I'm trying to solve. My apologies. I will try to explain here clearly. I'm using a 3rd- party library named Selenium (used for web-automation) and it has a method named is_element_present(ele) i.e. takes one element and return true if it finds this element in the page's HTML and returns false otherwise. Given this, I'm just trying to write a method are_elements_present(aList) whose job is to return True if and only if all elements in aList are present in page's HTML. So here is how are_elements_present() looks like def are_elements_present(eleLocators): elePresent=False if not eleLocators: return False for ele in eleLocators: if selenium.is_element_present(ele): elePresent=True else: elePresent=False print 'cannot find this element= '+str(ele) break return elePresent Now suppose page HTML contains with these IDs ( ID is an attribute like input id=inp1 /) = div1,div2,div3,div4,div5,inp1,inp2 and if I call the above method this way are_elements_present ([div1,div2,inp1,inp2]) then it should return True. If I call like are_elements_present([div1,div2,div10,inp1]) it should return False. So I hope I've explained myself. Now all I'm looking for is to write are_elements_presents() in a more Pythonic way. So please let me know if I can write are_elements_present() in more smart/shorter way. Thanks a lot for your help, in advance. Best regards, Oltmans def are_all_elements_present(elems): if not elems: return False #because you want it backward return all( selenium.is_element_present(elem) for elem in elems ) The extra check is there because you're specifying that an empty list should return False, and all() returns True if no matches. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Sep 14, 5:05 am, Christopher Culver crcul...@christopherculver.com wrote: Hyuga hyugaricd...@gmail.com writes: I just wanted to add, in defense of the Chinese written language ... that I think it would make a fairly good candidate for use at least as a universal *written* language. Particularly simplified Chinese since, well, it's simpler. The advantages are that the grammar is relatively simple, and it can be used to illustrate concepts independently of the writer's spoken language. Musings about the universality of the Chinese writing system, once so common among Western thinkers, nevertheless do not square with reality. The Chinese writing system is in fact deeply linked to the Chinese language, even to the specific dialect being spoken. See Defrancis' _The Chinese Language: Fact and Fantasy_ (Honolulu: University of Hawaii Press, 1984): http://preview.tinyurl.com/rbyuuk Oh, certainly! I thought I said as much in my original post, but maybe I didn't stress that enough. I'm a lot stronger in Japanese than I am in Chinese, but even Japanese uses various Chinese characters in ways that have deep cultural ties that may not translate well (and in many cases that are completely different from those characters' implications in any Chinese language). I guess the reason I didn't stress that enough is that I'm in no way implying that they be used as is. I just think they could be taken as the basis for a standardized universal written language. One might argue that it would make more sense to come up with a new character set for that, but here we have one that so many people are already familiar with in some form or another. And the radical system makes them much easier to remember than many people realize. -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Sep 15, 4:12 am, Hendrik van Rooyen hend...@microcorp.co.za wrote: (snip) When a language lacks a word for a concept like window, then (I believe :-) ), it kind of puts a crimp in the style of thinking that a person will do, growing up with only that language. Are you telling us people using a language that does not have a word for window somehow cannot comprehend what a window is, are you mad man? Words are simply text attributes attached to objects. the text attribute doesn't change the object in any way. just think of is __repr__ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
On Mon, 14 Sep 2009 18:33:17 -0700 (PDT) André andre.robe...@gmail.com wrote: Here's an example using sets: def is_present(list_1, list_2): ...if set(list_1).intersection(set(list_2)): ... return True ...return False ... Not that it matters, but I'd probably write: def is_present(test, match): return bool(set(test) set(match)) /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Looking for a pure Python chart drawing module
I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Here's the list from the Python wiki at http://wiki.python.org/moin/NumericAndScientific/Plotting;. Almost all the options are really wrappers for some other package in C/C++. * Matplotlib -- wrapper for Antigrain, written in C/C++ * Veusz -- requires PyQt from http://www.riverbankcomputing.co.uk/pyqt, which is in C/C++ * Chaco -- requires binaries for Enthought Tool Suite * ScientificPython - uses mix of C, C++, and FORTRAN. * Gnuplot module -- wrapper for GNUPLOT * plot_wrap - wrapper for GNU plotutils * BLT - tcltk.com link goes to a domain squatter site. * PyQT - wrapper for Qwt C++ library * DISLIN - interface to C++ DISLIN system * Mayavi - interface to Mayavai2, standalone program * gdmodule GD - python wrapper for the GD library. * Gist - wrapper for gist graphics library * pgplot - Wrapper for pgplot. * Py-OpenDX - wrapper for IBM Data Explorer * VTK - wrapper for VTK in C++ * RPy - wrapper for R programming lnaguage * PyX - wrapper for Tex. * Biggles - wrapper for C++ module * Pychart - 100% Python, but last updated 21-Dec-2005. * PyNGL - uses PyNIO, which is in C * pygooglechart - Python interface to the Google Chart LookinAPI, only works in browser So, for pure Python, Pychart is it. I'll have to try it and see if it still works. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
2009/9/15 John Nagle na...@animats.com: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Here's the list from the Python wiki at http://wiki.python.org/moin/NumericAndScientific/Plotting;. Almost all the options are really wrappers for some other package in C/C++. ... * BLT - tcltk.com link goes to a domain squatter site. ... So, for pure Python, Pychart is it. I'll have to try it and see if it still works. John Nagle -- http://mail.python.org/mailman/listinfo/python-list As for BLT, there is Pmw.Blt, the original is written in Tcl. http://sourceforge.net/projects/blt/ http://pmw.sourceforge.net/doc/Blt.html http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc/ Maybe Tcl/Pmw has less problems on different platforms, but isn't pure python either; moreover I'm not sure what graph types are supported. vbr -- http://mail.python.org/mailman/listinfo/python-list
KeyBoard interrupt and Redirection operator
Hello Guys, I have a program which i use like this scraps.py arg1 arg2 filename. I am using the redirection operator to direct the output to the filename .The scenario here is that I want to print a message as long as the program is running and as generate an error message and exit as I use a keyboard interrupt.I am able to do this by using a try except clause but the issue is that everything is written to the file as i am using the redirection operator .Is there a way to write the running program message and the terminate program mesage to the console without writing it to the file. Thanks Aditya -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check something is in a list with rich-comparison objects?
En Tue, 15 Sep 2009 11:18:33 -0300, Jason jason.hee...@gmail.com escribió: Comparing a string to the enumerations in pysvn gives me an attribute error, because they've overloaded the rich compare methods: import pysvn string in [pysvn.wc_notify_action.status_completed, string] Traceback (most recent call last): File stdin, line 1, in module AttributeError: expecting wc_notify_action object for rich compare Is there a simple way around this? Looks like a bug in pysvn. Some class (whatever pysvn.wc_notify_action.status_completed is) is not well written. When compared against something unknown, it should return NotImplemented instead of raising AttributeError. py class BadBoy(object): ... foo = 1 ... # ... def __eq__(self, other): ... if not isinstance(other, BadBoy): ... raise TypeError, expecting BadBoy object for rich compare ... return self.foo==other.foo ... py hello in [BadBoy(), hello] Traceback (most recent call last): File stdin, line 1, in module File stdin, line 6, in __eq__ TypeError: expecting BadBoy object for rich compare py py class GoodBoy(object): ... foo = 1 ... # ... def __eq__(self, other): ... if not isinstance(other, GoodBoy): ... return NotImplemented ... return self.foo==other.foo ... py hello in [GoodBoy(), hello] True -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Trouble with MySQLdb
I'm receiving the following error: Traceback (most recent call last): File db.py, line 189, in module rows = db.get(SELECT * FROM survey) File db.py, line 55, in get self.sql(query) File db.py, line 47, in sql return self.cursor.execute(query) File build/bdist.linux-i686/egg/MySQLdb/cursors.py, line 168, in execute File build/bdist.linux-i686/egg/MySQLdb/cursors.py, line 73, in _warning_check SystemError: null argument to internal routine Here's the source for the db.py file: #!/usr/bin/env python import MySQLdb import MySQLdb.cursors # # MySQL Abstraction Layer # class MySQL: MySQL Abstraction Layer connection = None cursor = None db = None def __init__(self, host = 'localhost', usr = 'user', pwd = 'pass', db = 'main'): if host: self.connect(host, usr, pwd, db) def connect(self, host, usr, pwd, db): self.connection = MySQLdb.connect(host, usr, pwd, db, unix_socket='/opt/lampp/var/mysql/mysql.sock', cursorclass = MySQLdb.cursors.DictCursor) self.cursor = self.connection.cursor() self.db = db ## def sql(self, query): return self.cursor.execute(query) def next(self): return self.cursor.fetchone() ## def get(self, query, pkey = None): self.sql(query) if not pkey: ret = [] for i in self.cursor: ret.append(i) return ret def row(self, query): self.sql(query) for i in self.cursor: return i return None def field(self, query): ret = [] self.sql(query) for i in self.cursor: ret.append(i[0]) return ret def value(self, query): self.sql(query) for i in self.cursor: return i[0] return None ## def getFields(self, table): rows = self.get(DESCRIBE ` + table + `) return [str(i[0]) for i in rows] def getPrimaryKey(self, table): rows = self.get(DESCRIBE ` + table + `) return [str(i[0]) for i in rows if i[3] == 'PRI'] db = MySQL() rows = db.get(SELECT * FROM survey) for i in rows: print i raise SystemExit -- http://mail.python.org/mailman/listinfo/python-list
Re: Why use locals()
En Tue, 15 Sep 2009 11:18:35 -0300, Sion Arrowsmith s...@viridian.paintbox escribió: Sean DiZazzo half.ital...@gmail.com wrote: What I'm not clear about is under what circumstances locals() does not produce the same result as vars() . py help(vars) Help on built-in function vars in module __builtin__: vars(...) vars([object]) - dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyBoard interrupt and Redirection operator
En Tue, 15 Sep 2009 15:10:48 -0300, aditya shukla adityashukla1...@gmail.com escribió: I have a program which i use like this scraps.py arg1 arg2 filename. I am using the redirection operator to direct the output to the filename .The scenario here is that I want to print a message as long as the program is running and as generate an error message and exit as I use a keyboard interrupt.I am able to do this by using a try except clause but the issue is that everything is written to the file as i am using the redirection operator .Is there a way to write the running program message and the terminate program mesage to the console without writing it to the file. You're redirecting stdout, but stderr still goes to the console. print sys.stderr, This message appears on the console -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyBoard interrupt and Redirection operator
aditya shukla wrote: Hello Guys, I have a program which i use like this scraps.py arg1 arg2 filename. I am using the redirection operator to direct the output to the filename .The scenario here is that I want to print a message as long as the program is running and as generate an error message and exit as I use a keyboard interrupt.I am able to do this by using a try except clause but the issue is that everything is written to the file as i am using the redirection operator .Is there a way to write the running program message and the terminate program mesage to the console without writing it to the file. Thanks Aditya There are two output streams usually available to such a program. stdout: Where print's output goes, and is affected by the redirect operator. stderr: Output to this stream is not (normally) affected by the redirect operator. So print stuff or printsys.stdout, stuff will go to the redirected file and printsys.stderr, stuff will not be redirected. That answers you specific question, but note that various shells *do* provide (other) ways to redirect both stdout and stderr, but for a discussion on that, you will have to tell us what shell, and indeed what OS you are using. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
ActiveState Python 2.5 doesn't work via ssh?
Does anybody have any idea why Active State Python 2.5 works fine from a normal Cygwin shell window, but hangs when I try to start it when I'm ssh'd into the machine? -- Grant Edwards grante Yow! I don't know WHY I at said that ... I think it visi.comcame from the FILLINGS in my rear molars ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
On Sep 15, 8:25 pm, John Nagle na...@animats.com wrote: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Here's the list from the Python wiki at http://wiki.python.org/moin/NumericAndScientific/Plotting;. Almost all the options are really wrappers for some other package in C/C++. * Matplotlib -- wrapper for Antigrain, written in C/C++ * Veusz -- requires PyQt fromhttp://www.riverbankcomputing.co.uk/pyqt, which is in C/C++ * Chaco -- requires binaries for Enthought Tool Suite * ScientificPython - uses mix of C, C++, and FORTRAN. * Gnuplot module -- wrapper for GNUPLOT * plot_wrap - wrapper for GNU plotutils * BLT - tcltk.com link goes to a domain squatter site. * PyQT - wrapper for Qwt C++ library * DISLIN - interface to C++ DISLIN system * Mayavi - interface to Mayavai2, standalone program * gdmodule GD - python wrapper for the GD library. * Gist - wrapper for gist graphics library * pgplot - Wrapper for pgplot. * Py-OpenDX - wrapper for IBM Data Explorer * VTK - wrapper for VTK in C++ * RPy - wrapper for R programming lnaguage * PyX - wrapper for Tex. * Biggles - wrapper for C++ module * Pychart - 100% Python, but last updated 21-Dec-2005. * PyNGL - uses PyNIO, which is in C * pygooglechart - Python interface to the Google Chart LookinAPI, only works in browser So, for pure Python, Pychart is it. I'll have to try it and see if it still works. John Nagle My choice is PyQWT but few monts before I started pure python tkinter cartesian plot control: screenshot: http://www.iltchev.com/tkplot/tkplot.png source: http://www.iltchev.com/tkplot/tkplot.py.txt This class is in a very early stage, but I think it is good start. :) -- http://mail.python.org/mailman/listinfo/python-list
subprocess woes
I'm trying to write a function, sort_data, that takes as argument the path to a file, and sorts it in place, leaving the last sentinel line in its original position (i.e. at the end). Here's what I have (omitting most error-checking code): def sort_data(path, sentinel='.\n'): tmp_fd, tmp = tempfile.mkstemp() out = os.fdopen(tmp_fd, 'wb') cmd = ['/usr/local/bin/sort', '-t', '\t', '-k1,1', '-k2,2'] p = Popen(cmd, stdin=PIPE, stdout=out) in_ = file(path, 'r') while True: line = in_.next() if line != sentinel: p.stdin.write(line) else: break in_.close() p.stdin.close() retcode = p.wait() if retcode != 0: raise CalledProcessError(retcode, cmd) out.write(sentinel) out.close() shutil.move(tmp, path) This works OK, except that it does not catch the stderr from the called sort process. The problem is how to do this. I want to to avoid having to create a new file just to capture this stderr output. I would like instead to capture it to an in-memory buffer. Therefore I tried using a StringIO object as the stderr parameter to Popen, but this resulted in the error StringIO instance has no attribute 'fileno'. How can I capture stderr in the scenario depicted above? TIA! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyBoard interrupt and Redirection operator
aditya shukla wrote: Hello Guys, I have a program which i use like this scraps.py arg1 arg2 filename. I am using the redirection operator to direct the output to the filename .The scenario here is that I want to print a message as long as the program is running and as generate an error message and exit as I use a keyboard interrupt.I am able to do this by using a try except clause but the issue is that everything is written to the file as i am using the redirection operator .Is there a way to write the running program message and the terminate program mesage to the console without writing it to the file. Thanks Aditya That's what sys.stderr is for. It's redirected independently of stdout, and most people will leave it pointing to the console. You could for example use print sys.stderr , Starting program DaveA -- http://mail.python.org/mailman/listinfo/python-list
Upcoming Python/Django Classes
Holden Web is please to announce a public Introduction to Python class, near Washington DC, on October 13-15, presented by Steve Holden. This is followed, on Friday October 16, by a one-day Django Master Class presented by Jacob Kaplan-Moss. Further details are available from http://holdenweb.com/py/training/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Watch PyCon on video now! http://pycon.blip.tv/ -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess woes
On Sep 15, 2:26 pm, kj no.em...@please.post wrote: I'm trying to write a function, sort_data, that takes as argument the path to a file, and sorts it in place, leaving the last sentinel line in its original position (i.e. at the end). Here's what I have (omitting most error-checking code): def sort_data(path, sentinel='.\n'): tmp_fd, tmp = tempfile.mkstemp() out = os.fdopen(tmp_fd, 'wb') cmd = ['/usr/local/bin/sort', '-t', '\t', '-k1,1', '-k2,2'] p = Popen(cmd, stdin=PIPE, stdout=out) in_ = file(path, 'r') while True: line = in_.next() if line != sentinel: p.stdin.write(line) else: break in_.close() p.stdin.close() retcode = p.wait() if retcode != 0: raise CalledProcessError(retcode, cmd) out.write(sentinel) out.close() shutil.move(tmp, path) This works OK, except that it does not catch the stderr from the called sort process. The problem is how to do this. I want to to avoid having to create a new file just to capture this stderr output. I would like instead to capture it to an in-memory buffer. Therefore I tried using a StringIO object as the stderr parameter to Popen, but this resulted in the error StringIO instance has no attribute 'fileno'. How can I capture stderr in the scenario depicted above? TIA! kynn According to the docs for subprocess module (which you don't appear to be using even though that's what you used for your subject line), you can set stderr to stdout: http://docs.python.org/library/subprocess.html You can use cStringIO to create a file-like object in memory: http://docs.python.org/library/stringio.html --- Mike Driscoll Blog: http://blog.pythonlibrary.org -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess woes
Mike Driscoll wrote: You can use cStringIO to create a file-like object in memory: http://docs.python.org/library/stringio.html No, you can't with subprocess. The underlying operating system API requires a file descriptor of a real file. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
Christopher Culver wrote: Robin Becker ro...@reportlab.com writes: well allegedly, the medium is the message so we also need to take account of language in addition to the meaning of communications. I don't believe all languages are equivalent in the meanings that they can encode or convey. Our mathematics is heavily biassed towards continuous differential systems and as a result we end up with many physical theories that have smooth equilibrium descriptions, we may literally be unable to get at other theories of the physical world because our languages fall short. This is the old Sapir-Whorf hypothesis, which fell out of favour among linguists half a century ago already. 1) Language does not constrain human thought, and 2) any two human languages are both capable of expressing the same things, though one may already have a convenient lexeme for the topic at hand while the other uses circumlocution. This is the old Lenneberg-Chomsky Universalist hypothesis, which has fallen out of favor among cognitive scientists and others as various researchers have done actual experiments to determine how and when language does and does not influence perception and thought. See http://en.wikipedia.org/wiki/Linguistic_relativity -- http://mail.python.org/mailman/listinfo/python-list
Re: python decimals
Mark Dickinson wrote: On Sep 15, 2:27 am, Andrew Svetlov andrew.svet...@gmail.com wrote: Is there some kind of python binding for decNumber library? Standard decimal.Decimal is good enough, but very slow. My current project toughly coupled with 'currency' operations and we have performance problems related to decimal calculations. From my perspective decNumber is fast and has well wide domain to represent and process all required set of numbers - we don't need to work with 'almost infinite numbers' as python decimal can. I tried to google for desired binding - but found nothing. gmpy is interesting project, but supported types is not exactly what we need - rationals and big floats is not decimals in fixed point notation. My team discussed about making own python binding of decNumber - but before we start this task I like to ask python community: is there existing implementation? I don't want to invent the wheel again. Searching Python decNumber binding puts your query, from various sources, in several of the top 10 sports ;-) Did not seen anythng in the next 20 either. As far as I know, no such bindings exist. There have been various efforts to rewrite the decimal module in C, but (again as far as I know) none of those efforts have come to fruition yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
John Nagle wrote: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Here's the list from the Python wiki at http://wiki.python.org/moin/NumericAndScientific/Plotting;. Almost all the options are really wrappers for some other package in C/C++. * Matplotlib -- wrapper for Antigrain, written in C/C++ * Veusz -- requires PyQt from http://www.riverbankcomputing.co.uk/pyqt, which is in C/C++ * Chaco -- requires binaries for Enthought Tool Suite * ScientificPython - uses mix of C, C++, and FORTRAN. * Gnuplot module -- wrapper for GNUPLOT * plot_wrap - wrapper for GNU plotutils * BLT - tcltk.com link goes to a domain squatter site. * PyQT - wrapper for Qwt C++ library * DISLIN - interface to C++ DISLIN system * Mayavi - interface to Mayavai2, standalone program * gdmodule GD - python wrapper for the GD library. * Gist - wrapper for gist graphics library * pgplot - Wrapper for pgplot. * Py-OpenDX - wrapper for IBM Data Explorer * VTK - wrapper for VTK in C++ * RPy - wrapper for R programming lnaguage * PyX - wrapper for Tex. * Biggles - wrapper for C++ module * Pychart - 100% Python (NOT!), but last updated 21-Dec-2005. * PyNGL - uses PyNIO, which is in C * pygooglechart - Python interface to the Google Chart LookinAPI, only works in browser So, for pure Python, Pychart is it. I'll have to try it and see if it still works. http://home.gna.org/pychart/doc/introduction.html Tried PyChart. Set up for PNG file format. Got the error Exception: Ghostscript not found.This thing just creates PostScript, then pumps it through GhostScript (anybody remember that?) to get other formats. And does the documentation say that? Only in the FAQ section. Grrr. There doesn't seem to be any pure Python chart module at all. Just wrappers. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Application Packages
Say I have an application that lives in /usr/local/myapp it comes with some default plugins that live in /usr/local/myapp/plugins and I allow users to have plugins that would live in ~/myapp/plugins Is there a way to map ~/myapp to a user package so I could do from user.plugins import * or better yet map it to myapp.user? Dj Gilcrease OpenRPG Developer ~~http://www.openrpg.com -- http://mail.python.org/mailman/listinfo/python-list
unpacking vars from list of tuples
I'm inexperienced with some of the fancy list slicing syntaxes where python shines. If I have a list of tuples: k=[(a, bob, c), (p, joe, d), (x, mary, z)] and I want to pull the middle element out of each tuple to make a new list: myList = [bob, joe, mary] is there some compact way to do that? I can imagine the obvious one of myList = [] for a in k: myList.append(a[1]) But I'm guessing Python has something that will do that in one line... Any suggestion is appreciated... Ross. -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
On Tue, Sep 15, 2009 at 2:51 PM, Ross ros...@gmail.com wrote: I'm inexperienced with some of the fancy list slicing syntaxes where python shines. If I have a list of tuples: k=[(a, bob, c), (p, joe, d), (x, mary, z)] and I want to pull the middle element out of each tuple to make a new list: myList = [bob, joe, mary] is there some compact way to do that? I can imagine the obvious one of myList = [] for a in k: myList.append(a[1]) But I'm guessing Python has something that will do that in one line... Indeed: myList = [a[1] for a in k] Google for list comprehension python. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
On Tue, Sep 15, 2009 at 11:51 PM, Ross ros...@gmail.com wrote: I'm inexperienced with some of the fancy list slicing syntaxes where python shines. If I have a list of tuples: k=[(a, bob, c), (p, joe, d), (x, mary, z)] and I want to pull the middle element out of each tuple to make a new list: myList = [bob, joe, mary] is there some compact way to do that? I can imagine the obvious one of myList = [] for a in k: myList.append(a[1]) But I'm guessing Python has something that will do that in one line... Any suggestion is appreciated... You can use a list comprehension: myList = [a[1] for a in k] -- André Engels, andreeng...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
On 15 Sep., 23:51, Ross ros...@gmail.com wrote: If I have a list of tuples: k=[(a, bob, c), (p, joe, d), (x, mary, z)] and I want to pull the middle element out of each tuple to make a new list: myList = [bob, joe, mary] if a tuple is OK: zip(*k)[1] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why use locals()
On Sep 15, 11:41 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Tue, 15 Sep 2009 11:18:35 -0300, Sion Arrowsmith s...@viridian.paintbox escribió: Sean DiZazzo half.ital...@gmail.com wrote: What I'm not clear about is under what circumstances locals() does not produce the same result as vars() . py help(vars) Help on built-in function vars in module __builtin__: vars(...) vars([object]) - dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. Now *this* I would say is unPythonic: it's basically another obvious way to do something with no additional benefits. It'd be more useful (and less of a misnomer) if it would return an object really repesenting the variable visibility at the current scope, something like globals().copy().update(locals()), while taking care of edge cases like undeclared locals. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
If I have a list of tuples: k=[(a, bob, c), (p, joe, d), (x, mary, z)] and I want to pull the middle element out of each tuple to make a new list: myList = [bob, joe, mary] is there some compact way to do that? I can imagine the obvious one of myList = [] for a in k: myList.append(a[1]) But I'm guessing Python has something that will do that in one line... To add some readability to the other suggested solutions, I'd use tuple unpacking my_list = [name for status, name, code in k] Not knowing what [0] and [2] are, I randomly designated them as status and code, but you likely have your own meanings. If you don't, you can always just use the _ convention: my_list = [name for _, name, _ in k] # or my_list = [name for (_, name, _) in k] As an aside, my_list is preferred over myList in common Python practice. I don't know if there's a preferred convention for with vs without the parens in such a tuple-unpacking list comprehension. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
On Sep 15, 6:00 pm, Andre Engels andreeng...@gmail.com wrote: On Tue, Sep 15, 2009 at 11:51 PM, Ross ros...@gmail.com wrote: I'm inexperienced with some of the fancy list slicing syntaxes where python shines. If I have a list of tuples: k=[(a, bob, c), (p, joe, d), (x, mary, z)] and I want to pull the middle element out of each tuple to make a new list: myList = [bob, joe, mary] is there some compact way to do that? I can imagine the obvious one of myList = [] Thanks both Chris and André. That's quite obvious once it's pointed out for me. Thanks especially for the terminology that will make learning the related concepts a bit easier. Ross for a in k: myList.append(a[1]) But I'm guessing Python has something that will do that in one line... Any suggestion is appreciated... You can use a list comprehension: myList = [a[1] for a in k] -- André Engels, andreeng...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: VTK install
On Sep 16, 12:28 am, Francesco Bochicchio bieff...@gmail.com wrote: On Sep 15, 6:29 am, Gib gib.bo...@gmail.com wrote: As part of the MayaVi install, I need to install VTK. ... Since VTK appears to be installed, I'm guessing that either the path setting is wrong, or python is not using PYTHONPATH. How can I check that PYTHONPATH is being used? The paths in PYTHONPATH should show un sys.path python variable. So just do from a python prompt import sys; sys.path and check if the VTK directories are listed. You colòud aslo tentatively append your path to sys.path and then try again import vtk to see if it is a path problem or something else ... Ciao FB Interesting. sys.path includes this path: 'C:\\Documents and Settings\\mbog002.EC\\ C:\\Program Files\\VTK\\lib\ \site-packages' The first part is what I set the environment variable HOME to (as per Enthought instructions), the second part is the VTK path. Apparently the specified VTK path is being made relative to HOME - clearly inconsistent with the installation instructions. I solved the problem by editing PYTHONPATH in the registry. Definitely a trap for Windows users. -- http://mail.python.org/mailman/listinfo/python-list
Re: MayaVi install
On Sep 16, 3:45 am, Robert Kern robert.k...@gmail.com wrote: On 2009-09-14 23:07 PM, Gib wrote: I am trying to follow the instructions for installing MayaVi given on the Enthought site: http://code.enthought.com/projects/mayavi/docs/development/html/mayav... I'm following the step-by-step instructions to install with eggs under Windows. When I get to this point: easy_install Sphinx EnvisageCore EnvisagePlugins configobj Sphinx 0.6.3 is installed OK, but when envisagecore 3.1.1 is being installed, after doing a few steps it fails with the message: error: Setup script exited with error: Unable to find vcvarsall.bat A search showed that vcvarsall.bat is where you might expect to find it, in C:\Program Files\Microsoft Visual Studio 8\VC I'm not sure what to do now. Probably put that directory on your PATH. You will get better Mayavi support on the enthought-dev mailing list: https://mail.enthought.com/mailman/listinfo/enthought-dev -- 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 Thanks, will try the mailing list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
John Nagle wrote: http://home.gna.org/pychart/doc/introduction.html Tried PyChart. Set up for PNG file format. Got the error Exception: Ghostscript not found.This thing just creates PostScript, then pumps it through GhostScript (anybody remember that?) to get other formats. And does the documentation say that? Only in the FAQ section. Grrr. There doesn't seem to be any pure Python chart module at all. Just wrappers. John Nagle http://home.gna.org/pychart/doc/module-theme.html excerpt output_format This variable sets the encoding of the data produced by PyChart. The value of this variable must be one of the following strings. ps: eps: Encapsulated PostScript. This is the default. pdf: Adobe Page Description Format, or PDF. pdf-uncompressed: PDF without compression. This option should be used for a debugging purpose only. png: PNG graphics. You need to have ghostscript (gs) installed to use this option, because PyChart internally calls ghostscript to convert PostScript to PNG. /excerpt Looks like it will directly create pdf files, not sure if that will for you. Hope this helps. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Application Packages
Dj Gilcrease schrieb: Say I have an application that lives in /usr/local/myapp it comes with some default plugins that live in /usr/local/myapp/plugins and I allow users to have plugins that would live in ~/myapp/plugins Is there a way to map ~/myapp to a user package so I could do from user.plugins import * or better yet map it to myapp.user? No. You can execfile things in there, or you can add ~/myapp to the sys.path and then import things in there. And you can create aliases for those of course. Alternatively, namespace-packages and virtualenvs might be a solution, but not exactly straight-forward as well. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: LinkedIn Messages, 9/15/2009
On Tue, 15 Sep 2009 14:39:04 +0100, LinkedIn Communication communicat...@linkedin.com wrote: LinkedIn [snippety snip] Methinks the spam filter needs updating. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove empty strings from list
On Tue, 15 Sep 2009 02:55:13 +0100, Chris Rebert c...@rebertia.com wrote: On Mon, Sep 14, 2009 at 6:49 PM, Helvin helvin...@gmail.com wrote: Hi, Sorry I did not want to bother the group, but I really do not understand this seeming trivial problem. I am reading from a textfile, where each line has 2 values, with spaces before and between the values. I would like to read in these values, but of course, I don't want the whitespaces between them. I have looked at documentation, and how strings and lists work, but I cannot understand the behaviour of the following: line = f.readline() line = line.lstrip() # take away whitespace at the beginning of the readline. list = line.split(' ') # split the str line into a list # the list has empty strings in it, so now, remove these empty strings [snip] Block quoting from http://effbot.org/zone/python-list.htm Note that the for-in statement maintains an internal index, which is incremented for each loop iteration. This means that if you modify the list you’re looping over, the indexes will get out of sync, and you may end up skipping over items, or process the same item multiple times. Thus why your code is skipping over some elements and not removing them. Moral: Don't modify a list while iterating over it. Use the loop to create a separate, new list from the old one instead. In this case, your life would be improved by using l = line.split() instead of l = line.split(' ') and not getting the empty strings in the first place. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Fwd: Converting a script to Python 3 - having trouble.
Hi, I have the following code that works fine in Python 2.x, but I can't seem to get it to work in Python 3 with Popen. Can you please tell me how to get the same functionality out of Python 3? The gist of what I doing is in the setpassword function. I have tried numerous ways to get this to work, and just can't figure it out, and the docs on Popen are no help whatsoever on how to use the now open process. The examples completely skip over what to do with the process after you open it. The command I am running is a Perforce p4 passwd username command. It prompts for the password twice, and I have to enter it twice to reset a user's password. I would appreciate your help on getting this to work under Python 3. Rusty Working code in Python 2.x (Does not work in Python 3.) import os import string import sys import time ### def setpassword(user): password = passworD\n p4passwd = os.popen( p4 passwd %s % user, 'w' ) time.sleep(1) p4passwd.write( password ) time.sleep(1) p4passwd.write( password ) if p4passwd.close() == 1: print Password reset failed.\n sys.exit( 1 ) ### if __name__ == '__main__': if len (sys.argv) = 1: print Read the usage section at the top of the script for required parameters. sys.exit(1) user = sys.argv[1] setpassword(user) Attempted code in Python 3: (Doesn't work either) import os import string import sys import time import platform from subprocess import * if platform.system() == Windows: p4=p4.exe else: p4=/p4/1/bin/p4_1 ### def log(msglevel=DEBUG, message=): if msglevel == TEST: print(Running in test mode. Command run would have been:\n, message) elif msglevel == ERROR: print(message) sys.exit(1) elif (verbosity == 3): print(message) elif (verbosity == 2 and msglevel == INFO): print(message) ### def setpassword(user): password = passworD\n try: cmd = ' passwd {0}'.format(user) pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) stderr = pipe.stdin.write(password) time.sleep(1) stderr = pipe.stdin.write(password) if pipe.stdin.close != 0: log(ERROR, Password reset failed.\n{0}{1} generated the following error: {2}.format(p4, cmd, stderr)) except OSError as err: log(ERROR, Execution failed: {0}.format(err)) ### if __name__ == '__main__': if len (sys.argv) = 1: print (Read the usage section at the top of the script for required parameters.) sys.exit(1) user = sys.argv[1] setpassword(user) -- Rusty 775-636-7402 Office 775-851-1982 Fax -- Rusty 775-636-7402 Office 775-851-1982 Fax -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess woes
In d87065db-f51f-4afe-924c-f9e4a1eb0...@g23g2000vbr.googlegroups.com Mike Driscoll kyoso...@gmail.com writes: On Sep 15, 2:26=A0pm, kj no.em...@please.post wrote: I'm trying to write a function, sort_data, that takes as argument the path to a file, and sorts it in place, leaving the last sentinel line in its original position (i.e. at the end). =A0Here's what I have (omitting most error-checking code): def sort_data(path, sentinel=3D'.\n'): =A0 =A0 tmp_fd, tmp =3D tempfile.mkstemp() =A0 =A0 out =3D os.fdopen(tmp_fd, 'wb') =A0 =A0 cmd =3D ['/usr/local/bin/sort', '-t', '\t', '-k1,1', '-k2,2'] =A0 =A0 p =3D Popen(cmd, stdin=3DPIPE, stdout=3Dout) =A0 =A0 in_ =3D file(path, 'r') =A0 =A0 while True: =A0 =A0 =A0 =A0 line =3D in_.next() =A0 =A0 =A0 =A0 if line !=3D sentinel: =A0 =A0 =A0 =A0 =A0 =A0 p.stdin.write(line) =A0 =A0 =A0 =A0 else: =A0 =A0 =A0 =A0 =A0 =A0 break =A0 =A0 in_.close() =A0 =A0 p.stdin.close() =A0 =A0 retcode =3D p.wait() =A0 =A0 if retcode !=3D 0: =A0 =A0 =A0 =A0 raise CalledProcessError(retcode, cmd) =A0 =A0 out.write(sentinel) =A0 =A0 out.close() =A0 =A0 shutil.move(tmp, path) This works OK, except that it does not catch the stderr from the called sort process. =A0The problem is how to do this. =A0I want to to avoid having to create a new file just to capture this stderr output. =A0I would like instead to capture it to an in-memory buffer. Therefore I tried using a StringIO object as the stderr parameter to Popen, but this resulted in the error StringIO instance has no attribute 'fileno'. How can I capture stderr in the scenario depicted above? TIA! kynn According to the docs for subprocess module (which you don't appear to be using even though that's what you used for your subject line), Sorry, I should have been clearer. I *am* using subprocess; that's were Popen and PIPE come from. I omitted the import lines along with much else to keep the code concise. Maybe I overdid it. you can set stderr to stdout: This won't do: I'm already using stdout to collect the output of sort. You can use cStringIO to create a file-like object in memory: Nope. I get the same error I get when I try this idea using StringIO (i.e. no attribute 'fileno'). kj -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess woes
Upon re-reading my post I realize that I left out some important details. In h8oppp$qo...@reader1.panix.com kj no.em...@please.post writes: I'm trying to write a function, sort_data, that takes as argument the path to a file, and sorts it in place, leaving the last sentinel line in its original position (i.e. at the end). I neglected to mention that the files I intend to use this with are huge (of the order of 1GB); this is why I want to farm the work out to GNU's sort. Here's what I have (omitting most error-checking code): I should have included the following in the quoted code: from subprocess import Popen, PIPE, CalledProcessError def sort_data(path, sentinel='.\n'): tmp_fd, tmp = tempfile.mkstemp() out = os.fdopen(tmp_fd, 'wb') cmd = ['/usr/local/bin/sort', '-t', '\t', '-k1,1', '-k2,2'] p = Popen(cmd, stdin=PIPE, stdout=out) in_ = file(path, 'r') while True: line = in_.next() if line != sentinel: p.stdin.write(line) else: break in_.close() p.stdin.close() retcode = p.wait() if retcode != 0: raise CalledProcessError(retcode, cmd) out.write(sentinel) out.close() shutil.move(tmp, path) This works OK, except that it does not catch the stderr from the called sort process. The problem is how to do this. I want to to avoid having to create a new file just to capture this stderr output. I would like instead to capture it to an in-memory buffer. Therefore I tried using a StringIO object as the stderr parameter to Popen, but this resulted in the error StringIO instance has no attribute 'fileno'. How can I capture stderr in the scenario depicted above? TIA! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Converting a script to Python 3 - having trouble.
On Wed, 16 Sep 2009 00:01:17 +0100, Russell Jackson ru...@rcjacksonconsulting.com wrote: Hi, I have the following code that works fine in Python 2.x, but I can't seem to get it to work in Python 3 with Popen. Can you please tell me how to get the same functionality out of Python 3? The gist of what I doing is in the setpassword function. I have tried numerous ways to get this to work, and just can't figure it out, and the docs on Popen are no help whatsoever on how to use the now open process. The examples completely skip over what to do with the process after you open it. So how did it fail? ### def setpassword(user): password = passworD\n try: cmd = ' passwd {0}'.format(user) pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) stderr = pipe.stdin.write(password) time.sleep(1) stderr = pipe.stdin.write(password) if pipe.stdin.close != 0: Did you perhaps mean if pipe.stdin.close(): ? Does it help if you read stdout rather than sleeping for arbitrary periods? -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
multiproccess: What is the Dameon flag?
Hello, What is the Daemon flag and when/why would I want to use it? Thank you, AF -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess woes
On Tue, Sep 15, 2009 at 12:26 PM, kj no.em...@please.post wrote: I'm trying to write a function, sort_data, that takes as argument the path to a file, and sorts it in place, leaving the last sentinel line in its original position (i.e. at the end). Here's what I have (omitting most error-checking code): def sort_data(path, sentinel='.\n'): tmp_fd, tmp = tempfile.mkstemp() out = os.fdopen(tmp_fd, 'wb') cmd = ['/usr/local/bin/sort', '-t', '\t', '-k1,1', '-k2,2'] p = Popen(cmd, stdin=PIPE, stdout=out) in_ = file(path, 'r') while True: line = in_.next() if line != sentinel: p.stdin.write(line) else: break in_.close() p.stdin.close() retcode = p.wait() if retcode != 0: raise CalledProcessError(retcode, cmd) out.write(sentinel) out.close() shutil.move(tmp, path) This works OK, except that it does not catch the stderr from the called sort process. The problem is how to do this. I want to to avoid having to create a new file just to capture this stderr output. I would like instead to capture it to an in-memory buffer. Therefore I tried using a StringIO object as the stderr parameter to Popen, but this resulted in the error StringIO instance has no attribute 'fileno'. How can I capture stderr in the scenario depicted above? Use a pipe by setting stderr=PIPE?: p = Popen(cmd, stdin=PIPE, stdout=out, stderr=PIPE) #... error_output = p.stderr.read() Or am I missing something? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
John Nagle ha scritto: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Did you look at matplotlib? In their examples page there are some charts like the ones you asked for. I guess it could work for you, and it seems to work flawlessy in MS Windows as in gnu/linux. regards gerlos -- Solo lo scienziato è vero poeta: ci dà la luna, ci promette le stelle, ci farà un nuovo universo se sarà il caso. http://gerlos.altervista.org gerlos +- - - gnu/linux registred user #311588 -- http://mail.python.org/mailman/listinfo/python-list
Re: Retrieve url's of all jpegs at a web page URL
On Tue, Sep 15, 2009 at 7:28 AM, grimmus graham.col...@gmail.com wrote: Hi, I would like to achieve something like Facebook has when you post a link. It shows images located at the URL you entered so you can choose what one to display as a summary. I was thinking i could loop through the html of a page with a regex and store all the jpeg url's in an array. Then, i could open the images one by one and save them as thumbnails with something like below. 0. Install BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) 1: #untested from BeautifulSoup import BeautifulSoup import urllib page_url = http://the.url.here; with urllib.urlopen(page_url) as f: soup = BeautifulSoup(f.read()) for img_tag in soup.findAll(img): relative_url = img_tag.src img_url = make_absolute(relative_url, page_url) save_image_from_url(img_url) 2. Write make_absolute() and save_image_from_url() 3. Profit. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess woes
In mailman.1498.1253057406.2854.python-l...@python.org Chris Rebert c...@rebertia.com writes: On Tue, Sep 15, 2009 at 12:26 PM, kj no.em...@please.post wrote: I'm trying to write a function, sort_data, that takes as argument the path to a file, and sorts it in place, leaving the last sentinel line in its original position (i.e. at the end). =C2=A0Here's what I have (omitting most error-checking code): def sort_data(path, sentinel=3D'.\n'): =C2=A0 =C2=A0tmp_fd, tmp =3D tempfile.mkstemp() =C2=A0 =C2=A0out =3D os.fdopen(tmp_fd, 'wb') =C2=A0 =C2=A0cmd =3D ['/usr/local/bin/sort', '-t', '\t', '-k1,1', '-k2,2'= ] =C2=A0 =C2=A0p =3D Popen(cmd, stdin=3DPIPE, stdout=3Dout) =C2=A0 =C2=A0in_ =3D file(path, 'r') =C2=A0 =C2=A0while True: =C2=A0 =C2=A0 =C2=A0 =C2=A0line =3D in_.next() =C2=A0 =C2=A0 =C2=A0 =C2=A0if line !=3D sentinel: =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0p.stdin.write(line) =C2=A0 =C2=A0 =C2=A0 =C2=A0else: =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0break =C2=A0 =C2=A0in_.close() =C2=A0 =C2=A0p.stdin.close() =C2=A0 =C2=A0retcode =3D p.wait() =C2=A0 =C2=A0if retcode !=3D 0: =C2=A0 =C2=A0 =C2=A0 =C2=A0raise CalledProcessError(retcode, cmd) =C2=A0 =C2=A0out.write(sentinel) =C2=A0 =C2=A0out.close() =C2=A0 =C2=A0shutil.move(tmp, path) This works OK, except that it does not catch the stderr from the called sort process. =C2=A0The problem is how to do this. =C2=A0I want to= to avoid having to create a new file just to capture this stderr output. =C2=A0I would like instead to capture it to an in-memory buffer. Therefore I tried using a StringIO object as the stderr parameter to Popen, but this resulted in the error StringIO instance has no attribute 'fileno'. How can I capture stderr in the scenario depicted above? Use a pipe by setting stderr=3DPIPE?: p =3D Popen(cmd, stdin=3DPIPE, stdout=3Dout, stderr=3DPIPE) #... error_output =3D p.stderr.read() Thanks, that did the trick. Thanks! kj -- http://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Converting a script to Python 3 - having trouble.
I just get an errorlevel from the executable when I read stdout, but I can't tell what is going on because, of course, I can't tell what Popen is actually doing. I never see the prompt from the executable that I would expect to see when I read stdout. I originally had the function like this: def setpassword(user): password = passworD\n try: cmd = ' passwd {0}'.format(user) pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) stdout = pipe.stdout.readline() stderr = pipe.stdin.write(password) time.sleep(1) stdout = pipe.stdout.readline() stderr = pipe.stdin.write(password) if pipe.stdin.close != 0: log(ERROR, Password reset failed.\n{0}{1} generated the following error: {2}.format(p4, cmd, stderr)) except OSError as err: log(ERROR, Execution failed: {0}.format(err)) but, the script just hung when I did that. I think it was stuck on the readline, and never got anything from the process. I didn't think that the if statement was incorrect based on examples I saw in the docs, and the fact that it didn't complain about that part, but I'll try the close(): Thanks, Rusty On Tue, Sep 15, 2009 at 4:24 PM, Rhodri James rho...@wildebst.demon.co.ukwrote: On Wed, 16 Sep 2009 00:01:17 +0100, Russell Jackson ru...@rcjacksonconsulting.com wrote: Hi, I have the following code that works fine in Python 2.x, but I can't seem to get it to work in Python 3 with Popen. Can you please tell me how to get the same functionality out of Python 3? The gist of what I doing is in the setpassword function. I have tried numerous ways to get this to work, and just can't figure it out, and the docs on Popen are no help whatsoever on how to use the now open process. The examples completely skip over what to do with the process after you open it. So how did it fail? ### def setpassword(user): password = passworD\n try: cmd = ' passwd {0}'.format(user) pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) stderr = pipe.stdin.write(password) time.sleep(1) stderr = pipe.stdin.write(password) if pipe.stdin.close != 0: Did you perhaps mean if pipe.stdin.close(): ? Does it help if you read stdout rather than sleeping for arbitrary periods? -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list -- Rusty 775-636-7402 Office 775-851-1982 Fax -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a script to Python 3 - having trouble.
On Tue, Sep 15, 2009 at 4:01 PM, Russell Jackson ru...@rcjacksonconsulting.com wrote: snip Attempted code in Python 3: (Doesn't work either) snip cmd = ' passwd {0}'.format(user) pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) You're not specifying the command to Popen correctly (a very common problem). (Shameless plug: I *really* wish someone would look at my docs patch to explain this common problem -- http://bugs.python.org/issue6760) Corrected code: cmd = [p4, 'passwd', user] pipe = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) Though your code may have other problems too (I didn't check). Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
socket.MSG_WAITALL flag broken on Windows XP in Python 2.5.4?
I noticed the flag socket.MSG_WAITALL seems to have crept its way into Python 2.5 on Windows (it's in 2.5.4, but not in 2.5.1, not sure about intermediate releases). I do not think Windows supports it. It seems to cause some problems in some libraries (like Pyro) that use it if it's available in the socket module. Does anyone know more about this? Thanks, Wes -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a script to Python 3 - having trouble.
On Tue, Sep 15, 2009 at 5:07 PM, Chris Rebert c...@rebertia.com wrote: On Tue, Sep 15, 2009 at 4:01 PM, Russell Jackson ru...@rcjacksonconsulting.com wrote: snip Attempted code in Python 3: (Doesn't work either) snip cmd = ' passwd {0}'.format(user) pipe = Popen(p4 + cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) snip Scratch that, I neglected to notice the shell=True option. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: multiproccess: What is the Dameon flag?
Allen Fowler wrote: Hello, What is the Daemon flag and when/why would I want to use it? From the documentation: When a process exits, it attempts to terminate all of its daemonic child processes.. Sometimes you want the main process to wait for its worker processes to terminate before terminating itself so that you can be sure that everything (including resources they might use) has been tidied up. Other times there's nothing to tidy up so you just want the worker processes to terminate when the main process terminates. In the second case the worker process are known as daemon processes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Application Packages
when looking up namespace-packages I found pkgutil which lets me add a myapp.user package with the following in its __init__.py and nothing else import os, os.path from pkgutil import extend_path homedir = os.environ.get('HOME') or os.environ.get('USERPROFILE') __path__ = extend_path([os.path.abspath(homedir + os.sep + 'myapp')], __name__) now I can do from myapp.user.plugins import * and it works -- http://mail.python.org/mailman/listinfo/python-list