Announce: Linux Desktop Testing Project (LDTP) 1.7.0 released
Greetings all, We are proud to announce the release of LDTP 1.7.0. This release features number of important breakthroughs in LDTP as well as in the field of Test Automation. This release note covers a brief introduction on LDTP followed by the list of new features and major bug fixes which makes this new version of LDTP the best of the breed. Useful references have been included at the end of this article for those who wish to hack / use LDTP. About LDTP: Linux Desktop Testing Project is aimed at producing high quality test automation framework (C / Python) and cutting-edge tools that can be used to test Linux Desktop and improve it. It uses the Accessibility libraries to poke through the application's user interface. The framework also has tools to record test-cases based on user events in the interface of the application which is under testing. We strive to help in building a quality desktop. LDTP NEWS Mago project uses LDTP - http://mago.ubuntu.com GLOM uses LDTP - http://git.gnome.org/cgit/glom/tree/ldtp/ Whats new in this release: Get the window uptime, maximize, minimize, close, activate all or any given window name are some of the noticable new APIs in this release. Generate key event function now uses xmodmap to determine the current local keyboard and generates the respective key codes. Bug fixes: 590755 – Keycodes mismatch using generatekeyevent from python-ldtp 586655 – typo hasstate example with more one state separator '+' instead of ',' 587614 – Method to measure how long a window is showing up 588674 – It would be nice if doesrowexist would look for partial matches 587456 – checkrow action fails on tree table cell 583021 – If an application changes a context, it is no longer found by LDTP 588819 – 'import ldtp' freezes interpreter 589898 – local variable 'gobject' referenced before assignment 586291 – Subsequent tests fail when first one registers callback handlers 586657 – Imporve user experience getallstates match for defined state constants Special thanks to Arvind Patil apatil at vmware.com, Ara Pulido ara at ubuntu.com, Guofu Xu Guofu.Xu at access-company.com, nouar garcia-mardmabek nouar.garcia at sun.com, José Luis Segura Lucas josel.segura at gmx.es, Tim Sun tim.miao at sun.com, Anupa Kamath anupak at vmware.com, Paul Larson Paul.Larson at canonical.com, Murray Cumming murrayc at murrayc.com, Armin Burgmeier armin at arbur.net, New API addition: Window maximize, minimize, close, activate APIs using python wnck module Download source tarball - http://download.freedesktop.org/ldtp/1.x/1.7.x/ldtp-1.7.0.tar.gz Binary (openSUSE / Ubuntu / Fedora / Debian / RHEL / CentOS / Mandriva) - http://download.opensuse.org/repositories/home:/anagappan/ (Just scheduled in openSUSE build service, might take time to complete depending upon the server load) Eitan Isaacson eitan at ascender.com has done a massive work on LDTPv2, a complete rewrite of LDTP in python using pyatspi, available through http://cgit.freedesktop.org/ldtp/ldtp2/tree/ References: For detailed information on LDTP framework and latest updates visit http://ldtp.freedesktop.org For information on various APIs in LDTP including those added for this release can be got from http://ldtp.freedesktop.org/user-doc/index.html To subscribe to LDTP mailing lists, visit http://ldtp.freedesktop.org/wiki/Mailing_20list IRC Channel - #ldtp on irc.freenode.net Thanks Nagappan -- Linux Desktop (GUI Application) Testing Project - http://ldtp.freedesktop.org http://nagappanal.blogspot.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[ANNOUNCE] PyPoppler 0.10.1
I am pleased to announce version 0.10.1 of the Python bindings for Poppler. It is available at: http://launchpad.net/poppler-python/trunk/development/+download/pypoppler-0.10.1.tar.gz md5: 146ecb7e1049dd9b92478d61c148829e PyPoppler 0.10.1 (Aug 13 2009) == o Support for accessing Action fields (Daniel Jacobs) o Bug #397850 AnnotMapping/Annot implementation incomplete (Gian) o Update configure.ac to work with libtool 2.x (Gian) o Update aclocal.m4 (Gian) o Ignore some more files automatically created by libtool (Gian) Blurb: == Poppler[1] is a PDF rendering library based on the xpdf-3.0 code base. PyPoppler is a wrapper which exposes the poppler API to the python world. It is fairly complete, most of the API are covered. The documentation is actually missing, help wanted :) Like the Poppler library itself, PyPoppler is licensed under the GNU GPL. PyPoppler requires: = o Poppler = 0.10.0 o PyGObject = 2.10.1 o PyGTK = 2.10.0 o PyCairo = 1.8.4 Bug reports should go to https://launchpad.net/poppler-python [1] http://poppler.freedesktop.org/ cheers -- Gian Mario Tagliaretti GNOME Foundation member gia...@gnome.org -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: Need feedback on ORF-extracting code
gb345 wrote: Hi everyone. I'm relatively new to Python, and could use your feedback on the code below. First some nomenclature. A nucleotide is one of A, C, G, T, or U. (In practice, a sequence of such nucleotides never contains both T and U, but this fact is not important in what follows.) A codon is a sequence of 3 of these. A stop codon is any one of UAA, UAG, UGA, TAA, TAG, or TGA. Two codons are said to be in frame in a containing sequence of nucleotides if their positions differ by a multiple of 3. An open reading frame, or ORF, is defined as a maximal subsequence of nucleotides whose length is a multiple of 3, begins with either AUG or ATG, terminates right before a stop codon in the original sequence, and contains no stop codons that are in frame with the initial codon (AUG or ATG). The fact that ORFs have lengths that are multiples of 3 means that there are three possible registers for ORFs (depending the modulo 3 of their starting positions), and that ORFs in different registers can overlap. I'll refer to these registers as 0, 1, and 2, because they contain ORFs that are in frame with the codons at positions 0, 1, and 2 of the original sequence, respectively. In the code below, routine extract_orfs takes as input a string, assumed to be a sequence of nucleotides, and returns a tuple of tuples, describing ORFs. These ORFs can overlap. The helper routine _xo takes as input a string (a sequence of nucleotides), and an offset, and returns a tuple of tuples, again representing ORFs, but this time all in the same register, since they are all in frame with the position passed as the second argument to the function. I would appreciate your comments on this code. I feel that it is not as clear as it could be, but I don't know how to make it any clearer. (NOTE: I realize that, in all likelihood, publicly available Python code already exists for this. At the moment I'm more interested in improving my Python skills.) Many thanks in advance! Gabe # BEGINNING OF CODE import sys import re _start = r'A[TU]G' _stop = r'(?:[TU]A[AG]|[TU]GA)' _nonstop = r'(?:[CAG][TUCAG]{2}|[TU](?:[TUC][TUCAG]|[AG][TUC])|[TU]GG)' _codon = r'(?:[TUCAG]{3})' _orf_re = re.compile('(' + _codon + r'*?)(A[TU]G' + _nonstop + '*)(' + _stop + ')', flags=re.I) _lead_re = re.compile(r'[TUCAG]*?A[TU]G', flags=re.I) def _xo(seq, pos): Helper routine that finds all the non-overlapping in-frame orfs starting from a specific position in the input sequence. input: a string of letters in the set 'tucagTUCAG', and a starting position; output: a tuple of tuples; each internal tuple consists of a starting position, an orf, and the stop codon that terminates it. ret = [] while True: m = _orf_re.match(seq, pos) if not m: break orf = m.group(2) stop = m.group(3) assert len(orf) % 3 == 0 I am not currently familiar with the re module so I cannot comment in detail. The assert should be a claim that the re should *never* match anything other than a multiple of 3, so that it is a program bug if it ever do so. If this is not true, you should use an if statement. tjr ret.append((m.start() + len(m.group(1)), orf, stop)) pos = m.end() return ret def extract_orfs(seq): Extracts all (possibly overlapping) maximal open reading frames, defined as sequences beginning with AUG (or ATG), ending with an in-frame stop codon, and containing no in-frame stop codons in-between. input: a string of letters in the set 'tucagTUCAG'; output: a tuple of tuples; each internal tuple consists of a starting position, an orf, and the stop codon that terminates it. m = _lead_re.match(seq) if not m: return () pos = m.start() ret = [] for i in range(min(3, len(seq))): ret.extend(_xo(seq, pos + i)) ret.sort() return tuple(ret) # END OF CODE -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find out in which module an instance of a class is created?
En Mon, 10 Aug 2009 18:51:59 -0300, Johannes Janssen m...@johannes-janssen.de escribió: class A(object): def __init__(self, mod=None): if mod is None: self.mod = sys._getframe(1).f_globals['__name__'] else: self.mod = mod In warnings.warn() they used try around sys._getframe(1). As far as I understand what is done in warnings, there it is not sure what object caused the warning and therefore it is not sure whether you can or cannot use sys._getframe(1). Though in my case it should be quite clear. Can I be sure that my code will always work? The try/except around sys._getframe(1) is because that function is not mandatory/available on all Python implementations (that's the case for jython which doesn't provide it). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to page output in ?
En Wed, 12 Aug 2009 18:41:38 -0300, kj no.em...@please.post escribió: How does one tell the python interactive interpreter to run the next output to stdout through the default pager? Basically, I'm looking for Python's equivalent of Perl's debugger's | prefix, as in DB1 |print $long_output Try using pydoc.pager - read the source -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: best practice for documenting a project? pydoc?
Esmail wrote: shaileshkumar wrote: Hello, EPYDOC is very good for automatic generation of documentation from source code. You may also consider Sphinx http://sphinx.pocoo.org/ which is used for many projects including the official Python documentation, documentation of Zope (http://docs.zope.org/). See the full list of projects using Sphinx at http://sphinx.pocoo.org/examples.html - Shailesh Hi, Thanks for the links. Have you heard of something called HappyDoc? I just came across it by looking for info on epydoc. Thanks, Esmail I've never used Happydoc. I am using Epydoc, which is very efficient. Sphinx is very good as well, but its scope is much larger than documenting python code and will not provide the click and run effect of epydoc, for which you don't have to write any additional documentation. Epydoc supports restructured text, so you'll be able to switch to Sphinx later on without additional work. But if I remember well, your documentation is for personal use, so I guess you'll stick with epydoc. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: inspect.stack() performance
En Thu, 06 Aug 2009 09:00:45 -0300, Doron Tal doron.tal.l...@gmail.com escribió: I use inspect.stack() to extract some info, such as file name, function name and line number, for the sake of logging (home brew logger). I tested to see how much time it takes to execute the command: Python 2.4.3 (#1, Jan 21 2009, 01:11:33) [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2 Type help, copyright, credits or license for more information. import timeit t = timeit.Timer('inspect.stack()', 'import inspect') t.repeat(3,1000) [0.28500604629516602, 0.28315305709838867, 0.29169297218322754] About 280uSec per call. If I log 1000 times per seconds than I get to spend 28% of the process time on inspect.stack() Is there a better/quicker way of retrieving the same info? inspect loads the whole source code of every module in the stack (using linecache). If all you want is module name + line number, use this: f = sys._getframe() print f.f_globals['__name__'], f.f_lineno (see a recent post about warnings.warn too) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Monkeypatching an object to become callable
En Tue, 11 Aug 2009 20:21:16 -0300, Nikolaus Rath nikol...@rath.org escribió: Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid writes: 7stud a écrit : (snip) class Wrapper(object): def __init__(self, obj, func): self.obj = obj self.func = func def __call__(self, *args): return self.func(*args) def __getattr__(self, name): return object.__getattribute__(self.obj, name) This should be return getattr(self.obj, name) directly calling object.__getattribute__ might skip redefinition of __getattribute__ in self.obj.__class__ or it's mro. Works nicely, thanks. I came up with the following shorter version which modifies the object in-place: class Modifier(obj.__class__): def __call__(self): return fn() obj.__class__ = Modifier To me this seems a bit more elegant (less code, less underscores). Or are there some cases where the above would fail? I assume the above code is inside a function like make_callable(obj, fn) Then, a new class is created for every instance you make callable; you may want to cache all those classes (classes aren't cheap). Might fail: when obj is not a new-style class, or its __class__ isn't writable (e.g. builtin types). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib incredibly slow :-(
David Robinow wrote: On Wed, Aug 12, 2009 at 12:37 PM, Chris Withersch...@simplistix.co.uk wrote: David Stanek wrote: Also on the same box where you run this script can you test with curl or wget? It's a Windows box, so no :-( Why not? http://users.ugent.be/~bpuype/wget/ http://curl.haxx.se/download.html Fair point, but I don't see what this will achieve... I've already established that the file downloads in seconds with [something else], so I'd like to understand why python isn't doing the same and fix the problem... Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
loops for ffmpeg CLI in python
Hi, I am a begineer in Python. Actually I am encoding video files with different bitrates using ffmpeg CLI. I wanted to ask you that how can I make loops so that I can vary the bitrates in the CLI of ffmpeg?? I want to bulid a loop for the command below where i just want to vary the -vb parameter i.e. 10M. ffmpeg.exe -i sample.avi -y -f h264 -vb 10M -r 25 encoded_1000_0-05.h264 I have tried to make simple loops but it doest work:( Can anyone here help me out? Regards, Gillani _ Share your memories online with anyone you want. http://www.microsoft.com/middleeast/windows/windowslive/products/photos-share.aspx?tab=1-- http://mail.python.org/mailman/listinfo/python-list
Unsigned char array to an unsigned longlong array
Hello, I'm using Python 2.6.2. Is there a way to have an Array of unsigned longlong (C Type: unsigned longlong, Minimum size if bytes: 8) ? I found a page on the internet (http://mail.python.org/pipermail/patches/2005-April/017430.html), but I'm not quite sure if it is available. What I want to do is to store an array of bytes in an array of longlongs. To workaround this issue, I have tried to use the double array (TypeCode 'd'), since the size in bytes is the same (8 for instance). But it gives me strange result. Please look at the example: import array myByteArray = array.array('B', [1,2,3,4,5,6,7,8]) myByteArray = array('B', [1, 2, 3, 4, 5, 6, 7, 8]) myLongArray = array.array('L', myByteArray.tostring() ) myLongArray = array('L', [67305985L, 134678021L]) myDoubleArray = array.array('d', myByteArray.tostring() ) myDoubleArray = array('d', [5.447603722011605e-270]) If we convert the byte array to an hex form, we will get for the long array: [04030201, 08070605]. If we convert this hex array to decimal, we then get the Long Array: [67305985, 134678021]. Now, if we do the same exercise for the double array, the hex form will look like: [0807060504030201]. And the decimal value would be: [5.784376957523072e+17]. Where does the 5.447603722011605e-270 value comes from ? Thanks for your help, Francis -- http://mail.python.org/mailman/listinfo/python-list
Re: Character encoding the copyright symbol
Dave Angel da...@ieee.org writes: But I wanted to comment on the (c) remark. If you're in the US, that's the wrong abbreviation for copyright. The only recognized abbreviation is (copr). More reading on this: URL:http://en.wikipedia.org/wiki/Universal_Copyright_Convention URL:http://en.wikipedia.org/wiki/Copyright_symbol In brief: To be a legally-recognised copyright notice under US law, it must begin with “Copyright”, or one of the abbreviations “Copr.” or the exact symbol “©”. As you rightly point out, neither “(c)” nor “(C)” have any legal status as a copyright marker. The Berne Convention, by making copyright active on *every* creative work of expression, even in the total *absence* of a copyright notice, essentially undermines the force of this and makes it exceedingly difficult to divest a work of copyright. But that's a whole 'nother depressing mess. -- \ “A politician is an animal which can sit on a fence and yet | `\ keep both ears to the ground.” —Henry L. Mencken | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: hashability
On Wed, 12 Aug 2009 00:33:01 -0700, James Stroud wrote: Tell that to two different machines on two different days. Then bet the life of yourself and your nearest and dearest family on that fact and see whether you really want to take a hash value for granted. As far as I know, Python doesn't make any guarantees about hashes being repeatable on different machines, different versions, or even different runs of the interpreter. If a property of the python language fails the bet the lives of your nearest and dearest on a consistent result test, I call it ill defined and, subjectively speaking, I prefer exceptions to be thrown--And, by damned, I'll throw them myself if I have to. If it saves one life, it's worth it all. Depends on the life, and the cost. Would you pay a million dollars from your own pocket to save the life of a 119 year old with advanced lung cancer, a bad heart, and a raging infection of Ebola, from choking on a fish bone? What if the effort of saving that one life kills two lives? Opportunity costs are costs too. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Unrecognized escape sequences in string literals
On Aug 12, 7:19 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: You are making an unjustified assumption: \y is not an error. You are making in an unjustified assumption that I ever made such an assumption! My claim is and has always been NOT that \y is inately an error, but rather that treating unrecognized escape sequences as legal escape sequences is error PRONE. While I'm amused that you've made my own point for me, I'm less amused that you seem to be totally incapable of seeing past your parochial language assumptions, Where do you get the notion that my assumptions are in any sense parochial? They come from (1) a great deal of experience programming very reliable software, and (2) having learned at least two dozen different programming languages in my life. I disagree with nearly everything you say in this post. I think that a few points you make have some validity, but the vast majority are based on a superficial and confused understanding of language design principles. Whatever. I've taken two graduate level classes at MIT on programming languages design, and got an A in both classes, and designed my own programming language as a final project, and received an A+. But I guess I don't really know anything about the topic at all. But it's not the only reasonable design choice, and Bash has made a different choice, and Python has made yet a third reasonable choice, and Pascal made yet a fourth reasonable choice. And so did Perl and PHP, and whatever other programming language you happen to mention. In fact, all programming languages are equally good, so we might as well just freeze all language design as it is now. Clearly we can do no better. One party insisting that red is the only logical colour for a car, and that anybody who prefers white or black or blue is illogical, is unacceptable. If having all cars be red saved a lot of lives, or increased gas mileage significantly, then it might very well be the best color for a car. But of course, that is not the case. With programming languages, there is much more likely to be an actual fact of the matter on which sorts of language design decisions make programmers more productive on average, and which ones result in more reliable software. I will certainly admit that obtaining objective data on such things is very difficult, but it's a completely different thing that one's color preference for their car. |ouglas -- http://mail.python.org/mailman/listinfo/python-list
Re: resume upload wsgi script
gert schrieb: On Aug 10, 10:39 am, Diez B. Roggisch de...@nospam.web.de wrote: 250KB :) So why do you bother? Its just HTTP1.1 has everything for making ftp like file transfers possible. When I write it to a file then I am back at square one because I still need to load it completely to get it into a blob. Well, the blob is nothing but datat in the file-system. If you are *really* concerned about that, then don't use the db, but use the filesystem, appending to the file until it's finished - and storing a reference to it to the DB. We do that as well, because otherwise the db will become unmanagable anyway (dumping, backups). I also hate debugging sql that contains blob data. So if using files how do you clean the http post stuff? (b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)\r \n--'+b,file,DOTALL) using as litlle memory as possible ? I can not use PUT upload only because flash does not support PUT. PUT or POST has nothing todo with that. It's the question if you need formencoded data or not. If not, you can simply upload the data directly, no nead to cleanup anything. For decoding formencoded data, you will need to write your own parser if you insist on these very debatable memory-constraints of yours. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Nice copy in interactive terminal
casebash wrote: I've been wondering for a while if there exists an interactive terminal which has nice copy feature (ie. I can copy code without getting the in front of every line). It would help if we knew what platform you're interested in -- your User-Agent is G2/1.0, but I don't know what that is. :o) On Windows, PythonWin can copy from the interactive window without the prompts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsigned char array to an unsigned longlong array
En Tue, 11 Aug 2009 23:22:27 -0300, Jus ju...@hotmail.com escribió: Is there a way to have an Array of unsigned longlong (C Type: unsigned longlong, Minimum size if bytes: 8) ? What I want to do is to store an array of bytes in an array of longlongs. To workaround this issue, I have tried to use the double array (TypeCode 'd'), since the size in bytes is the same (8 for instance). Do you want to operate on it from inside Python, or manage it in some way? If not, use whatever format you like, even bytes. It's just a contiguous memory block with a known size. But it gives me strange result. Please look at the example: import array myByteArray = array.array('B', [1,2,3,4,5,6,7,8]) myLongArray = array.array('L', myByteArray.tostring() ) myLongArray = array('L', [67305985L, 134678021L]) myDoubleArray = array.array('d', myByteArray.tostring() ) myDoubleArray = array('d', [5.447603722011605e-270]) If we convert the byte array to an hex form, we will get for the long array: [04030201, 08070605]. What do you mean convert the byte array to an hex form? If we convert this hex array to decimal, we then get the Long Array: [67305985, 134678021]. Now, if we do the same exercise for the double array, the hex form will look like: [0807060504030201]. And the decimal value would be: [5.784376957523072e+17]. How did you got that? Where does the 5.447603722011605e-270 value comes from ? The struct module agrees: py s=struct.pack('q', 0x0807060504030201) py struct.unpack('d', s) (5.447603722011605e-270,) And looking at the hex representation: py (5.447603722011605e-270).hex() '0x1.7060504030201p-895' The 1. is implied, 7060504030201 are visible (52 bits), and the exponent is: py hex(-895+1023) '0x80' So that value seems OK to me, at least with IEEE 754 hardware... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
what is it, that I don't understand about python and lazy evaluation?
Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. Example: def test(txt, retval): ..print(txt) ..return retval .. test(1, True) or test(2, True) 1 True test(1, True) and test(2, True) 1 2 True Can anybody explain what happens with evens()? best regards Erik Bernoth PS: The code comes from a list post from 2006. You find it here: http://mail.python.org/pipermail/python-list/2006-November/585783.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Scraping Wikipedia with Python
On Tue, Aug 11, 2009 at 8:53 PM, David C Ullrichdullr...@sprynet.com wrote: Try reading a little there! Starting there I went to http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot where I found a section on existing bots, comments on how the scraping is not what you want, and even a Python section with a link to something labelled PyWikipediaBot... Some information on using the PyWikipediaBot for scraping from someone who used to program on the bot (and occasionally still does): To make the framework work, you need to add a file user-config.py with the following contents: family = 'wikipedia' mylang = 'en' If you want to use the bot to also edit pages on wikipedia, you will have to add: usernames['wikipedia']['en'] = the username of your bot If you work on another language of course you use that language's abbreviation instead of en. The heart of the framework is the file wikipedia.py, you need to import that one. It contains two important classes: Page and Site, which represent a wikipedia page and the site as a whole, respectively. It is best to put your code in a try like this: try: mysite = wikipedia.getSite() your code here finally: wikipedia.stopme() The stopme() functionality has to do with the bot's behaviour to avoid over-feeding the server with requests. It has a certain time (default is 10 seconds) between two requests, but if you have several bots running, it will lengthen this time. stopme() tells that the bot is not running any more, so other runs are not delayed by it. wikipedia.getSite() gets the site object for your default site (if the settings above are chosen it is the English language Wikipedia). Still with me? Good, because now we get into the real programming. The Page class has as its __init__: def __init__(self, site, title, insite=None, defaultNamespace=0): site is here the wiki on which the page exists (usually this will be mysite, which is why I defined it above), title the title of the page. The optional parameters are for special usage. The Page class has a number of methods, which you can find in the file, but some of the most important are: page.title() - the title of the page page.site() - the wiki the page is on page.get() - the (wiki) text of the page page.put(text) - saves the page with 'text' as its new content. An important optional parameter is 'comment', which specifies the summary that is given with the change page.exists() - a boolean, true if the page exists, false otherwise page.linkedPages() - a list of Page objects, being the pages the page links to However, instead of page.get() it is advisable to use: wikipedia.getall(site,pages) with 'site' being a Site object (e.g. mysite) and pages a list (or more generally, iterable) of Page objects. It will get all pages in the list using a single call to the wiki, thus speeding up your bot and at the same time reducing its load on the wiki. Once a page has been loaded (either through get or through getall), subsequent calls to page.get() will not reload it. Thus, the normal way of working is to create a list of pages one is interested in, use getall (in groups of 60 or so) to load them, then use get to work with them. Another useful file in the framework is pagegenerators. It provides a number of generators that yield Page objects. Some interesting ones (check the code for the exact parameters): AllpagesPageGenerator: generates all pages of the wiki, alphabetically from a specified begin ReferringPageGenerator: all pages linking to a given page CategorizedPageGenerator: all pages in a given directory LinkedPageGenerator: all pages linked to from a given page Other generators are used by 'wrapping them around' a given generator. The most important of these is the PreloadingGenerator, which ensures that the page are preloaded (using wikipedia.getall) in groups. A simple way to use the bot framework to scrape all pages of the English Wikipedia (warning: This takes a few days!) would be: import wikipedia import pagegenerators basicgen = pagegenerators.AllpagesPageGenerator(includeredirects = False) generator = pagegenerators.PreloadingGenerator(basicgen, 200) for page in generator: title = page.title() text = page.get() do whatever you want with title and text -- André Engels, andreeng...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess + python-daemon - bug/problem?
Ben Finney ben+pyt...@benfinney.id.au writes: My first thought was perhaps it's related to the fact that the process has no stdout? But setting ‘stdout’ and ‘stderr’ to the same file:: #! /usr/bin/python import daemon import subprocess fake_console = open(fake_console.txt, w+) daemon.DaemonContext(stdout=fake_console, stderr=fake_console).open() subprocess.Popen(['echo', '1']).wait() For newcomers to this thread: the ‘daemon’ module is provided by the URL:http://pypi.python.org/pypi/python-daemon ‘python-daemon’ distribution, of which I am the maintainer. still gives the same error:: 1 Traceback (most recent call last): File /home/bignose/Projects/python/python-daemon/bin/andy-clegg-test, line 8, in module subprocess.Popen(['echo', '1']).wait() File /usr/lib/python2.5/subprocess.py, line 1184, in wait pid, sts = self._waitpid_no_intr(self.pid, 0) File /usr/lib/python2.5/subprocess.py, line 1014, in _waitpid_no_intr return os.waitpid(pid, options) OSError: [Errno 10] No child processes I'm not familiar enough with the nuances of the ‘subprocess’ module to know what might be going wrong here. I'd like to know whether it might be a problem in the ‘python-daemon’ library. I am no closer to a solution on this one. I don't have enough experience or knowledge of the ‘subprocess’ module to know whether it's a bug in ‘subprocess’, a bug in ‘python-daemon’, or a hard-to-track interaction between the two. Any narrowing of the problem would be appreciated. -- \“I bought a dog the other day. I named him Stay. It's fun to | `\ call him. ‘Come here, Stay! Come here, Stay!’ He went insane. | _o__) Now he just ignores me and keeps typing.” —Steven Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: what is it, that I don't understand about python and lazy evaluation?
Erik Bernoth wrote: Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. Example: def test(txt, retval): ..print(txt) ..return retval .. test(1, True) or test(2, True) 1 True test(1, True) and test(2, True) 1 2 True Can anybody explain what happens with evens()? best regards Erik Bernoth PS: The code comes from a list post from 2006. You find it here: http://mail.python.org/pipermail/python-list/2006-November/585783.html In the list comprehension, it goes over all the items from the generator until the generator is done, and any item that is less than 15 becomes part of the list. The if n 15 does not control when the generator terminates, only which results from it are selected to be part of the list. You can pass the maximum desired value to make it terminate: def evens(max): i = 0 while i = max: yield i i += 2 L = list(evens(15)) L: [0, 2, 4, 6, 8, 10, 12, 14] L = [n for n in evens(15)] L: [0, 2, 4, 6, 8, 10, 12, 14] Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Re: what is it, that I don't understand about python and lazy evaluation?
2009/8/13 Erik Bernoth erik.bern...@googlemail.com: after 14 it is not nessesary to evaluate evens() any further. How does Python know this? I.e. how does it know that evens() will always yield things in ascending order? For example, I could write an iterator like this: def my_iter(): for i in [0,2,4,6,8,10,12,14,16,18,1,3,5]: yield i Now, imagine I do [i for i in my_iter() if i 15]. If you quit iterating after `i' becomes 16, you'll miss the valid numbers 1, 3, 5 at the end of the list! -- -David -- http://mail.python.org/mailman/listinfo/python-list
Re: what is it, that I don't understand about python and lazy evaluation?
Erik Bernoth wrote: Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. It's equivalent to: L = [] for n in evens(): if n 15 L.append(n) -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: fileinput
naaman wrote: On Aug 12, 1:35 pm, Dave Angel da...@ieee.org wrote: naaman wrote: I'm writing my first Python script and I want to use fileinput to open a file in r+ mode. Tried fileinput.input(sys.argv[1:],r+) but that didn't work. ANy ideas? Need to find and overwrite a line in a file several times. I can do it using open and seek() etc. but was wondering if I can use fileinput. thanks; I haven't used it, but check out the 'inplace' keyword parameter. DaveA I've only Python for a week so I'm not sure what inplace does You should read the docs for it ( http://www.python.org/doc/2.6.2/library/fileinput.html ), but it's not very clear to me either So I dug up an example on the web: (ref: http://effbot.org/librarybook/fileinput.htm ) import fileinput, sys for line in fileinput.input(inplace=1): # /convert Windows/DOS text files to Unix files/ if line[-2:] == \r\n: line = line[:-2] + \n sys.stdout.write(line) The inplace argument tells it to create a new file with the same name as the original (doing all the necessary nonsense with using a scratch file, and renaming/deleting) for each file processed. Stdout is pointed to that new version of the file. Notice that you have to explicitly write everything you want to wind up in the file -- if a given line is to remain unchanged, you just write line directly. If you're new to Python, I do not recommend trying to do open/seek to update a text file in place, especially if you're in DOS. There are lots of traps. the inplace method of fileinput avoids these by implicitly creating temp files and handling the details for you, which probably works great if you're dealing with text, in order. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: csv.DictWriter.write_header()
On Aug 13, 1:15 pm, Alan G Isaac alan.is...@gmail.com wrote: On Aug 13, 6:45 am, Alan G Isaac alan.is...@gmail.com wrote: Given a csv.DictWriter instance `dw` I think it would be nice to be able to say dw.write_header() instead of dw.writer.writerow(dw.fieldnames) Good idea? On 8/12/2009 10:24 PM John Machin apparently wrote: Yes, it's a brilliant idea. All you have to do is insert the following lines in your code after importing csv: csv.DictWriter.write_header = ( lambda dw: dw.writer.writerow(dw.fieldnames) ) I do not understand the reason for your silly, sarcastic response. Duck typing: ask a silly question, get a silly answer. I already showed you how to achieve the result, What result? You said (in effect) I think it would be nice to be able to write A instead of B. You didn't show any way of setting things up so that one could write A instead of B. I showed one way. Other possibilities are a 2-line patch to the users own csv.py, and submitting a patch to the dev team. The second is kludgy, and there could be a wait until e.g. 2.7 before the third happens. So back to the first way; everybody should have a utility module that they import to do little fixes like that ... here is a slightly more robust version: import csv try: csv.DictWriter.write_header except AttributeError: csv.DictWriter.write_header = ( lambda dw: dw.writer.writerow(dw.fieldnames) ) so obviously I am not just asking for my own personal gain. ??? I take it you do not realize that many users do not see a simple way to get this often needed functionality. No, I don't. How did you come to that realisation? AFAICT they don't ask in this forum or on StackOverflow. (For example, see the gymnatics suggested by Shai Vaingast in his otherwise excellent and useful book.) I can imagine that one might (without reading the source) make do with the published APIs: dw = csv.DictWriter(open(...), my_field_names dw.writerow(dict((fn, fn) for fn in my_field_names)) And indeed, there is no reason to expect them to. Indeed not, as for somebody who otherwise sees utility in the DictWriter class not having a writer_headers method is a glaring deficiency. Note that there is a difference between expecting C to do X and expecting C to be able to do X. I really hope you don't mean that people should not be encouraged to be able to write a trivial class like csv.DictWriter and add trivial functionality themselves ... or to be able to just write the required functionality inline: wtr = csv.writer(open(...), ...) wtr.writerow(my_field_names) for adict in source_of_dicts(): wtr.writerow(adict[fn] for fn in my_field_names) or even: for obj in source_of_objects(): wtr.writerow(getattr(obj, fn) for fn in my_field_names) So my question was, would this improve the class from a usability perspective? Of course. Do you have a useful response? See above. Also, the csv module appears to be in two minds about underscores in attribute names (field_size_limit, skipinitialspace, writerow, writerows) -- it may cause less confusion if it were called writeheader (consistent with writerow). -- http://mail.python.org/mailman/listinfo/python-list
Re: best practice for documenting a project? pydoc?
Hello Jean-Michel, Thanks for your post. Based on it, and the ones received so far I will give epydoc a closer look. I don't need something superfancy (at least at the moment), just something that helps me document my code more in an organized way and helps me sift through the various classes/methods more easily once I come back to the project after some lengthy interruptions. Best, Esmail Jean-Michel Pichavant wrote: I've never used Happydoc. I am using Epydoc, which is very efficient. Sphinx is very good as well, but its scope is much larger than documenting python code and will not provide the click and run effect of epydoc, for which you don't have to write any additional documentation. Epydoc supports restructured text, so you'll be able to switch to Sphinx later on without additional work. But if I remember well, your documentation is for personal use, so I guess you'll stick with epydoc. -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib incredibly slow :-(
On Thu, Aug 13, 2009 at 3:20 AM, Chris Withersch...@simplistix.co.uk wrote: David Robinow wrote: On Wed, Aug 12, 2009 at 12:37 PM, Chris Withersch...@simplistix.co.uk wrote: David Stanek wrote: Also on the same box where you run this script can you test with curl or wget? It's a Windows box, so no :-( Why not? http://users.ugent.be/~bpuype/wget/ http://curl.haxx.se/download.html Fair point, but I don't see what this will achieve... I've already established that the file downloads in seconds with [something else], so I'd like to understand why python isn't doing the same and fix the problem... My post was simply to correct the implication that curl and wget can not be used on Windows. It's up to you whether you want to use one or the other. I'm not the OP, and this is not my area of expertise, but ... You've got two data points. You've jumped to the conclusion that there's something wrong with Python or your code. You're probably right. However, if you try wget, for example, and it's as slow as your code, you cqn look elsewhere. If, on the other hand, wget is as fast as IE, you'll have more proof that your code is the problem. Then, since wget is open source you can look at the source code and see what wget is doing right that you (or httplib) is doing wrong. -- http://mail.python.org/mailman/listinfo/python-list
PIL and Python
Hello ! I want use python to change the note from .jpeg files . What is the functions on PIL how make this ? Thank you ! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
On 2009-08-13, Dave Angel da...@ieee.org wrote: I'm assuming you want to call it every time_interval seconds, on average, with a little jitter allowed on each call, but keeping correct long term. In other words, if one call is a little late, you want the next one to still happen as close to on-time as possible. The general outline is something like (untested): times_called = 0 #number of times function has been called start_time = now while True: elapsed = now - start_time int_elapsed = int(elapsed/time_interval) for times_called in range(times_called, int_elapsed): call_the_function() sleep(time_interval/10) #this might give us 10% jitter, which is usually fine I don't understand the reasoning behind the above loop -- specifically the sleeping of smaller intervals than needed. Why not something like this: interval = 5.0 # interval in seconds next = time.time() while True: now = time.time() if now next: time.sleep(now-next) print call_the_function() next += interval That will be accurate over the long term with minimal jitter. -- http://mail.python.org/mailman/listinfo/python-list
Re: what is it, that I don't understand about python and lazy evaluation?
Erik Bernoth erik.bernoth at googlemail.com writes: Isn't it strange, that this code runs (in a lazy language) for eternity? Python is a not a lazy language. `and` and `or` are particular, they are language constructs (*), not operators, that's why they can decide whether or not to evaluate their second term. It's a feature, but this feature is not general to Python. (*) by this I mean they have similar status as, for example, `if` and `else` -- http://mail.python.org/mailman/listinfo/python-list
Re: Networked Broadcast Messaging
On Aug 11, 9:18 pm, David Bolen db3l@gmail.com wrote: If you want better guarantees, you might look into a distributed message bus like Spread (http://www.spread.org/) or perhaps a messaging protocol like XMPP (http://xmpp.org/) through its PubSub extension. Both have Python interfaces, though I have no personal experience with either. But perhaps that will also give you some terms or starting points for searching for other options. This is also very helpful. In particular Spread, looks very attractive. Thanks for the tip, Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Social problems of Python doc [was Re: Python docs disappointing]
On 08/12/2009 12:27 PM, Raymond Hettinger wrote: On Aug 12, 3:32 am, Paul Boddiep...@boddie.org.uk wrote: Maybe the problem is that although everyone welcomes contributions and changes (or says that they do), the mechanisms remain largely beyond criticism. FWIW, I support the idea the regular docs incorporating links to freely editable wiki pages. That will at least make it easier for people to make changes or add notes. That being said, I would like to add a few thoughts about the current process. ISTM that important corrections (when the docs are clearly in error) tend to get made right away. What is more interesting are the doc requests that get rejected and why: [...snip interesting categorization of bad doc enhancement suggestions...] In short, most doc requests that get rejected are requests that didn't actually improve the documentation. I do support links from the regular docs to an external wiki but the main docs should continue to go through the regular process using the tracker. What is the purpose of such a wiki? 1. To provide hopefully useful adjunct information for each doc page? 2. To provide a source of input for improving the next version of the docs? In general I have a low opinion of wikis. Nearly all the ones I've seen are trash heaps of out-dated and wrong information, atrocious writing, and comments that look like the middle of some arcane usenet thread. They lack organization making it very difficult to find the needles of good information in the haystack of junk. The only one that seems to work is Wikipedia and it works because it has a very heavy-weight process controlling contributions. (And even then, my biggest complaint with Wikipedia is the poor writing quality in a lot of articles.) I'm not trying to be negative, only pointing out that to serve either of the goals I asked about above, a wiki will probably require a considerable management effort that should be faced up front. To simply set up a wiki and wait for it to self-organize (as I here read once) is a pipe-dream. How will it be managed? Anything written stays? If not what standards are used to remove junk entries? Wrong entries? Questionable entries? Who will do this? Will they act based on their own judgment or some documented formal standards? What happens to comments when a new doc version is released? What happens when entries become obsolete? What happens when comments are disputed? If the goal is (2) what kind of wiki contributions are being solicited (I don't understand what this sentence means? a complete rewrite of a section?) and how is that communicated? Who will take a long string of wiki comments constituting a discussion and condense them into something that can be submitted as a doc patch? (This I suspect is where the work is, where someone with good writing skills is needed.) Will this process be sufficient to raise the quality of the docs significantly, or are other steps also needed such as an attitude shift in what the core committers consider acceptable? If the goal is (1) above, it could potentially have a deleterious effect on the docs in that it will be easier to respond to requests to expand some description with, there's no need since that is covered in (or belongs in) the wiki comments. All the above not withstanding, I too think a wiki is worth trying. But without doing a lot more than just setting up a wiki, I sadly believe even a python.org supported wiki is doomed to failure. -- http://mail.python.org/mailman/listinfo/python-list
IFL 2009: Final Call for Papers and Participation
Call for Papers and ParticipationIFL 2009Seton Hall UniversitySouth Orange, NJ, USAhttp://tltc.shu.edu/blogs/projects/IFL2009/Register at: http://tltc.shu.edu/blogs/projects/IFL2009/registration.html* NEW *Registration and talk submission deadline fast approaching: August 23, 2009***The 21st International Symposium on Implementation and Application of Functional Languages, IFL 2009, will be held for the first time in the USA. The hosting institution is Seton Hall University in South Orange, NJ, USA and the symposium dates are September 23-25, 2009. It is our goal to make IFL a regular event held in the USA and in Europe. The goal of the IFL symposia is to bring together researchers actively engaged in the implementation and application of functional and function-based programming languages. IFL 2009 will be a venue for researchers to present and discuss new ideas and concepts, work in progress, and publication-ripe results related to the implementation and application of functional languages and function-based programming.Following the IFL tradition, IFL 2009 will use a post-symposium review process to produce a formal proceedings which will be published by Springer in the Lecture Notes in Computer Science series. All participants in IFL 2009 are invited to submit either a draft paper or an extended abstract describing work to be presented at the symposium. These submissions will be screened by the program committee chair to make sure they are within the scope of IFL and will appear in the draft proceedings distributed at the symposium. Submissions appearing in the draft proceedings are not peer-reviewed publications. After the symposium, authors will be given the opportunity to incorporate the feedback from discussions at the symposium and will be invited to submit a revised full arcticle for the formal review process. These revised submissions will be reviewed by the program committee using prevailing academic standards to select the best articles that will appear in the formal proceedings.Invited Speaker: Benjamin C. Pierce University of Pennsylvania Talk Title: How To Build Your Own Bidirectional Programming LanguageTOPICSIFL welcomes submissions describing practical and theoretical work as well as submissions describing applications and tools. If you are not sure if your work is appropriate for IFL 2009, please contact the PC chair at ifl2...@shu.edu. Topics of interest include, but are not limited to:language concepts type checking contractscompilation techniques staged compilationruntime function specializationruntime code generation partial evaluation (abstract) interpretation generic programming techniques automatic program generation array processing concurrent/parallel programming concurrent/parallel program execution functional programming and embedded systems functional programming and web applications functional programming and security novel memory management techniques runtime profiling and performance measurements debugging and tracing virtual/abstract machine architectures validation and verification of functional programs tools and programming techniques FP in EducationPAPER SUBMISSIONSProspective authors are encouraged to submit papers or extended abstracts to be published in the draft proceedings and to present them at the symposium. All contributions must be written in English, conform to the Springer-Verlag LNCS series format and not exceed 16 pages. The draft proceedings will appear as a technical report of the Department of Mathematics and Computer Science of Seton Hall University.IMPORTANT DATESRegistration deadline August 23, 2009Presentation submission deadline August 23, 2009IFL 2009 Symposium September 23-25, 2009Submission for review process deadline November 1, 2009Notification Accept/Reject December 22, 2009Camera ready version February 1, 2010PROGRAM COMMITTEEPeter Achten University of Nijmegen, The NetherlandsJost Berthold Philipps-Universität Marburg, GermanyAndrew Butterfield University of Dublin, IrelandRobby Findler Northwestern University, USAKathleen Fisher ATT Research, USACormac Flanagan University of California at Santa Cruz, USAMatthew Flatt University of Utah, USAMatthew Fluet Toyota Technological Institute at Chicago, USADaniel Friedman Indiana University, USAAndy Gill University of Kansas, USAClemens Grelck University of Amsterdam/Hertfordshire, The Netherlands/UKJurriaan Hage Utrecht University, The NetherlandsRalf Hinze Oxford University, UKPaul Hudak Yale University, USAJohn Hughes Chalmers University of Technology, SwedenPatricia Johann University of Strathclyde, UKYukiyoshi Kameyama University of Tsukuba, JapanMarco T. Morazán (Chair) Seton Hall University, USARex Page University of Oklahoma, USAFernando Rubio Universidad Complutense de Madrid, SpainSven-Bodo Scholz University of Hertfordshire, UKManuel Serrano INRIA Sophia-Antipolis, FranceChung-chieh Shan Rutgers University, USADavid Walker Princeton University, USAViktória Zsók
Re: Social problems of Python doc [was Re: Python docs disappointing]
On 13 Aug, 16:05, ru...@yahoo.com wrote: All the above not withstanding, I too think a wiki is worth trying. But without doing a lot more than just setting up a wiki, I sadly believe even a python.org supported wiki is doomed to failure. The ones on python.org seem to function reasonably well. I accept that they could be more aggressively edited, but this isn't done because there's a compromise between letting people contribute and keeping things moderately coherent, with the former being favoured. For other purposes, it would be quite acceptable to favour editorial control. I won't argue that providing infrastructure solves a problem - that's precisely the kind of thing I was criticising when I noted that some people will readily criticise the choice of tools to do a job instead of focusing on the job that has to be done - and you need people who are reasonably competent editors, but Wiki solutions remove a lot of technical barriers. I'm not arguing for the flavour of Wiki which implies unfettered, anonymous access from everyone on the Internet, either: the kind of Wiki that detractors portray all Wiki solutions as being in order to further their super-special it has to fit like a glove or it's totally unusable software agenda. It's quite possible to have people with somewhat more privileges than others in order to keep the peace, and they don't all need to have an entrenched editorial interest: on the current python.org Wiki sites, most of the administrators don't have an active interest in most of the content, but they are able to exercise control when it's clear that some contributors aren't particularly interested in actually improving the content. As well as having an active community effort around the existing python.org Wiki sites, there are also people who are interested in improving these offerings. What worries me is that despite such activity and such interest, many people will continue to lament the lack of vitality (or whatever other metric) of the general python.org offering, whilst retaining a blind spot for the obvious contribution that the Wikis can make to such improvement efforts. I encourage people to use wiki.python.org a lot more, should they be looking to improve the wealth of information provided by the community. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: what is it, that I don't understand about python and lazy evaluation?
Antoine Pitrou wrote: Erik Bernoth erik.bernoth at googlemail.com writes: Isn't it strange, that this code runs (in a lazy language) for eternity? Python is a not a lazy language. `and` and `or` are particular, they are language constructs (*), not operators, that's why they can decide whether or not to evaluate their second term. It's a feature, but this feature is not general to Python. (*) by this I mean they have similar status as, for example, `if` and `else` Agreed. In fact, I don't know of any aspect of Python which I'd call lazy, although the word appears in the docs in a few places. I've seen, but not used, languages which had lazy evaluations. Simplest example would be an infinite precision math package, where the actual precision is not actually used till something external to the program got visibility to the value. So the constant PI might really be a generator, which would generate enough precision for whatever the value was being used for. If you did a free-form print of PI, the console would never terminate (in principle), but in practice, it'd get slower and slower printing out the digits till the machine ran out of memory, or the user lost patience. Python, on the other hand has at least three short-circuit operations, in which parts of the expression are defined not to be evaluated at all, if other parts meet certain conditions. These are the 'and' and 'or' keywords mentioned above, the chained comparison construct, and the conditional expression, added recently. In each of these, the semantics of the language require that those parts not be evaluated. val = (42 x function()) val = 19 if i12 else function() val = x or function() In each example, the function() may or may not be actually called, depending on the other values of the expression. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Menu in Frame
Hello! I am trying to figure out if it is possible to place a Tkinter menu within a frame. This would be instead of having the menu-bar at the top of the window. Thanks, Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: loops for ffmpeg CLI in python
On Wed, 2009-08-12 at 11:29 +0200, fakhar Gillani wrote: Hi, I am a begineer in Python. Actually I am encoding video files with different bitrates using ffmpeg CLI. I wanted to ask you that how can I make loops so that I can vary the bitrates in the CLI of ffmpeg?? I want to bulid a loop for the command below where i just want to vary the -vb parameter i.e. 10M. ffmpeg.exe -i sample.avi -y -f h264 -vb 10M -r 25 encoded_1000_0-05.h264 I have tried to make simple loops but it doest work:( Can anyone here help me out? It might help if you specify what you tried and why it didn't work (for you). -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Python configuration question when python scripts are executed using Appweb as web server.
Gabriel Genellina wrote: [snip] Here are couple of links that discusses setting PYTHONPATH environment variable. http://docs.python.org/using/windows.html Ouch, that document should be reworked and updated! I don't understand this comment, given that the PEP370 Implementation section 2nd paragraph quite specifically refers to the use of PYTHONPATH, I quote. The user site directory is added before the system site directories but after Python's search paths and PYTHONPATH. This setup allows the user to install a different version of a package than the system administrator but it prevents the user from accidently overwriting a stdlib module. Stdlib modules can still be overwritten with PYTHONPATH. What am I missing? http://www.daimi.au.dk/~chili/PBI/pythonpath.html [snip] -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Delegate attribute requests to object
I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? Here's some example code: class Decorator: def __init__(): self.decorated = Decorated() def newFunction(): # Do something pass def interceptRequests(request): return self.decorated.request() class Decorated: def __init__(): self.variable = 10 def oldFunction(): # Do something pass I want to be able to do something like this: objectA = Decorator() objectB = Decorated() assert objectA.oldFunction() == objectB.oldFunction() # No error Is it possible (without inheritance)? -- Evan Kroske http://welcome2obscurity.blogspot.com/ The code, comments, and challenges of a novice software developer desperate for attention. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: How to launch a function at regular time intervals ?
Grant Edwards wrote: On 2009-08-13, Dave Angel da...@ieee.org wrote: I'm assuming you want to call it every time_interval seconds, on average, with a little jitter allowed on each call, but keeping correct long term. In other words, if one call is a little late, you want the next one to still happen as close to on-time as possible. The general outline is something like (untested): times_called = 0 #number of times function has been called start_time = now while True: elapsed = now - start_time int_elapsed = int(elapsed/time_interval) for times_called in range(times_called, int_elapsed): call_the_function() sleep(time_interval/10) #this might give us 10% jitter, which is usually fine I don't understand the reasoning behind the above loop -- specifically the sleeping of smaller intervals than needed. Why not something like this: interval = 5.0 # interval in seconds next = time.time() while True: now = time.time() if now next: time.sleep(now-next) print call_the_function() next += interval That will be accurate over the long term with minimal jitter. Two reasons I didn't take an approach like that one. 1) I frequently need to do something else while waiting, so I tend to do multiple smaller sleeps. As long as each sleep is at least 100ms, the overhead cost is pretty small. 2) If (occasionally) the function takes longer than the specified interval time, my approach does catch-up calls so the average remains the same. My loop was only a rough outline, and if neither of these considerations applies, yours is much nicer. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Interface to Exchange Calendar via web services
I have a python app that needs to look up a person's Exchage Calendar entries to see if they are currently available. Does anyone have any code examples for communicating with EWS (Exchange Web Services)? I've found some code in Java and CSharp to do this, but none in python so far. Thanks! -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list
Re: Delegate attribute requests to object
Perhaps I'm misunderstanding something, but I don't think that's really typical decorator behavior? Typically decorators, as I understand them, take an instance argument -- so you wouldn't be saying def __init__(self): self.decorated = Decorated() you'd be saying def __init__(self, decorated): self.decorated = decorated As for the attribute access, I believe you can override __getattr__ to do what you want: class Decorator: [snip] def __getattr__(self, request): return self.decorated.__getattr__(request) The same thing should work for methods, although you may want to pass arguments through as well. Is there a reason why, for this use, just making Decorator a subclass of Decorated (and only overriding the methods you need to be different) wouldn't work? On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske e.kro...@gmail.com wrote: I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? Here's some example code: class Decorator: def __init__(): self.decorated = Decorated() def newFunction(): # Do something pass def interceptRequests(request): return self.decorated.request() class Decorated: def __init__(): self.variable = 10 def oldFunction(): # Do something pass I want to be able to do something like this: objectA = Decorator() objectB = Decorated() assert objectA.oldFunction() == objectB.oldFunction() # No error Is it possible (without inheritance)? -- Evan Kroske http://welcome2obscurity.blogspot.com/ The code, comments, and challenges of a novice software developer desperate for attention. -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
Thanks all for your answers. As suggested by Dave and Frank, I am indeed looking for the main program to continue running in the background (I have several functions I want to launch, each at a predefined time interval). I like Frank's solution, on the paper it seems it would do what I am looking for, but I cannot succeed in having it working. I guess I've been stuck with this problem for too long and can't succeed in using my brain accurately anymore... ;-) I defined the class as defined by Frank, and I then inserted the following code in a While True loop, without any other code (the idea is just to test Frank's solution before really using it in my program): func = MyFunction() func.start() func.stop() func.join() However I'm not getting the expected behavior. It's not taking into account the 30 sec wait, the function is called again and again without any time interval... Any idea ? Again, thanks a lot. -- http://mail.python.org/mailman/listinfo/python-list
Re: Social problems of Python doc [was Re: Python docs disappointing]
On Wed, 12 Aug 2009 20:23:27 -0700, rurpy wrote: That's no different from *any* major refactoring. The exact same problem exists for code as well as documentation. It's a solved problem for code, and it's a solved problem for documentation. Huh? I don't buy this at all. Code refactoring doesn't change the semantics of the program at all -- it simplifies the code that implements behavior without changing behavior. How does this apply to revising documentation? My apologies, I mis-wrote. Of course refactoring is inappropriate in this context. What I meant was a major redesign where the API may change. Except of course that documentation changes don't need to be concerned with backwards compatibility, except possibly to avoid breaking old links. [...] Yes it would. Most patches are ignored, because the dev team are overworked, and if they don't see the need for a patch, they won't approve it. I'm confused. If they weren't overworked, then they would approve patches they didn't see a need for? No. If they're overworked, they're less likely to spend time investigating patches which aren't immediately obvious that they're needed. And additionally, if the patch doesn't appear to be useful, it's unlikely to be approved. Why would it be? Or are you saying because they are overworked they fail to approve patches that should be approved? Invariably there will be good patches missed because they haven't been noticed. I am not sure how either supports the argument that the tracker is the best method of improving the docs. These are not arguments in favour of the tracker, these are realistic issues that any project of non-trivial size have to deal with. Virtually every project (not just software projects either) have to deal with the fact that there will be more things to do than resources to do them with. [...] No, submitting a tracker issue is a necessary but not sufficient step. Without a tracker issue, you're very unlikely to have people agree to replace the existing docs with your docs, although a PEP would probably do it. (A PEP is significantly more effort than raising a tracker issue.) Has there ever been a PEP for a doc change? Are you making a serious suggestion? I don't know if there ever has been, but as far as I know, there are two ways to get changes approved to Python: informal approval by somebody with check-in privileges, or formal approval on the basis of a PEP. If you can't get the first, then the second is an option, albeit unlikely. As long as every the docs sux complaint is met here with the standard responses that I've mentioned, But they aren't met with such a so-called standard response. I just looked through the first 70 or so messages in this thread and in this case I have agree with you, most of the responses were not what I called standard responses. There was one guy, a Steven D'Aprano early on that trotted out the, it's free software, fix it if you don't like it line, And I stand by it. If you're not helping to solve the problem, then what exactly are you doing? Even if you can't provide a patch, provide a bug report. What specifically is wrong with the docs? Be specific. Give examples. Explain why it is wrong. State your assumptions, e.g. what audience do you represent? If you do these things, you're helping. If you're just complaining, then you're not. We know that there are problems. We've said repeatedly that corrections and patches are welcome. We've repeatedly told you how to communicate your answer to the question of what should be done. None of this is good enough for you. I don't know what else you expect. You have been told repeatedly why your insistence that the tracker must be the only channel, is wrong. I don't understand why you can't understand that. (Generally only those in authority, bosses, parents, police, and the like, tell others what a situation is and have a right to demand that the subject accept it without question. I think you could find a more respectful and less authoritarian way of phrasing what you said above since you are not in a position of authority over me.) You're not my real dad!!! In the words of Jesse The Body Venture, I'm just telling it like it is. The tracker is the only practical way of getting doc changes accepted, for those without check-in privileges or the ear of someone with them. Me telling you this is no more an expression of authority than me telling you that the USA has 50 states. Of course I could be wrong. My understanding of the facts might be wrong, or I may not be in full possession of all the relevant facts. If so, I welcome correction. So please tell me, what other practical ways are there for an unprivileged person to get the official Python docs modified? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
On 2009-08-13, Dave Angel da...@ieee.org wrote: Grant Edwards wrote: On 2009-08-13, Dave Angel da...@ieee.org wrote: The general outline is something like (untested): times_called = 0 #number of times function has been called start_time = now while True: elapsed = now - start_time int_elapsed = int(elapsed/time_interval) for times_called in range(times_called, int_elapsed): call_the_function() sleep(time_interval/10) #this might give us 10% jitter, which is usually fine I don't understand the reasoning behind the above loop -- specifically the sleeping of smaller intervals than needed. Why not something like this: interval = 5.0 # interval in seconds next = time.time() while True: now = time.time() if now next: time.sleep(now-next) print call_the_function() next += interval That will be accurate over the long term with minimal jitter. Two reasons I didn't take an approach like that one. 1) I frequently need to do something else while waiting, so I tend to do multiple smaller sleeps. As long as each sleep is at least 100ms, the overhead cost is pretty small. I guess I always use a separate thread for cases like that. 2) If (occasionally) the function takes longer than the specified interval time, my approach does catch-up calls so the average remains the same. I'm still confused -- doesn't mine do that as well? -- Grant Edwards grante Yow! Are you the at self-frying president? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Database query execution times in Python?
In article mailman.4437.1249670565.8015.python-l...@python.org, pwnedd keith.hugh...@gmail.com wrote: I've been writing some code using libraries based on the Python Database API 2.0 (MySQLdb pg), and so far things are working really well. There is one thing that I have not been able to figure out how to do, however: Retrieve the time is took a given query to execute. Look up EXPLAIN -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ ...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons. --Aahz -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib incredibly slow :-(
In article mailman.4613.1250033136.8015.python-l...@python.org, Chris Withers ch...@simplistix.co.uk wrote: Aahz wrote: In article mailman.4598.1250022343.8015.python-l...@python.org, Chris Withers ch...@simplistix.co.uk wrote: Does anyone know of an alternative library for creating http requests and getting their responses that's faster but hopefully has a similar interface? PyCurl This seems to be a wrapper around libcurl. Does it work on Windows? Yes. If so, where can I find some decent examples? (the ones listed on the pycurl website are not what I'd call decent :-S) Sorry, I mostly have been working on our Mac port, so I'm not sure what's needed to make this work on Windows. Did you try downloading the PyCurl binary? Maybe it statically links libcurl on Windows. What do you need to know for a decent example? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ ...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons. --Aahz -- http://mail.python.org/mailman/listinfo/python-list
Re: Social problems of Python doc [was Re: Python docs disappointing]
A basic question in this thread is: Who will host the doc-wiki/whatever and how will it be linked to? If not hosted at python.org it can still be linked to from their docs, if allowed, possibly with 3rd level domain and re-direct. I host a number of commercial servers but I don't expect Guido to bless them with said links. If hosted at python.org it will require resources from the existing admins. If elsewhere then trusted admins and organization. If not linked to from python.org then it may well expire from lack of interest, as other seemingly nice attempts did. Ray Schumacher -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
David wrote: Thanks all for your answers. As suggested by Dave and Frank, I am indeed looking for the main program to continue running in the background (I have several functions I want to launch, each at a predefined time interval). I like Frank's solution, on the paper it seems it would do what I am looking for, but I cannot succeed in having it working. I guess I've been stuck with this problem for too long and can't succeed in using my brain accurately anymore... ;-) I defined the class as defined by Frank, and I then inserted the following code in a While True loop, without any other code (the idea is just to test Frank's solution before really using it in my program): func = MyFunction() func.start() func.stop() func.join() However I'm not getting the expected behavior. It's not taking into account the 30 sec wait, the function is called again and again without any time interval... Any idea ? Again, thanks a lot. What exactly do you mean by I then inserted the following code in a While True loop? Do you mean you put all four lines in it? If yes, then you're repeatedly starting then stopping the function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Delegate attribute requests to object
More information at http://www.python.org/doc/2.5.2/ref/attribute-access.html if you need it :-) On Thu, 13 Aug 2009 10:13:47 -0700, Evan Kroske e.kro...@gmail.com wrote: I don't want to inherit from the classes I'm decorating because they have a common superclass. I can make a generic decorator that I can use on all its sibling classes. I'll try your getattr method to see if it works. On Thu, Aug 13, 2009 at 12:07 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: Perhaps I'm misunderstanding something, but I don't think that's really typical decorator behavior? Typically decorators, as I understand them, take an instance argument -- so you wouldn't be saying def __init__(self): self.decorated = Decorated() you'd be saying def __init__(self, decorated): self.decorated = decorated As for the attribute access, I believe you can override __getattr__ to do what you want: class Decorator: [snip] def __getattr__(self, request): return self.decorated.__getattr__(request) The same thing should work for methods, although you may want to pass arguments through as well. Is there a reason why, for this use, just making Decorator a subclass of Decorated (and only overriding the methods you need to be different) wouldn't work? On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske e.kro...@gmail.com wrote: I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? Here's some example code: class Decorator: def __init__(): self.decorated = Decorated() def newFunction(): # Do something pass def interceptRequests(request): return self.decorated.request() class Decorated: def __init__(): self.variable = 10 def oldFunction(): # Do something pass I want to be able to do something like this: objectA = Decorator() objectB = Decorated() assert objectA.oldFunction() == objectB.oldFunction() # No error Is it possible (without inheritance)? -- Evan Kroske http://welcome2obscurity.blogspot.com/ The code, comments, and challenges of a novice software developer desperate for attention. -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: what is it, that I don't understand about python and lazy evaluation?
Erik Bernoth wrote: Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. Example: def test(txt, retval): ..print(txt) ..return retval .. test(1, True) or test(2, True) 1 True test(1, True) and test(2, True) 1 2 True Can anybody explain what happens with evens()? best regards Erik Bernoth PS: The code comes from a list post from 2006. You find it here: http://mail.python.org/pipermail/python-list/2006-November/585783.html As MRAB pointed out, the issue is not with evens, it's with the list comprehension. The list comprehension doesn't know when to stop, only which numbers to include. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Help newbie with how to call a source command
Hi all, I'm landing here because I need some help that I couldn't get through it. Question 1. I want to call a source command from python script. It will source some variables enviroment for further commands. I tried the following which did not work os.sys('source '+source_text) call(['source',source_text], shell=True) commands.getoutput('source '+source_text) Anyone have experiences with this? Because I'm very new to this world so a details reply is really appreciated!!! thank you very much Question 2. I call a shell command from python, this time it runs a script which runs some ruby scripts. And the error returns: ruby: command not found Thank you again -- http://mail.python.org/mailman/listinfo/python-list
Re: what is it, that I don't understand about python and lazy evaluation?
Ethan Furman wrote: Erik Bernoth wrote: Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. Example: def test(txt, retval): ..print(txt) ..return retval .. test(1, True) or test(2, True) 1 True test(1, True) and test(2, True) 1 2 True Can anybody explain what happens with evens()? best regards Erik Bernoth PS: The code comes from a list post from 2006. You find it here: http://mail.python.org/pipermail/python-list/2006-November/585783.html As MRAB pointed out, the issue is not with evens, it's with the list comprehension. The list comprehension doesn't know when to stop, only which numbers to include. ~Ethan~ Actually, I am mistaken (gasp! shock! ;). A list comprehension will run until the iterator(s) it's based on end, and even() runs forever. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to address a global variable in a function
In article 82c2f2e7-ed3e-482b-9318-d5539a2a9...@y10g2000prg.googlegroups.com, n179911 n179...@gmail.com wrote: I have a global variable // line 8 tx = 0 and then I have this function (start in line 12): def handleTranslate(result): print line txStr, tyStr = result.group(1), result.group(2) print txStr, tyStr tx += int(txStr) ty += int(tyStr) return BTW, you probably want to learn why global names are a bad idea, I don't have time to explain that here (or point you at references). Going through some of the online tutorials should address this. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ ...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons. --Aahz -- http://mail.python.org/mailman/listinfo/python-list
Re: Delegate attribute requests to object
Oops, my apologies, it's the __getattribute__ method you want to call on self.decorated (because __getattr__ won't be there unless you define it specifically) So it should go: def __getattr__(self, request): return self.decorated.__getattribute__(request) On Thu, 13 Aug 2009 11:00:28 -0700, Evan Kroske e.kro...@gmail.com wrote: Unfortunately, __getattr__ didn't work. When I try to use your code class Decorator: [snip] def __getattr__(self, request): return self.decorated.__getattr__(request) I get this error: AttributeError: 'Decorated' object has no attribute '__getattr__' Is that a private method, or am I simply using it wrong? Thanks for the help. On Thu, Aug 13, 2009 at 1:18 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: More information at http://www.python.org/doc/2.5.2/ref/attribute-access.html if you need it :-) On Thu, 13 Aug 2009 10:13:47 -0700, Evan Kroske e.kro...@gmail.com wrote: I don't want to inherit from the classes I'm decorating because they have a common superclass. I can make a generic decorator that I can use on all its sibling classes. I'll try your getattr method to see if it works. On Thu, Aug 13, 2009 at 12:07 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: Perhaps I'm misunderstanding something, but I don't think that's really typical decorator behavior? Typically decorators, as I understand them, take an instance argument -- so you wouldn't be saying def __init__(self): self.decorated = Decorated() you'd be saying def __init__(self, decorated): self.decorated = decorated As for the attribute access, I believe you can override __getattr__ to do what you want: class Decorator: [snip] def __getattr__(self, request): return self.decorated.__getattr__(request) The same thing should work for methods, although you may want to pass arguments through as well. Is there a reason why, for this use, just making Decorator a subclass of Decorated (and only overriding the methods you need to be different) wouldn't work? On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske e.kro...@gmail.com wrote: I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? Here's some example code: class Decorator: def __init__(): self.decorated = Decorated() def newFunction(): # Do something pass def interceptRequests(request): return self.decorated.request() class Decorated: def __init__(): self.variable = 10 def oldFunction(): # Do something pass I want to be able to do something like this: objectA = Decorator() objectB = Decorated() assert objectA.oldFunction() == objectB.oldFunction() # No error Is it possible (without inheritance)? -- Evan Kroske http://welcome2obscurity.blogspot.com/ The code, comments, and challenges of a novice software developer desperate for attention. -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
i Don't get why it makes trouble
j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string I want to format the string. the list has five elements and the string has five placeholder but it wont format the string -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pyjamas 0.6pre3 released
much as we'd very much like to declare a 0.6 stable release, really really soon and move forward, the ChangeLog just keeps growing (133 and counting) with the bugfixes, testing and contributions since 0.5p1. pyjamas is a port of GWT to python, and includes a python-to-javascript compiler and a widget UI toolkit that is similar to pyqt4, pygtk2 etc. applications can either be run as javascript (in a web browser) or on the desktop (using pyjamas-desktop) as python. conceptually therefore, pyjamas is similar to adobe AIR - except that it's python, not ActionScript, and it's entirely free software. hurrah! key changes: * the python-to-javascript has been significantly reworked, and now includes a --strict option which adds python strict features at the expense of speed. to disable these, and obtain speed instead, use -O * pyjamas-desktop has been merged into the pyjamas distribution, which includes support for one stable browser engine (XULrunner, the same engine behind firefox); pywebkitgtk (the engine behind safari and the iphone) and MSHTML (IE's engine). pywebkitgtk is useable (but unfriendly - no DOM exception handling); MSHTML is even less friendly - COM gets in the way at present, and eats even python exceptions). there's a lot more that could be said, but you've probably noticed all the other prerelease notices so 'nuff said, other than: thank you to the people who've been helping and contributing with testing, patches and more. downloads and more information: http://pypi.python.org/pypi/Pyjamas http://sf.net/projects/pyjamas http://code.google.com/p/pyjamas http://pyjs.org -- http://mail.python.org/mailman/listinfo/python-list
trouble with reload
According to the Python documentation, 'reload' reloads a previously imported module (so that changes made via an external editor will be effective). But, when I try to use this command, I get the following error message: TypeError: reload() argument must be module Any suggestions will be appreciated. -- View this message in context: http://www.nabble.com/trouble-with-reload-tp24956946p24956946.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
13-08-2009 azrael jura.gro...@gmail.com wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string I want to format the string. the list has five elements and the string has five placeholder but it wont format the string j must be a tuple -- so either define it as (u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna') or when using it, wrap it with tuple() constructor: h = ... % tuple(j) -- Jan Kaliszewski (zuo) z...@chopin.edu.pl -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with reload
Could you please clarify how you're calling it? E.g. reload('foo') or reload(foo) ? On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman pfeld...@verizon.net wrote: According to the Python documentation, 'reload' reloads a previously imported module (so that changes made via an external editor will be effective). But, when I try to use this command, I get the following error message: TypeError: reload() argument must be module Any suggestions will be appreciated. -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
Me wrote: 13-08-2009 azrael jura.gro...@gmail.com wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string I want to format the string. the list has five elements and the string has five placeholder but it wont format the string j must be a tuple -- so either define it as [snip] PS. If you use Python 2.6 or newer, better use .format() method (then you can use also a list): h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, \ ... d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as \ ... z, drzava as d, valuta as v WHERE u.naziv = '{0}' AND o.naziv = \ ... '{1}' AND z.naziv = '{2}' AND d.naziv = '{3}' AND v.naziv = '{4}'\ ... .format(*j) Cheers, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
Grant Edwards wrote: snipOn 2009-08-13, Dave Angel da...@ieee.org wrote: Grant Edwards wrote: snip interval = 5.0 # interval in seconds next = time.time() while True: now = time.time() if now next: time.sleep(now-next) print call_the_function() next += interval That will be accurate over the long term with minimal jitter. snip 2) If (occasionally) the function takes longer than the specified interval time, my approach does catch-up calls so the average remains the same. I'm still confused -- doesn't mine do that as well? Yep. I missed it again. Clearly it does the catchup the next time around the while loop. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with reload
On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman wrote: According to the Python documentation, 'reload' reloads a previously imported module (so that changes made via an external editor will be effective). But, when I try to use this command, I get the following error message: TypeError: reload() argument must be module That would mean that you're trying to reload something other than a module. Of course you think you're reloading a module. The problem is that... oops, since you don't show the code that leads to this error it's hard to say what the problem is. Any suggestions will be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
On Aug 12, 3:09 pm, David davig...@googlemail.com wrote: Hi all, I'm trying to launch a function at regular time intervals but cannot find the way to do it. Here is the code I wrote (time_interval is a user defined variable in seconds): [snip] Has anyone run into a similar problem (and solved it) ? Thanks for your help I did - as part of a script where I needed to send load into a system at a steady rate. I ended up using threading to do the function calls, since they were not guaranteed to complete before the next interval. duration_start = time.time() interval_counter = 0 while time.time() - duration_start duration: for thread_count in xrange(numthreads): threading.Thread(target=exec_thread, kwargs={#snip unimportant#}).start() interval_counter += 1 time.sleep((duration_start + (interval * interval_counter)) - time.time()) Executing this loop with a simple echo and time print showed that there was no creep over time, and the deviation between intervals was around 1/100th of a second. I'm fairly sure I'm creating some gnarly memory leaks and such by not joining spent threads, but it's been a non-issue in my usage. Adding a list to keep track of the threads and join on complete threads would be fairly trivial to implement. I think for simpler applications, using threading.Timer to kick off the function would work just as well. ~G -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
David wrote: Thanks all for your answers. As suggested by Dave and Frank, I am indeed looking for the main program to continue running in the background (I have several functions I want to launch, each at a predefined time interval). I like Frank's solution, on the paper it seems it would do what I am looking for, but I cannot succeed in having it working. I guess I've been stuck with this problem for too long and can't succeed in using my brain accurately anymore... ;-) I defined the class as defined by Frank, and I then inserted the following code in a While True loop, without any other code (the idea is just to test Frank's solution before really using it in my program): func = MyFunction() func.start() func.stop() func.join() However I'm not getting the expected behavior. It's not taking into account the 30 sec wait, the function is called again and again without any time interval... Any idea ? Again, thanks a lot. Why don't you include the code you're actually trying, instead of just trying to describe it. Frank's class didn't call any function, it just had a place to do it. So we really don't know what you're running, nor what about it is wrong. Perhaps a few well placed print statements? DaveA -- http://mail.python.org/mailman/listinfo/python-list
get output of du / ls command - currently ugly code ...
Hi all, Essentially all I want to know the size of a directory, and the size of a zipped tarball so that I can compute/report the compression ratio. The code I have seems hideous, but it seems to work. Surely there is an easier,more elegant way to do this? dir_size = os.popen('du -sk somename') data = dir_size.readlines() dir_size = int(data[0].split()[0]) print 'dir size: ', dir_size tar_size = os.popen('ls -s somename.tar.gz') data = tar_size.readlines() tar_size = int(data[0].split()[0]) print 'tar size: ', tar_size Thanks Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
On 13 kol, 21:12, Jan Kaliszewski z...@chopin.edu.pl wrote: Me wrote: 13-08-2009 azrael jura.gro...@gmail.com wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string I want to format the string. the list has five elements and the string has five placeholder but it wont format the string j must be a tuple -- so either define it as [snip] PS. If you use Python 2.6 or newer, better use .format() method (then you can use also a list): h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, \ ... d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as \ ... z, drzava as d, valuta as v WHERE u.naziv = '{0}' AND o.naziv = \ ... '{1}' AND z.naziv = '{2}' AND d.naziv = '{3}' AND v.naziv = '{4}'\ ... .format(*j) Cheers, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl Thanks Worked fine for me. I was a freakin idiot. I forgot about using a tuple. damn lists :D Thanks for the debuginig of my thoughts and actions. thnx -- http://mail.python.org/mailman/listinfo/python-list
Re: Help newbie with how to call a source command
Joni Lee wrote: Hi all, I'm landing here because I need some help that I couldn't get through it. Question 1. I want to call a source command from python script. It will source some variables enviroment for further commands. I tried the following which did not work os.sys('source '+source_text) call(['source',source_text], shell=True) commands.getoutput('source '+source_text) Anyone have experiences with this? Because I'm very new to this world so a details reply is really appreciated!!! thank you very much Question 2. I call a shell command from python, this time it runs a script which runs some ruby scripts. And the error returns: ruby: command not found Thank you again 1) You cannot do source from Python. It's a shell command whose very nature is to remember some environment variables for the duration of that particular shell. So once it returns to your python program, they're lost. However, if you just need those variables for invocations of the same shell, you have a couple of choices. You can parse the file yourself, and set up an environment dictionary, and pass that when you invoke subsequent shells. Or you can build a script on the fly, prepending whatever script you're planning to run with that source_text file. 2) In this question, and in general, you need to specify the Python version, the OS environment, the particular Python code you used to launch the shell, the contents of the script, and the results you saw. Use copy and paste, don't just paraphrase. And in a case like this one, somebody familiar with the environment (Ruby on Unix?) will probably have other questions: environment dictionary passed to the shell, did you get a Ruby startup prompt? Or whatever. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: get output of du / ls command - currently ugly code ...
On Aug 13, 8:28 pm, Esmail ebo...@hotmail.com wrote: Hi all, Essentially all I want to know the size of a directory, and the size of a zipped tarball so that I can compute/report the compression ratio. The code I have seems hideous, but it seems to work. Surely there is an easier,more elegant way to do this? dir_size = os.popen('du -sk somename') data = dir_size.readlines() dir_size = int(data[0].split()[0]) print 'dir size: ', dir_size tar_size = os.popen('ls -s somename.tar.gz') data = tar_size.readlines() tar_size = int(data[0].split()[0]) print 'tar size: ', tar_size Thanks Esmail Try using os.path.getsize(somename.tar.gz) -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
On Aug 13, 2009, at 2:56 PM, azrael wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks: http://en.wikipedia.org/wiki/SQL_injection Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: get output of du / ls command - currently ugly code ...
re...@yahoo.co.uk wrote: On Aug 13, 8:28 pm, Esmail ebo...@hotmail.com wrote: Hi all, Essentially all I want to know the size of a directory, and the size of a zipped tarball so that I can compute/report the compression ratio. dir_size = os.popen('du -sk somename') data = dir_size.readlines() dir_size = int(data[0].split()[0]) print 'dir size: ', dir_size Hi, Try using os.path.getsize(somename.tar.gz) Beautiful! .. that takes care of the tarball .. but it doesn't seem to work for reporting the total size of the directory. Any suggestions how to do that in a nicer way? I just looked through os.path.* and there doesn't seem to be a function to report what du -sb would. Thanks for your help, Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: get output of du / ls command - currently ugly code ...
On Thu, 2009-08-13 at 15:28 -0400, Esmail wrote: Hi all, Essentially all I want to know the size of a directory, and the size of a zipped tarball so that I can compute/report the compression ratio. The code I have seems hideous, but it seems to work. Surely there is an easier,more elegant way to do this? dir_size = os.popen('du -sk somename') data = dir_size.readlines() dir_size = int(data[0].split()[0]) print 'dir size: ', dir_size tar_size = os.popen('ls -s somename.tar.gz') data = tar_size.readlines() tar_size = int(data[0].split()[0]) print 'tar size: ', tar_size I don't know about easier, but a more elegant way is to not use os.popen() and to use Python's functions os.path.getsize (or os.stat) and os.walk (or os.path.walk) to achieve this. In fact if you look at the docstring for os.walk there is an example that almost does what you're doing with du, but is cross-platform and not dependent on shelling a process and scraping its stdout. -a -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
On Thu, Aug 13, 2009 at 4:09 PM, Philip Semanchuk phi...@semanchuk.comwrote: On Aug 13, 2009, at 2:56 PM, azrael wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks: http://en.wikipedia.org/wiki/SQL_injection No explanation of SQL injection is complete without a link to the relevant XKCD. http://xkcd.com/327/ Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
[RELEASED] Python 3.1.1 Release Candidate
On behalf of the Python development team, I'm pleased to announce the first release candidate of Python 3.1.1. This bug fix release fixes many normal bugs and several critical ones including potential data corruption in the io library. The final version should be out within the next week. Python 3.1 focuses on the stabilization and optimization of the features and changes that Python 3.0 introduced. For example, the new I/O system has been rewritten in C for speed. File system APIs that use unicode strings now handle paths with undecodable bytes in them. Other features include an ordered dictionary implementation, a condensed syntax for nested with statements, and support for ttk Tile in Tkinter. For a more extensive list of changes in 3.1, see http://doc.python.org/3.1/whatsnew/3.1.html or Misc/NEWS in the Python distribution. To download Python 3.1.1 visit: http://www.python.org/download/releases/3.1/ The 3.1 documentation can be found at: http://docs.python.org/3.1 Bugs can always be reported to: http://bugs.python.org Enjoy! -- Benjamin Peterson Release Manager benjamin at python.org (on behalf of the entire python-dev team and 3.1.1's contributors) -- http://mail.python.org/mailman/listinfo/python-list
need help calculating point between two coordinates.
Hi there I'am working on a route comparison tool for carpools. The route comparison is based on 'steps' retrieved from google maps GDirection. These steps vary in length and i use the coordinates at the beginning of each step. However, sometimes the distance of these steps is too long(ex. driving 30-40 km. on the freeway). Therefore i would like to calculate/find the coordinate located in between two given coordinates. Lets say one step starts at: 56.043185,9.922714 and ends at: 56.234287,9.864521 I would then like to calculate the point right in the middle of these coordinates. I use the haversine form to calculate the distance between coordinates, but im not sure whether or not this can be used for the same purpose. http://www.mpi.nl/world/persons/private ... versine.py I apologize if this thread has been posted the wrong place:) any help is greatly appreciated! kind regards. Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: get output of du / ls command - currently ugly code ...
Albert Hopkins wrote: I don't know about easier, but a more elegant way is to not use os.popen() and to use Python's functions os.path.getsize (or os.stat) and os.walk (or os.path.walk) to achieve this. In fact if you look at the docstring for os.walk there is an example that almost does what you're doing with du, but is cross-platform and not dependent on shelling a process and scraping its stdout. Thanks Albert, I'll take a look, Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
On 13 kol, 22:09, Philip Semanchuk phi...@semanchuk.com wrote: On Aug 13, 2009, at 2:56 PM, azrael wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip I know Already. This is sopussed to be a small office application connecting on a LAN mysql server with no web connection. Thank you anyway -- http://mail.python.org/mailman/listinfo/python-list
Idle text wrap
Hi, I'm using Idle interactive shell. Actually Idle-Spoon which has a few nice extensions and Python 2.6 on Linux. When I print str_value + \n Where str_value is for example a string of 120 chars. I notice that the lines seem to get hard wrapped at around 80. Is there a way I can config it to either wrap to the window, or for a higher amount before wrapping? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
On Aug 13, 2009, at 6:00 PM, azrael wrote: On 13 kol, 22:09, Philip Semanchuk phi...@semanchuk.com wrote: On Aug 13, 2009, at 2:56 PM, azrael wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip I know Already. This is sopussed to be a small office application connecting on a LAN mysql server with no web connection. Thank you anyway You're welcome. I'm glad you are aware. You're ahead of a lot of developers out there. I encourage you to at least think about using parameterized SQL anyway because you never know when someone (maybe even you!) will copy paste your code, or use your library without realizing that it was internal use only. It's usually just as easy as building SQL strings anyway. And besides, what about L'viv? =) Good luck with whatever choice you make Philip -- http://mail.python.org/mailman/listinfo/python-list
implementing descriptors
I am new to Python and I have a question about descriptors. If I have a class as written below, is there a way to use descriptors to be certain that the datetime in start is always before the one in end? class foo(object): def __init__(self,a = None,b = None) self.start = a self.end = b from datetime import datetime c = datetime(2009,8,13,6,15,0) d = datetime(2009,8,14,12,0,0) afoo = foo(c,d) For instance, if the following code were run, I would like to instance of foo to switch the start and end times. afoo.start = datetime(2010,8,13,6,15,0) I was thinking of using the __set__ descriptor to catch the assignment and reverse the values if necessary, but I can't figure out how to determine which values is being set. Thanks for the help! David -- http://mail.python.org/mailman/listinfo/python-list
Re: How to launch a function at regular time intervals ?
On 13 août, 21:28, Dave Angel da...@ieee.org wrote: David wrote: Thanks all for your answers. As suggested by Dave and Frank, I am indeed looking for the main program to continue running in the background (I have several functions I want to launch, each at a predefined time interval). I like Frank's solution, on the paper it seems it would do what I am looking for, but I cannot succeed in having it working. I guess I've been stuck with this problem for too long and can't succeed in using my brain accurately anymore... ;-) I defined the class as defined by Frank, and I then inserted the following code in a While True loop, without any other code (the idea is just to test Frank's solution before really using it in my program): func = MyFunction() func.start() func.stop() func.join() However I'm not getting the expected behavior. It's not taking into account the 30 sec wait, the function is called again and again without any time interval... Any idea ? Again, thanks a lot. Why don't you include the code you're actually trying, instead of just trying to describe it. Frank's class didn't call any function, it just had a place to do it. So we really don't know what you're running, nor what about it is wrong. Perhaps a few well placed print statements? DaveA Yes, I guess it would be more simple. Here is really what I am trying to do. I simplified the functions, but the purpose is to write some text in a local file every x seconds (here, I'm just writing the timestamp, i.e. a string representing the date time, every 10 seconds) and to transfer this file to a distant server via FTP every y seconds (20 seconds in the example below). My code is a little bit more complicated because each time I transfer the file, I delete the local file which is then recreated when data is written, but for simplicity I left this out in the code below. So, here is the code I've been using to test Frank's code. I've been struggling with using or not a While True loop or not, and everything I try seems to run into issues. import threading from datetime import datetime import ftplib class CFtpConnection: FTP Connection parameters def __init__(self, host, port, timeout, user, passwd): self.host = self.port = 21 self.timeout = 60 self.user = self.passwd = class CStoreData(threading.Thread): Write timestamp in a file every 10 seconds in separate thread def __init__(self, timestamp): threading.Thread.__init__(self) self.event = threading.Event() self.timestamp = timestamp def run(self): while not self.event.is_set(): file_handler = open(Test.txt, 'a') file_handler.write(self.timestamp.strftime(%y%m%d%H%M%S \n)) file_handler.close() self.event.wait(10) def stop(self): self.event.set() class CTransferData(threading.Thread): Transfer timestamp file every 20 seconds in separate thread def __init__(self, ftp_connection): threading.Thread.__init__(self) self.event = threading.Event() self.ftp_connection = ftp_connection def run(self): while not self.event.is_set(): file_handler = open(Test.txt, 'r') Ftp_handler = ftplib.FTP('') Ftp_handler.connect(self.ftp_connection.host, self.ftp_connection.port, self.ftp_connection.timeout) Ftp_handler.login(self.ftp_connection.user, self.ftp_connection.passwd) Ftp_handler.storbinary(STOR Test.txt, file_handler) file_handler.close() Ftp_handler.close() self.event.wait(20) def stop(self): self.event.set() ftp_connection = CFtpConnection(, 21, 60, , ) ftp_connection.host = '127.0.0.1' ftp_connection.user = admin ftp_connection.passwd = admin while(1): timestamp = datetime.now() func_store_data = CStoreData(timestamp) func_store_data.start() func_transfer_data = CTransferData(ftp_connection) func_transfer_data.start() func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() -- http://mail.python.org/mailman/listinfo/python-list
Re: implementing descriptors
dippim wrote: I am new to Python and I have a question about descriptors. If I have a class as written below, is there a way to use descriptors to be certain that the datetime in start is always before the one in end? class foo(object): def __init__(self,a = None,b = None) self.start = a self.end = b from datetime import datetime c = datetime(2009,8,13,6,15,0) d = datetime(2009,8,14,12,0,0) afoo = foo(c,d) For instance, if the following code were run, I would like to instance of foo to switch the start and end times. afoo.start = datetime(2010,8,13,6,15,0) I was thinking of using the __set__ descriptor to catch the assignment and reverse the values if necessary, but I can't figure out how to determine which values is being set. Thanks for the help! David Take a look at the example given here. http://users.rcn.com/python/download/Descriptor.htm -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL and Python
On Aug 13, 1:55 pm, catalinf...@gmail.com catalinf...@gmail.com wrote: Hello ! I want use python to change the note from .jpeg files . What is the functions on PIL how make this ? Thank you ! What do u mean by the note? -- http://mail.python.org/mailman/listinfo/python-list
Re: implementing descriptors
On 8/13/2009 3:17 PM dippim said... I am new to Python and I have a question about descriptors. If I have a class as written below, is there a way to use descriptors to be certain that the datetime in start is always before the one in end? class foo(object): def __init__(self,a = None,b = None) self.start = a self.end = b from datetime import datetime c = datetime(2009,8,13,6,15,0) d = datetime(2009,8,14,12,0,0) afoo = foo(c,d) For instance, if the following code were run, I would like to instance of foo to switch the start and end times. afoo.start = datetime(2010,8,13,6,15,0) I was thinking of using the __set__ descriptor to catch the assignment and reverse the values if necessary, why not... class foo(object): def __init__(self,a = None,b = None) self.start = min(a,b) self.end = max(a,b) Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: need help calculating point between two coordinates.
PeteDK wrote: Hi there I'am working on a route comparison tool for carpools. The route comparison is based on 'steps' retrieved from google maps GDirection. These steps vary in length and i use the coordinates at the beginning of each step. However, sometimes the distance of these steps is too long(ex. driving 30-40 km. on the freeway). Therefore i would like to calculate/find the coordinate located in between two given coordinates. Lets say one step starts at: 56.043185,9.922714 and ends at: 56.234287,9.864521 I would then like to calculate the point right in the middle of these coordinates. I use the haversine form to calculate the distance between coordinates, but im not sure whether or not this can be used for the same purpose. http://www.mpi.nl/world/persons/private ... versine.py I apologize if this thread has been posted the wrong place:) any help is greatly appreciated! kind regards. Pete For the distances you're talking about, those coordinates are very close to linear. So to find the midpoint, just average the coordinates. You might be off by half a km, but roads bend more than that. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Python and behavior
Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. ss=1 and f ss 'f' ss=0 and f ss 0 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and behavior
goldtech wrote: Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. ss=1 and f ss 'f' ss=0 and f ss 0 Python's Boolean operators don't turn arbitrary values into True and False values. If you use it in any conditional, you'll get the same result as if it did, but it is occasionally it's nice to get the actual values used in the and instead of having the value distilled down to a True/False. From the Python manual: These are the Boolean operations, ordered by ascending priority: Operation Result Notes |x or y|if x is false, then y, else x (1) |x and y| if x is false, then x, else y (1) |not x| if x is false, then |True|, else |False|(2) Notes: *(1)* These only evaluate their second argument if needed for their outcome. *(2)* not has a lower priority than non-Boolean operators, so |not a == b| is interpreted as |not (a == b)|, and |a == not b| is a syntax error. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and behavior
On Aug 13, 7:36 pm, goldtech goldt...@worldpost.com wrote: Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. ss=1 and f ss 'f' ss=0 and f ss 0 Does this help? ss = True and 'f' ss 'f' ss = False and 'e' ss False -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and behavior
Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. ss=1 and f ss 'f' ss=0 and f ss 0 The and and or operators in Python are actually not true boolean operators: they operate on the more fundamental interpretation of Truth that Python uses (and that 'if' for example uses) that goes back before Python got actual boolean True/False values. x and y evaluates first x; if it is false, its value is returned. Otherwise, the value of y is returned. x or y evaluates first x; if it is true, its value is returned. Otherwise, the value of y is returned. Python's idea of true verses false isn't the same as True and False. It's been described as something verses nothing, as in Python the following are considered false: False, None, numeric 0 (in all types of numbers), empty strings, empty containers (lists, tuples, dictionaries, sets). Everything else is True. Instances of any class are True by default, but they can have a __nonzero__ operation on them to override that. So, every value has an innate 'truthfulness' about it: the 'if' statement bases its decision on that truthfulness. In the context of truthfulness, the string hello is just as true as the singleton True. So, if you do x and y, if 'x' is a false value... then 'x' is returned-- as 'x' is just as false as the singleton False. Both are different ways of saying 'false' in logical operations. Lots of people don't like this. Lots of people do. Some people want it to be pure-true boolean algebra, have them return True/False always-- some people have even argued for if only branching on True/False values. The fact of the matter is, this is all just a fundamental part of Python that pre-dates it ever having true boolean values, and is never gonna go away. There's some useful properties to it, like: value = opt or default In this case, if opt was set to a something, it'll end up in value. Otherwise, default will. Of course that's only useful where a opt would never have a blank string or 0 or such in it naturally. The poor-man's ternary operator was commonly used before Python got a proper one: value = x and Yes or No The construct had some limits(namely, the value in the Yes part of the expression must be truthy), but is still useful in a lot of situations. If x would evaluate true, then value would be set to Yes. Otherwise, it'd be set to No. HTH, --Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and behavior
Gary Herron wrote: goldtech wrote: Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. ss=1 and f ss 'f' ss=0 and f ss 0 Python's Boolean operators don't turn arbitrary values into True and False values. If you use it in any conditional, you'll get the same result as if it did, but it is occasionally it's nice to get the actual values used in the and instead of having the value distilled down to a True/False. From the Python manual: These are the Boolean operations, ordered by ascending priority: Operation Result Notes |x or y|if x is false, then y, else x (1) |x and y| if x is false, then x, else y (1) |not x| if x is false, then |True|, else |False|(2) The Pythonic table would be: Operation Result |x or y|x if x else y |x and y| y if x else x |not x| False if x else False :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: fileinput
On Aug 13, 7:50 am, Dave Angel da...@ieee.org wrote: naaman wrote: On Aug 12, 1:35 pm, Dave Angel da...@ieee.org wrote: naaman wrote: I'm writing my first Python script and I want to use fileinput to open a file in r+ mode. Tried fileinput.input(sys.argv[1:],r+) but that didn't work. ANy ideas? Need to find and overwrite a line in a file several times. I can do it using open and seek() etc. but was wondering if I can use fileinput. thanks; I haven't used it, but check out the 'inplace' keyword parameter. DaveA I've only Python for a week so I'm not sure what inplace does You should read the docs for it (http://www.python.org/doc/2.6.2/library/fileinput.html ), but it's not very clear to me either So I dug up an example on the web: (ref: http://effbot.org/librarybook/fileinput.htm) import fileinput, sys for line in fileinput.input(inplace=1): # /convert Windows/DOS text files to Unix files/ if line[-2:] == \r\n: line = line[:-2] + \n sys.stdout.write(line) The inplace argument tells it to create a new file with the same name as the original (doing all the necessary nonsense with using a scratch file, and renaming/deleting) for each file processed. Stdout is pointed to that new version of the file. Notice that you have to explicitly write everything you want to wind up in the file -- if a given line is to remain unchanged, you just write line directly. If you're new to Python, I do not recommend trying to do open/seek to update a text file in place, especially if you're in DOS. There are lots of traps. the inplace method of fileinput avoids these by implicitly creating temp files and handling the details for you, which probably works great if you're dealing with text, in order. DaveA Thanks Dave. I'll check that out -- http://mail.python.org/mailman/listinfo/python-list
A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode
• A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html plane text version follows: -- A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode Xah Lee, 2009-08-13 Just wanted to express some frustration with whitespace-mode. Emacs 23, just released, has this whitespace-mode feature. It renders spaces, tabs, newlines characters with a visible glyph. This feature, is in Microsoft Word since about 1992. This feature is important in practical ways. For example, when you work with “tab separated line” files (CSV) that's a common format for importing/exporting address books or spreadsheets. It's also important in whitespace-significant langs such as Python. Or, in text processing when placement of space and tabs matters in the output. All i wanted, is to make Space and Tab and Newline chars visible. However, the emacs whitespace-mode does much more than that. It is designed for tech geeking control freaks to tune every aspect of white space in his source code. The mode is filled with bells and whistles. It distinguishes tabs mixed with spaces, EOLs mixed with spaces, EOLs at beginning of file, EOLs at end of file, run on spaces at end of line, lines that has nothing to do with white spaces but is simply longer than 80 chars, etc. Each of these is rendered with different foreground, background, colors, so that they cannot possibly escape the notices of control freaks. By default, most of these are on, so that, when you turn on the mode, most reasonable clean source code become this colorful rainbow unreadable fuck. I tried to tune it, with my 10 years of emacs of fucking 16 hours of using per day, and 3 years of elisp coding experience. But, after a hour, it's confusion hell sans avail. O, that Alex idiot with his emacswiki, refused to lead emacswiki into any readable state. All he can think about is my social skills. (See: Problems of Emacswiki.) What the fuck motherfuck. Hi tech geekers, coding freaks, social science ignoramus fucks, basic economics illiterate FSF fucks, freedom abusing selfish ideologists fucks, Richard Stallman propagandist fuck, we-try-to-be-easy-to-use linuxer idioting fucks, FUCK U. Xah ∑ http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
new version TimingAnalyzer
Hi All, 1.Added a new User Delay and Constraint Editor panel. You can add, delete, or update User Delays or Constraints. 2 .These User Delays and User Constraints are saved at the top of the .tim file. 3.Changing a User Delay or User Constraint updates every one of the same type in the diagram. 4.Files created with previous versions are converted to this new format when saved. 5.Added Python Interpreter, Jython 2.5. Now you can write scripts in Python. 6.Execute Python scripts using the same script dialog for the beanshell scripts or from Jython command line window. 7.Included start_app.py script in the install directory that will start the TimingAnalyzer from a Jython command line window. 8.Updated spice_pwl.bsh. This beanshell script generates spice piece wise linear test vectors for DigitalBus. 9.Included dff.py. This Python script shows how to generate a timing diagram for a D Flip Flop. Anyone interested in helping convert the Java scripts (in the scripts dir) to Python should let me know. Dan Fabrizio www.timing-diagrams.com -- http://mail.python.org/mailman/listinfo/python-list
Re: i Don't get why it makes trouble
On 14 kol, 00:14, Philip Semanchuk phi...@semanchuk.com wrote: On Aug 13, 2009, at 6:00 PM, azrael wrote: On 13 kol, 22:09, Philip Semanchuk phi...@semanchuk.com wrote: On Aug 13, 2009, at 2:56 PM, azrael wrote: j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] len(j) 5 h = SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s' % (j) Traceback (most recent call last): File string, line 1, in string TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip I know Already. This is sopussed to be a small office application connecting on a LAN mysql server with no web connection. Thank you anyway You're welcome. I'm glad you are aware. You're ahead of a lot of developers out there. I encourage you to at least think about using parameterized SQL anyway because you never know when someone (maybe even you!) will copy paste your code, or use your library without realizing that it was internal use only. It's usually just as easy as building SQL strings anyway. And besides, what about L'viv? =) Good luck with whatever choice you make Philip Currently I am working on just a prototype to show what is possible to be done to get me some fundings for my future work. after that I will get over to an SQL Alchemy. It's ORM will take over this business for me. A lot of people a not aware of SQL injection. My friend from college asked me and a couple of other guys for Pen testing of an website. His SQL injection mistake made him an epic fail. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: csv.DictWriter.write_header()
On Wed, Aug 12, 2009 at 4:45 PM, Alan G Isaacalan.is...@gmail.com wrote: Given a csv.DictWriter instance `dw` I think it would be nice to be able to say dw.write_header() instead of dw.writer.writerow(dw.fieldnames) Good idea? Maybe. You could file a bug: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
something like perl's Mail::GPG ?
hello, i am looking for a module with functionality similar to that of the Perl's Mail::GPG package. I need to verify multipart emails that are PGP-signed. thanks for any advice konstantin -- http://mail.python.org/mailman/listinfo/python-list
Re: fileinput
On Aug 13, 7:50 am, Dave Angel da...@ieee.org wrote: naaman wrote: On Aug 12, 1:35 pm, Dave Angel da...@ieee.org wrote: naaman wrote: I'm writing my first Python script and I want to use fileinput to open a file in r+ mode. Tried fileinput.input(sys.argv[1:],r+) but that didn't work. ANy ideas? Need to find and overwrite a line in a file several times. I can do it using open and seek() etc. but was wondering if I can use fileinput. thanks; I haven't used it, but check out the 'inplace' keyword parameter. DaveA I've only Python for a week so I'm not sure what inplace does You should read the docs for it (http://www.python.org/doc/2.6.2/library/fileinput.html ), but it's not very clear to me either So I dug up an example on the web: (ref: http://effbot.org/librarybook/fileinput.htm) import fileinput, sys for line in fileinput.input(inplace=1): # /convert Windows/DOS text files to Unix files/ if line[-2:] == \r\n: line = line[:-2] + \n sys.stdout.write(line) The inplace argument tells it to create a new file with the same name as the original (doing all the necessary nonsense with using a scratch file, and renaming/deleting) for each file processed. Stdout is pointed to that new version of the file. Notice that you have to explicitly write everything you want to wind up in the file -- if a given line is to remain unchanged, you just write line directly. If you're new to Python, I do not recommend trying to do open/seek to update a text file in place, especially if you're in DOS. There are lots of traps. the inplace method of fileinput avoids these by implicitly creating temp files and handling the details for you, which probably works great if you're dealing with text, in order. DaveA I wonder if inline creates an empty file and then the text from the processed file gets written to it. If that's what is going on then it's perfect solution. It will eliminate all the tell() and seek() and overwriting a shorter line with a longer one. I'll try it over the weekend. thanks -- http://mail.python.org/mailman/listinfo/python-list
problem with interface of operator.itemgetter
I have a function to do some thing like LEFT JOIN in SQL, the function use the itemgetter to get the ON and SELECT parameters of the two table(list of list), the problem is that itemgetter may return a value or a tuple of values, because of the inconsistent return type of itemgetter, I have to do 2^3 IF check, the function like this: def left_join(table1, on_index1, table2, on_index2, getter1, getter2): do thing like: SELECT on1(table1), g1(table1), g2(table2) FROM table1 LEFT JOIN table2 ON on1(table1) == on2(table2) on1 = itemgetter(*on_index1) on2 = itemgetter(*on_index2) g1 = itemgetter(*getter1) g2 = itemgetter(*getter2) d2 = {} d2 = dict((on2(r2), r2) for r2 in table2) #if itemgetter always return tuple, below could simple as one line #return [ list(on1(r1) + g1(r1) + g2(d2.get(on1(r1 for r1 in table1 ] len_on = len(on_index1) len_g1 = len(getter1) len_g2 = len(getter2) if len_on == 1: if len_g1 == 1 and len_g2 == 1: return [ [on1(r1), g1(r1), g2(d2.get(on1(r1)))] for r1 in table1 ] elif len_g1 == 1 and len_g2 1: return [ list((on1(r1),g1(r1))+g2(d2.get(on1(r1 for r1 in table1 ] elif len_g1 1 and len_g2 == 1: return [ list((on1(r1),)+g1(r1)+(g2(d2.get(on1(r1))),)) for r1 in table1 ] else: #len_g1 1 and len_g2 1: return [ list((on1(r1),)+g1(r1)+g2(d2.get(on1(r1 for r1 in table1 ] else: # len_on 1 if len_g1 == 1 and len_g2 == 1: return [ list(on1(r1))+[g1(r1),g2(d2.get(on1(r1)))] for r1 in table1 ] elif len_g1 == 1 and len_g2 1: return [ list(on1(r1)+(g1(r1),)+g2(d2.get(on1(r1 for r1 in table1 ] elif len_g1 1 and len_g2 == 1: return [ list(on1(r1)+g1(r1)+(g2(d2.get(on1(r1))),)) for r1 in table1 ] else: #len_g1 1 and len_g2 1: return [ list(on1(r1)+g1(r1)+g2(d2.get(on1(r1 for r1 in table1 ] so is there a way to force itemgetter to return tuple even when itemgetter(only_have_one_argument)? or some other function to do this? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Delegate attribute requests to object
En Thu, 13 Aug 2009 12:50:47 -0300, Evan Kroske e.kro...@gmail.com escribió: I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? You may search the list archives for references to proxy and delegation. The term decorator has a very specific meaning in Python (as a syntax construct), don't use it in the search. Is it possible (without inheritance)? Yes, using delegation. See below. En Thu, 13 Aug 2009 15:29:04 -0300, Rami Chowdhury rami.chowdh...@gmail.com escribió: Oops, my apologies, it's the __getattribute__ method you want to call on self.decorated (because __getattr__ won't be there unless you define it specifically) So it should go: def __getattr__(self, request): return self.decorated.__getattribute__(request) __getattribute__ doesn't exist on old-style classes either. Also, note that very rarely one has to *call* __special__ methods; the code should read: def __getattr__(self, request): return getattr(self.decorated, request) but that works *only* for old-style classes, as discussed here [1]. [3] is another approach for new-style classes (maybe not production-ready yet). And this recipe [2] shows how to make the decorated object keep calling methods on the decorator itself. [1] http://code.activestate.com/recipes/252151/ [2] http://code.activestate.com/recipes/519639/ [3] http://code.activestate.com/recipes/496741/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: fileinput
On Aug 13, 1:20 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Wed, 12 Aug 2009 01:27:47 -0300, naaman arphak...@gmail.com escribió: I'm writing my first Python script and I want to use fileinput to open a file in r+ mode. Tried fileinput.input(sys.argv[1:],r+) but that didn't work. ANy ideas? Don't use fileinput, it can't handle r+, only sequencial access. Even if you could use it, the documentation says [1]: fileinput.input([files[, inplace[, backup[, mode[, openhook]) r+ corresponds to the `inplace` parameter (behaving like inplace=True) instead of `mode`. You could write fileinput.input(sys.argv[1:], mode=r+) instead - but again from the docs: mode... must be one of 'r', 'rU', 'U' and 'rb' Need to find and overwrite a line in a file several times. I can do it using open and seek() etc. but was wondering if I can use fileinput. open+seek is the way to do that (assuming you don't alter the line length) [1]http://docs.python.org/library/fileinput.html#fileinput.input -- Gabriel Genellina unfortunately, I am overwriting shorter with longer -- http://mail.python.org/mailman/listinfo/python-list