ANN: PyQt v4.2 (Python Bindings for Qt)
Riverbank Computing is pleased to announce the release of PyQt v4.2 available from http://www.riverbankcomputing.co.uk/pyqt/. The highlights of this release include: - The ability to write widget plugins for Qt Designer in Python. - Integration of the Python command shell and the Qt event loop. This allows developers to call Qt functions dynamically on a running application. - Integration of the Qt event loop with the standard Python DBus bindings available from www.freedesktop.org. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. See http://www.riverbankcomputing.com/Docs/PyQt4/html/classes.html for the class documentation. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 10 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i18n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtTest A set of classes to automate unit testing of PyQt applications and GUIs. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. QAxContainer A set of classes for Windows that allows the integration of ActiveX controls and COM objects. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: Django Tutorial Part 1 - Setup (New ShowMeDo video in our first Django series)
Summary: Seans shows you how to setup your own Django installation on a bare Ubuntu installation in just 10 minutes. This is the first episode in a longer Django series - please leave an encouraging Thank-You comment if you like Sean's work: http://showmedo.com/videos/video?name=stoops010fromSeriesID=69 Description: Django is a Python web framework used for rapid application development in any environment. In under 10 minutes, we will go from a bare Linux (Ubuntu) installation to a fully functional Django server. This tutorial follows the installation guide found on the official Django website, but a few details have been added for clarification. About Sean Stoops: This is Sean's first video tutorial, he is keen to build a longer series. Would you show your support for Sean by leaving a comment and voting for him please? About ShowMeDo.com: Free videos (we call them ShowMeDos) showing you how to do things. The videos are made by us and our users, for everyone. 89 of our 186 videos are for Python, with more to come. We'd love to have more contributions - would you share what you know? Sharing is easy, full instructions are here: http://showmedo.com/submissionsForm The founders, Ian Ozsvald, Kyran Dale http://ShowMeDo.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: working of round()
On Apr 15, 8:06 pm, [EMAIL PROTECTED] wrote: Does round() always perfectly return the output expected or are there some artifacts which don't allow perfect functionality Using python 2.5: round(12.234, 2) 12.23 round(12.234, 3) 12.234 round(12.234, 1) 12.199 but was expecting 12.2 Also, for round(x,n), can't 'x' be an expression round(5.25/2, 2) was expecting 2.62 , but round(5.25/2, 2) 2.6299 The problem is that floats are encoded as fractions where the denominator is an exponent of 2. 2.63 is not representable as such a fraction. 2.6299... is the closest fraction. Rounding this number will only give you the same thing. If you want decimals to act as expected, use the Decimal class in module decimal. It works as expected, but is much slower. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
In article [EMAIL PROTECTED], Steven W. Orr [EMAIL PROTECTED] wrote: I'm reading a logfile with a timestamp at the begging of each line, e.g., Mar 29 08:29:00 I want to call datetime.datetim() whose arg2 is a number between 1-12 so I have to convert the month to an integer. I wrote this, but I have a sneaky suspicion there's a better way to do it. mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } def mon2int( mon ): global mons return mons[mon] Is there a generator expression or a list comprehension thingy that would be *betterer*? (I realize it's probably not that important but I find lots of value in learning all the idioms.) There's no harm in your method as written, though it were probably wise to tolerate variations in capitalization. But if you want to be cute about it, you could write something like this to set up your table: from datetime import date months = dict((date(1900, x+1, 1).strftime('%b').lower(), x+1) for x in xrange(12)) def month2int(mName): return months[mName.lower()] If you don't like the lookup table, you can get a nicely portable result without it by using time.strptime(), e.g., import time def month2int(mName): return time.strptime(mName, '%b').tm_mon # parses short names Without knowing anything further about your needs, I would probably suggest the latter simply because it makes the hard work be somebody else's problem. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
In [EMAIL PROTECTED], Steven W. Orr wrote: I want to call datetime.datetim() whose arg2 is a number between 1-12 so I have to convert the month to an integer. I wrote this, but I have a sneaky suspicion there's a better way to do it. mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } def mon2int( mon ): global mons return mons[mon] You've already got some answers, I just want to point out that the ``global`` is unnecessary here and that `mons` as a constant should be spelled in capital letters by convention. And maybe it's better to write `MONTHS` instead the abbreviation. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
On Apr 16, 1:14 pm, Paul McGuire [EMAIL PROTECTED] wrote: On Apr 15, 10:33 pm, 7stud [EMAIL PROTECTED] wrote: On Apr 15, 9:30 pm, 7stud [EMAIL PROTECTED] wrote: On Apr 15, 7:30 pm, Steven W. Orr [EMAIL PROTECTED] wrote: Arrgh. import calendar months = calendar.month_abbr #returns an array with the 0 element empty #so the month names line up with the indexes 1-12 d = {} for i in range(1, 13): d[months[i]] = i print d This dict construction idiom is worth learning: d = dict( (a,b) for a,b in ... some kind of list comprehension or generator expr... ) In this case: d = dict( (mon,i) for i,mon in enumerate(calendar.month_abbr) ) Or to avoid including that pesky 0'th blank element: d = dict( [(mon,i) for i,mon in enumerate(calendar.month_abbr)][1:] ) -- Paul Great! -- http://mail.python.org/mailman/listinfo/python-list
Queue enhancement suggestion
I'd like to suggest adding a new operation Queue.finish() This puts a special sentinel object on the queue. The sentinel travels through the queue like any other object, however, when q.get() encounters the sentinel, it raises StopIteration instead of returning the sentinel. It does not remove the sentinel from the queue, so further calls to q.get also raise StopIteration. That permits writing the typical worker thread as for item in iter(q.get): ... without having to mess with the task-counting stuff that recently got added to the Queue module. The writing end of the queue simply calls .finish() when it's done adding items. Someone in an earlier thread suggested # writing side sentinel = object() q.put(sentinel) ... # reading side for item in iter(q.get, sentinel): ... however that actually pops the sentinel, so if there are a lot of readers then the writing side has to push a separate sentinel for each reader. I found my code cluttered with for i in xrange(number_of_worker_threads): q.put(sentinel) which certainly seems like a code smell to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
Hi! Not best, but another lisibility : mons=dict(Jan=1, Feb=2, Fev=2, Mar=3, Apr=4, Avr=4, May=5, Mai=5, Jun=6, Jui=6, Jul=7, Aug=8, Aou=8, Sep=9, Oct=10, Nov=11, Dec=12) def mon2int(m): return mons[m] def mond2int(**m): return mons[m.keys()[0]] print mons['Mar'] print mon2int('May') print mond2int(Jul=0) 3 5 7 (The dict is mixed : French/English) -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
Hi (bis) A class way : class cmon(object): Jan=1 Feb=2 Fev=2 Mar=3 Apr=4 Avr=4 May=5 Mai=5 Jun=6 Jui=6 Juin=6 Jul=7 Juil=7 Aug=8 Aou=8 Sep=9 Oct=10 Nov=11 Dec=12 print cmon.Mar print cmon.Sep print cmon.Dec -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Antigen Notification: Antigen found a message matching a filter
Microsoft Antigen for Exchange found a message matching a filter. The message is currently Detected. Message: Python_list Digest_ Vol 43_ Issue 249 Filter name: KEYWORD= spam: graduate Sent from: [EMAIL PROTECTED] Folder: SMTP Messages\Inbound And Outbound Location: ITURAN/First Administrative Group/VITORIA -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 question
In [EMAIL PROTECTED], Gabriel Genellina wrote: En Thu, 12 Apr 2007 08:43:49 -0300, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] escribió: In [EMAIL PROTECTED], Jorgen Bodde wrote: r = c.execute('select * from song where id = 1') for s in r: ... print s ... (1, u'Spikedrivers Blues', u'Mississippi John Hurt') This should not work because `r` should not be a `Cursor` object. The `execute()`-Method returns an integer with the number of affected rows. Actually DBAPI 2.0 says the return value is undefined. I just remembered the number of affected rows, but that's just for data manipulation statements like ``UPDATE`` or ``INSERT``. For ``SELECT`` the method should return `None`. My bad. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
plz sort this out
Hi, I am using networkx and pylab for creating a graph using a python script abc.py. I have saved the networkx folder in C:/Python24/Lib/site-packages. When I run the script from command prompt, it creates the graph and saves it to the place I want to but when I write a python-cgi script and run it as os.system('python abc.py') it doesn't gives me any result. I have included the path of my system using os.environ['PATH'] = .. I also appended the path of networkx directory using sys.path.append('C:/Python24/Lib/site-packages') as it seems to me that it is a path related problem and the cgi result page shows error (1) networkx *undefined* (2)* *drawing undefined (3) nx_pylab *undefined* (4) matplotlib *undefined* *(5) raise RuntimeError('%s' is not a writable dir; you must set environment variable HOME to be * * a writable dir %h)* Can you please tell me how to enable cgi to run this program on runtime. I have kept both the cgi script as well as python script in Apache/cgi-bin folder. Thanks, Piyali -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting started with python
On Apr 15, 9:49 pm, James Stroud [EMAIL PROTECTED] wrote: py t = timeit.Timer(stmt=s) py print %.2f usec/pass % (100 * t.timeit(number=10)/10) 40.88 usec/pass What does this accomplish: 100 * t.timeit(number=10)/10 that the following doesn't accomplish: 10 * t.timeit(number=10) -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue enhancement suggestion
Paul Rubin wrote: I'd like to suggest adding a new operation Queue.finish() This puts a special sentinel object on the queue. The sentinel travels through the queue like any other object, however, when q.get() encounters the sentinel, it raises StopIteration instead of returning the sentinel. It does not remove the sentinel from the queue, so further calls to q.get also raise StopIteration. That permits writing the typical worker thread as for item in iter(q.get): ... I'd go one step further and implement Queue.__iter__(). The worker than would do for item in q: ... without having to mess with the task-counting stuff that recently got added to the Queue module. The writing end of the queue simply calls .finish() when it's done adding items. Someone in an earlier thread suggested # writing side sentinel = object() q.put(sentinel) ... # reading side for item in iter(q.get, sentinel): ... however that actually pops the sentinel, so if there are a lot of readers then the writing side has to push a separate sentinel for each reader. I find that argument convincing. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and JMS?
Leonard J. Reder napisał(a): Yes indeed, we are using ActiveMQ and I did see the StomPy python package. But I also saw that it said stomp was done as a student project that ended. Maybe I will try hjb for now - all I need to do is listen for messages on a certain topic. Maybe some of our internal people will pick stom and make it better for the future though. I saw there are 2 libraries implementating stomp, the one mentioned by you and one which looked a bit better. The protocol itself also doesn't look very complicated, so this should be relatively easy to implement client library for somebody who works with ActiveMQ on a daily basis. -- Jarek Zgoda We read Knuth so you don't have to. -- http://mail.python.org/mailman/listinfo/python-list
Re: is laziness a programer's virtue?
Daniel Gee [EMAIL PROTECTED] wrote: +--- | You fail to understand the difference between passive laziness and | active laziness. Passive laziness is what most people have. It's | active laziness that is the virtue. It's the desire to go out and / | make sure/ that you can be lazy in the future by spending just a | little time writing a script now. It's thinking about time | economically and acting on it. +--- Indeed. See Robert A. Heinlein's short story (well, actually just a short section of his novel Time Enough For Love: The Lives of Lazarus Long) entitled The Tale of the Man Who Was Too Lazy To Fail. It's about a man who hated work so much that he worked very, *very* hard so he wouldn't have to do any (and succeeded). -Rob - Rob Warnock [EMAIL PROTECTED] 627 26th Avenue URL:http://rpw3.org/ San Mateo, CA 94403 (650)572-2607 -- http://mail.python.org/mailman/listinfo/python-list
Re: Qt4 in ubuntu
On 15 abr, 22:54, Diez B. Roggisch [EMAIL PROTECTED] wrote: Marcpp schrieb: Is possible install Qt4 pyqt4 under kubuntu? Few times ago i tried to run pyqt in ubuntu (gnome) but i can't do it. It's certainly possible. On ubuntu as well as on kubuntu. You can install all KDE and Qt stuff on ubuntu as well. But unless you are more specific what your actual problems were, you can't better help. Diez Hi Diez, finally I can install a Qt4 on Kubuntu, but now I have problems to install a Qt4Designer. I'm introducing to Qt with python, why tutorial you recommend to me? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
Paul McGuire wrote: Me? Push? Boy, a guy posts a couple of examples, tries to help some people that are stuck with a problem, and what does he get? Called pushy? Sheesh! Hey, I never called you pushy! Ok, maybe I sounded a little harsh--I was pretty frustrated after all. I guess I should have said something along the lines of, If you are going to promote pyparsing, it would be nice to be able see what it is all about it. Fortunately, I get enough positive feedback from these posts that my feelings are pretty resilient these days. Anyway, thanks and point taken for the alert on this subject from the newbie's perspective. When I first wrote these installations and started the pyparsing project on SF, I was fairly newb myself - I had to ask Dave Kuhlman to write setup.py for me! So I assumed the target audience already knew the stuff I was having to learn. I assumed that setup.py was just common knowledge among the Python world. I think your suggestion of a Wiki page on this subject should fill this gap neatly, especially since pyparsing is somewhat targetted at the newb and near-newb user, one that is struggling with regexp's or some other parsing technology, and just wants to get some basic code working. The other posts in this thread contain plenty of material to start from. Also, thanks for the Mac OS X point of view, most of my work is on Windows, and a little bit on Linux, but absolutely none on Mac. And I see that I should not assume knowledge of tar, either, so I'll be sure to mention its destructive streak, in overwriting existing files with the same name as those in the archive. Once untar'ed, there *is* a file named README, with an introduction and instructions to invoke setup.py properly. Iol. I read it: - Installation Do the usual: python setup.py install (pyparsing requires Python 2.3.2 or later.) Not much to go on--not even a mention of what directory you should be in when you run that command. Plus, you need to extract the files from the .tar file first. I'm glad to see you perservered and got pyparsing installed. You can also run pyparsing.py itself, which will run a simple SQL parser test. If you have not yet found the docs or examples, *please* look over the sample code in the examples directory, and the class-level documentation in the htmldocs directory. The docs directory should also include the materials from my PyCon'06 presentations. Please post back, either here or on the Pyparsing wiki discussion pages, and let me know how your pyparsing work is progressing. -- Paul (the developer, but you can call me Paul) I'm pretty facile with regex's, and after looking at some pyparsing threads over the last week or so, I was interested in trying it. However, all of the beginning examples use a Word() in the parse expression, but I couldn't find an adequate explanation of what the arguments to Word() are and what they mean. I finally found the information buried in one of the many documents--the one called Using the Pyparsing Module. If that seems like an obvious place to look, I did start there, but I didn't find it at first. I also scoured the the wiki, and I looked in the file pycon06- IntroToPyparsing-notes.pdf, which has this: Basic Pyparsing Words and Literals -- http://mail.python.org/mailman/listinfo/python-list
Re: Qt4 in ubuntu
Hi Diez, finally I can install a Qt4 on Kubuntu, but now I have problems to install a Qt4Designer. I'm introducing to Qt with python, why tutorial you recommend to me? Google for them. And use C++-tutorials, they can be easily translated to python. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
On Apr 16, 2:06 am, 7stud [EMAIL PROTECTED] wrote: Hmmm. My post got cut off. Here's the rest of it: I'm pretty facile with regex's, and after looking at some pyparsing threads over the last week or so, I was interested in trying it. However, all of the beginning examples use a Word() in the parse expression, but I couldn't find an adequate explanation of what the arguments to Word() are and what they mean. I finally found the information buried in one of the many documents--the one called Using the Pyparsing Module. If that seems like an obvious place to look, I did start there, but I didn't find it at first. I also scoured the the wiki, and I looked in the file pycon06- IntroToPyparsing-notes.pdf, which has this: Basic Pyparsing Words and Literals -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Feature Request: Allow changing base of member indices to 1
Paddy, Dijkstra's argument is obsolete, as it is based on how array length was computed many years ago -- if we have an array a = b..e, then the lenght of a is e-b (half open range). Good at low level programming. But a quarter of a century after we know concepts are much better than low level programming and explicit computations -- if we have an array a = b..e, then the length of a should be a.length() (or a.length(b,e)), and it is independent of Hi Javier, You seem to have missed out array *indexing* in your argument, or is array indexing obsolete? Of course, it isn't, but it has evolved over the past 25 years. When Djikstra wrote that, many people (including me) was using a Spectrum--- Now we have OO programming to deal with concepts and a more generic programming. So, to me it's clear his _argument_ is very outdated and cannot be applied directly and withot reservations to modern languages like Python. Javier - http://www.texytipografia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
Basic Pyparsing Words and Literals -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
Word(ABC, def) matches C, Added, Beef but not BB, ACE, ADD That is just baffling. There's no explanation that the characters specified in the first string are used to match the first char of a word and that the characters specified in the second string are used to match the rest of the word. It would also help to know that if only one string is specified, then the specified characters will be used to match all the chars in a word. I think you should add a simple example to your wiki that explains all that. Also, I think you should state right up front that alphas is a string made up of the chars a-zA-z and that nums is a string made up of the chars 0-9. That way when someone sees Word(alphas), they will understand exactly what that means. Also since matching any char is a pretty common thing, I think you should mention what printables is as well. In any case this is the example I applied pyparsing to: Given .txt file(all on one line). Requirement--construct a list from the text: - mara = [ 'U2FsdGVkX185IX5PnFbzUYSKg+wMyYg9', 'U2FsdGVkX1+BCxltXVTQ2+mo83Si9oAV0sasmIGHVyk=', 'U2FsdGVkX18iUS8hYBXgyWctqpWPypVz6Fj49KYsB8s=' ] --- and this is what I came up with: -- from pyparsing import Word, alphas, commaSeparatedList name = Word(alphas) lookFor = name + = + [ + commaSeparatedList + ] my_file = open(aaa.txt) for line in my_file: alist = lookFor.parseString(line) globals()[alist[0] ] = [ alist[3].strip('), alist[4].strip('), alist[5].strip(') ] print mara[2] -- Any tips? -- http://mail.python.org/mailman/listinfo/python-list
Re: File DB instead of real database?
Jia Lu a e'crit : Hello all I donot want to use a real DB like MySQL ... Whether MySQL is qualifies as a real DB is still an open question. But you can use SQLite, which is an embedded SQL database. -- http://mail.python.org/mailman/listinfo/python-list
please sort this out
Hi, I am using networkx and pylab for creating a graph using a python script abc.py. I have saved the networkx folder in C:/Python24/Lib/site-packages. When I run the script from command prompt, it creates the graph and saves it to the place I want to but when I write a python-cgi script and run it as os.system('python abc.py') it doesn't gives me any result. I have included the path of my system using os.environ['PATH'] = .. I also appended the path of networkx directory using sys.path.append('C:/Python24/Lib/site-packages') as it seems to me that it is a path related problem and the cgi result page shows error (1) networkx *undefined* (2)* *drawing undefined (3) nx_pylab *undefined* (4) matplotlib *undefined* *(5) raise RuntimeError('%s' is not a writable dir; you must set environment variable HOME to be * * a writable dir %h)* Can you please tell me how to enable cgi to run this program on runtime. I have kept both the cgi script as well as python script in Apache/cgi-bin folder. Thanks, Piyali -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
In [EMAIL PROTECTED], 7stud wrote: However, all of the beginning examples use a Word() in the parse expression, but I couldn't find an adequate explanation of what the arguments to Word() are and what they mean. I finally found the information buried in one of the many documents--the one called Using the Pyparsing Module. If that seems like an obvious place to look, I did start there, but I didn't find it at first. An obvious place should be the docstring of the `Word` class which says: Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: is laziness a programer's virtue?
Dan Bensen [EMAIL PROTECTED] writes: Xah Lee wrote: Laziness, Perl, and Larry Wall When the sorcerer Larry Wall said âThe three chief virtues of a programmer are: Laziness, Impatience and Hubrisâ, he used the word âlazinessâ to loosely imply ânatural disposition that results in being economicâ. Programming by definition is the process of automating repetitive actions to reduce the human effort required to perform them. A good programmer faced with a hard problem always looks for ways to make his|her job easier by delegating work to a computer. That's what Larry means. Automation is MUCH more effective than repetition. Indeed. A programmer is someone who, after doing similar tasks by hand a few times, writes a program to do it. This extends to programming tasks, so after writing similar programs a few times, a (good) programmer will use programming to make writing future similar programs easier. This can be by abstracting the essence of the task into library functions so new programs are just sequences of parameterized calls to these, or it can be by writing a program generator (such as a parser generator) or it can be by designing a domain-specific language and writing a compiler or interpreter for this. Torben -- http://mail.python.org/mailman/listinfo/python-list
string methods of a str subclass
I am probably misunderstanding some basic issue here but this behaviour is not what I would expect: Python 2.4 (#1, Mar 22 2005, 21:42:42) [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2 Type help, copyright, credits or license for more information. class mystr( str ): ... pass ... x = mystr( 'x' ) isinstance( x, mystr ) True isinstance( x.strip( ), mystr ) False Why is the strip( ) method returning something that is not a mystr instance? I would expect all methods operating on a string instance and returning another string instance to correctly operate on a mystr instance and return a mystr instance. How would I achieve something like this without manually copying all string returning methods from str and stuffing the result to mystr( ) before returning? -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue enhancement suggestion
On 2007-04-16, Paul Rubin http wrote: I'd like to suggest adding a new operation Queue.finish() This puts a special sentinel object on the queue. The sentinel travels through the queue like any other object, however, when q.get() encounters the sentinel, it raises StopIteration instead of returning the sentinel. It does not remove the sentinel from the queue, so further calls to q.get also raise StopIteration. That permits writing the typical worker thread as for item in iter(q.get): ... The problem is this doesn't work well if you have multiple producers. One producer can be finished while the other is still putting values on the queue. The solution I have been thinking on is the following. Add an open and close operation. Only threads that have the queue open can access it. The open call should specify whether you want to read or write to the queue or both. When all writers have closed the queue and the queue is empty a q.get will raise an exception. This may be done by putting a sentinel on the queue when the last writer closed the queue. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Method calls and stack consumption
Martin Manns wrote: Thanks for pointing out the oversimplified nature of the original example.I hope that the following one clarifies the problem. (I do not know, what has to be stored on the stack, but it should not be that much, because all recursion calls originate from inside the return statement.) class Node(object): def __init__(self): self.state = abs(randint(1,1000)) def GetDepState(self): return self.state + max(s.GetDepState() for s in S[self]) class ConditionalBreakNode(Node): def GetDepState(self): if randint(1,5) 1: return Node.GetDepState(self) else: return self.state Have you investigated the libraries available for that kind of problem? (No, I don't know them) Maybe one of them provides an implementation that does not depend on the stack. On the other hand, if the above is the natural expression of your problem, why not give stackless a try? Peter -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyQt v4.2 (Python Bindings for Qt)
Riverbank Computing is pleased to announce the release of PyQt v4.2 available from http://www.riverbankcomputing.co.uk/pyqt/. The highlights of this release include: - The ability to write widget plugins for Qt Designer in Python. - Integration of the Python command shell and the Qt event loop. This allows developers to call Qt functions dynamically on a running application. - Integration of the Qt event loop with the standard Python DBus bindings available from www.freedesktop.org. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. See http://www.riverbankcomputing.com/Docs/PyQt4/html/classes.html for the class documentation. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 10 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i18n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtTest A set of classes to automate unit testing of PyQt applications and GUIs. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. QAxContainer A set of classes for Windows that allows the integration of ActiveX controls and COM objects. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. -- http://mail.python.org/mailman/listinfo/python-list
Compare regular expressions
Hi, I'm writing a program with a large data stream to which modules can connect using regular expressions. Now I'd like to not have to test all expressions every time I get a line, as most of the time, one of them having a match means none of the others can have so. But ofcource there are also cases where a regular expression can contain another expression, like in: ^strange line (\w+) and (\w+)$ and ^strange line (\w+) (?:.*?)$ in which case I'd like to first test the seccond and only if it mathces test the seccond. Do anybody know if such a test is possible? if exp0.contains(exp1): ... -- http://mail.python.org/mailman/listinfo/python-list
Re: string methods of a str subclass
On Apr 16, 3:28 am, Daniel Nogradi [EMAIL PROTECTED] wrote: I am probably misunderstanding some basic issue here but this behaviour is not what I would expect: Python 2.4 (#1, Mar 22 2005, 21:42:42) [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2 Type help, copyright, credits or license for more information. class mystr( str ): ... pass ... x = mystr( 'x' ) isinstance( x, mystr ) True isinstance( x.strip( ), mystr ) False Why is the strip( ) method returning something that is not a mystr instance? I would expect all methods operating on a string instance and returning another string instance to correctly operate on a mystr instance and return a mystr instance. How would I achieve something like this without manually copying all string returning methods from str and stuffing the result to mystr( ) before returning? class A(object): def __init__(self, s): self.s = s def strip(self): return 2 class mystr(A): pass x = mystr(x) print isinstance(x, mystr) print isinstance(x.strip(), mystr) -- http://mail.python.org/mailman/listinfo/python-list
Re: Portably generating infinity and NaN
Paul Rubin wrote: [EMAIL PROTECTED] writes: But PEP 754 will only work for architectures supporting IEEE 754. I realize that's the vast majority of systems, but aren't there still a few Crays and VMS machines out there? (Do those architectures support NaN and Inf?) I wouldn't worry about it. There are Python subsystems (like threads) that don't work on certain OS's, fine, total portability means not being able to rely on them, and that's ok. I doubt any Crays are still running, or at least running any numerical code written in Python. Same for VMS. Do these systems provide infinities or NaN? If so, then fpconst could be extended to include them. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: string methods of a str subclass
Daniel Nogradi [EMAIL PROTECTED] wrote: Why is the strip( ) method returning something that is not a mystr instance? I would expect all methods operating on a string instance and returning another string instance to correctly operate on a mystr instance and return a mystr instance. Why would you expect that? Would you expect the __str__ and__repr__ methods also to return a mystr instance? If not those, then which other ones might also be excluded? Is x.encode('zip') still a mystr instance or an encoded byte-string? How would I achieve something like this without manually copying all string returning methods from str and stuffing the result to mystr( ) before returning? You don't without wrapping all the affected methods. It doesn't need to involve manual copying though: you have a programming language available so just write a list of method names and then some code to wrap them automatically. -- http://mail.python.org/mailman/listinfo/python-list
How to generate a continuous string
How to generate a continuous string, like this aaa the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) -- http://mail.python.org/mailman/listinfo/python-list
newbie question: how to read back the dictionary from a file?
Hi Dear all, I have some data here in the form of a dictionary, called vdic. Then I write them to a data file f using the write function as f.write(str(vdic)). The keys of this dictionary are integers and values are float numbers. Something like this: { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} Now, I want to read these data back in another function. Of course, I could parse the string little by little, e.g, first read a {, then loop read a int, then read a :, then a float etc etc... Since it is written out with standard python builtin functions, I guess there may be some more direct method than this, say a function in some modules? Could someone give me a hint? -- http://mail.python.org/mailman/listinfo/python-list
Re: string methods of a str subclass
On Apr 16, 3:28 am, Daniel Nogradi [EMAIL PROTECTED] wrote: I would expect all methods operating on a string instance and returning another string instance Ok, then this: class A(object): def __init__(self, s): self.s = s def strip(self): return self.s class mystr(A): pass x = mystr(x) print isinstance(x, mystr) print isinstance(x.strip(), mystr) x is a string, and that is what gets passed to the base class's __init__ method, and that is what strip() operates on. -- http://mail.python.org/mailman/listinfo/python-list
Rapyd-Tk Pmw Notebook tutorial
Hello, could anybody be so kind and write me a small tutorial about how to create a Pmw notebook with 3 tabs each containing 5 checkboxes with the help of Rapyd-Tk? Thanks in advance rg, boris -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate a continuous string
In [EMAIL PROTECTED], 人言落日是天涯,望极天涯不见家 wrote: How to generate a continuous string, like this aaa the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) Even easier: multiply the string by a number. In [12]: 'a' * 5 Out[12]: 'a' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate a continuous string
On 16 avr, 12:03, 人言落日是天涯,望极天涯不见家 [EMAIL PROTECTED] wrote: How to generate a continuous string, like this aaa the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) a*10 'aa' a*20 '' -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate a continuous string
On Apr 16, 2007, at 5:03 AM, 人言落日是天涯,望极天涯不 见家 wrote: How to generate a continuous string, like this aaa the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) It's even easier than that -- just multiply: 'a' * 32 '' -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to read back the dictionary from a file?
On 16 Apr 2007 03:03:40 -0700, lancered [EMAIL PROTECTED] wrote: Hi Dear all, I have some data here in the form of a dictionary, called vdic. Then I write them to a data file f using the write function as f.write(str(vdic)). The keys of this dictionary are integers and values are float numbers. Something like this: { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} Now, I want to read these data back in another function. Of course, I could parse the string little by little, e.g, first read a {, then loop read a int, then read a :, then a float etc etc... Since it is written out with standard python builtin functions, I guess there may be some more direct method than this, say a function in some modules? Could someone give me a hint? Check out cPickle or shelve modules. Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate a continuous string
On 16 Apr 2007 03:03:26 -0700, 人言落日是天涯,望极天涯不见家 [EMAIL PROTECTED] wrote: How to generate a continuous string, like this aaa the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) mystr = mychar*n n: Integer (number of times you want to duplicate) Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to read back the dictionary from a file?
On Apr 16, 4:03 am, lancered [EMAIL PROTECTED] wrote: Hi Dear all, I have some data here in the form of a dictionary, called vdic. Then I write them to a data file f using the write function as f.write(str(vdic)). The keys of this dictionary are integers and values are float numbers. Something like this: { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} Now, I want to read these data back in another function. Of course, I could parse the string little by little, e.g, first read a {, then loop read a int, then read a :, then a float etc etc... Since it is written out with standard python builtin functions, I guess there may be some more direct method than this, say a function in some modules? Could someone give me a hint? Try: import shelve s = shelve.open(newFile.dat) s[d] = {red:2, 3:blue, 2.5:x} s.close() s = shelve.open(newFile.dat) print s[d] my_dict = s[d] print my_dict[2.5] -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to read back the dictionary from a file?
s.close() -- http://mail.python.org/mailman/listinfo/python-list
Signal Handlers
Hello Guys, Thanks again for all the help you've given me this past week, things are moving briskly and my class library is building nicely and seems to be working well :-D Now, I'm working with an API for another piece of software today, and the API documentation details the signals that are broadcast upon particular events, which I need to listen for and then handle. Here is an example: void RemoteDeviceFound(string address, uint32 class, int16 rssi) This signal will be send every time an inquiry result has been found by the service daemon. In general they only appear during a device discovery. Now, how do I listen for this signal? I've seen a couple of examples where by they import the signal module, and then to signal.signal(RemoteDeviceFound, myFunctionToCall) but the python documentation seemed to think that this would be limited to 2 arguments, when I've obviously got 3 of them. Perhaps I've got my wires crossed, if it's really that simple then great. However, where about in my application should I declare that signal listener? Thanks, Rob -- http://mail.python.org/mailman/listinfo/python-list
Boost Problem! Boost.Build not found
Hi! I'm trying to extend my python program with some C++ code. Right now I've spent hours just trying to get boost to work! I'm trying to get the example hello.cpp to work. Using Windows XP and Visual Studio 8 (.NET 2005) I've set BOOST_BUILD_PATH = C:\boost\boost_1_33_1 (where i installed boost) I've changed the jamrules in C:\boost\boost_1_33_1\libs\python\example \tutorial to path-global BOOST_ROOT : C:\boost\boost_1_33_1 ; No matter what I do i always get: C:\boost\boost_1_33_1\libs\python\example\tutorialbjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find boost-build.jam --- Attempted search from C:\boost\boost_1_33_1\libs\python\example \tutorial up to t he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: C:\boost\boost_1_ 33_1. Please consult the documentation at 'http://www.boost.org'. Can anyone please tell me what I am doing wrong?? Theres no tutorial on how to make a boost-build.jam file.. and as I understand I don't need one as long as I set BOOST_BUILD_PATH .. Any help is apprecieated!! Thanks!, Soren -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes and pointers
[This might be a double posting, if it isn't my previous post was lost] Look up restype in the ctypes library - it sets the return type from a function. You may want to set it to c_void_p of something similar, instead of the default int. I made a similar discovery in my blog - http://www.pererikstrandberg.se/blog/index.cgi?page=PythonCansiCombo . This example loads the function find_root from the dll root_find_lib.dll into the variable find. the restype of find is then set to a c_double. This means that the item returned from C is a C_double and not the default int. root_find_lib = windll.LoadLibrary(root_find_lib.dll) find = root_find_lib.find_root find.restype = c_double You may already know this but 243666016 == 0E860C60 in different bases. HTH, Per [:)]-|-- -- Per Erik Strandberg .NET Architect - Optimization Tomlab Optimization Inc. http://tomopt.com/tomnet/ On 14 Apr, 19:25, Diez B. Roggisch [EMAIL PROTECTED] wrote: Hi, I'm working under mac os x with the OpenCV-library that I load viactypes. From a ObjectiveC-methodcall I get an integer, that really is a pointer to an IplImage-structure. I've got a function that takes such a pointer. But I don't find a way to pass it to that very function. These are the relevant parts of my code: cvImage = self._f.cvImage() print Address of IplImage: %x % cvImage cvImage = c_void_p(cvImage) print cvImage cvImage2 = macopencv.cvCloneImage(cvImage) The output is 2007-04-14 19:22:53.910 SequenceGrabberTest[5320] Returning IplImage at Address of IplImage: e860c60 e860c60 c_void_p(243666016) 2007-04-14 19:22:53.915 SequenceGrabberTest[5320] Exception raised during posting of notification. Ignored. exception: exceptions.ValueError: depythonifying 'pointer', got 'int' The first line is actually from the ObjectivC-method, a log-statement. As one can see, the pointer is passed back as integer. But then I'm stuck. Any suggestions would be appreciated! diez -- http://mail.python.org/mailman/listinfo/python-list
how to combine two applications in pygtk
hi, I want to know how to integrate two applications in pygtk. Should we add any header files in the main program or import any modules. also if we need to import any modules then how to convert the application in a module. Pls reply to this mail as soon as possible. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
Soren wrote: Unable to load Boost.Build: could not find boost-build.jam --- Attempted search from C:\boost\boost_1_33_1\libs\python\example \tutorial up to t he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: C:\boost\boost_1_ 33_1. Please consult the documentation at 'http://www.boost.org'. Can anyone please tell me what I am doing wrong?? Theres no tutorial on how to make a boost-build.jam file.. and as I understand I don't need one as long as I set BOOST_BUILD_PATH .. Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: is laziness a programer's virtue?
[EMAIL PROTECTED] (Rob Warnock) writes: Daniel Gee [EMAIL PROTECTED] wrote: +--- | You fail to understand the difference between passive laziness and | active laziness. Passive laziness is what most people have. It's | active laziness that is the virtue. It's the desire to go out and / | make sure/ that you can be lazy in the future by spending just a | little time writing a script now. It's thinking about time | economically and acting on it. +--- Indeed. See Robert A. Heinlein's short story (well, actually just a short section of his novel Time Enough For Love: The Lives of Lazarus Long) entitled The Tale of the Man Who Was Too Lazy To Fail. It's about a man who hated work so much that he worked very, *very* hard so he wouldn't have to do any (and succeeded). You can also argue that the essence of progress is someone saying Hey, there must be an easier way to do this!. Torben -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
On 16 Apr., 12:53, Rob Wolfe [EMAIL PROTECTED] wrote: Soren wrote: Unable to load Boost.Build: could not find boost-build.jam --- Attempted search from C:\boost\boost_1_33_1\libs\python\example \tutorial up to t he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: C:\boost\boost_1_ 33_1. Please consult the documentation at 'http://www.boost.org'. Can anyone please tell me what I am doing wrong?? Theres no tutorial on how to make a boost-build.jam file.. and as I understand I don't need one as long as I set BOOST_BUILD_PATH .. Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; -- HTH, Rob Hi Rob, Thanks for answer! It did solve the error... but created a new one: C:\boost\boost_1_33_1\libs\python\example\tutorialbjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. - C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find bootstrap.jam in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). What is boostrap.jam? I haven't seen that one mentioned in the short tutorial... Thanks!, Soren -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
On 16 Apr., 12:53, Rob Wolfe [EMAIL PROTECTED] wrote: Soren wrote: Unable to load Boost.Build: could not find boost-build.jam --- Attempted search from C:\boost\boost_1_33_1\libs\python\example \tutorial up to t he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: C:\boost\boost_1_ 33_1. Please consult the documentation at 'http://www.boost.org'. Can anyone please tell me what I am doing wrong?? Theres no tutorial on how to make a boost-build.jam file.. and as I understand I don't need one as long as I set BOOST_BUILD_PATH .. Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; -- HTH, Rob Hi Rob, Thanks for the answer! It did solve the error.. but produced a new one: C:\boost\boost_1_33_1\libs\python\example\tutorialbjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. - C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find bootstrap.jam in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). What is bootstrap.jam? .. Haven't seen that one in the short tutorial... Thanks alot!, Soren -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting started with python
James Stroud wrote: Steve Holden wrote: You'd be worth more if you'd used elif and omitted the continue statements, but for a first solution it's acceptable. Depends on what you are after. py s = ... for i in xrange(1,101): ... if not i % 15: ... continue ... if not i % 5: ... continue ... if not i % 3: ... continue ... else: ... pass ... py t = timeit.Timer(stmt=s) py print %.2f usec/pass % (100 * t.timeit(number=10)/10) 40.49 usec/pass py s = ... for i in xrange(1,101): ... if not i % 15: ... pass ... elif not i % 5: ... pass ... elif not i % 3: ... pass ... else: ... pass ... py t = timeit.Timer(stmt=s) py print %.2f usec/pass % (100 * t.timeit(number=10)/10) 40.88 usec/pass To be strictly comparable you should have pass statements before the continue statements as well. Ignoring that, clearly it's well worth saving that extra 390 nanoseconds each time round the loop. Repeat after me premature optimization is the root of all evil. http://en.wikipedia.org/wiki/Optimization_(computer_science) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes and pointers
per9000 wrote: [This might be a double posting, if it isn't my previous post was lost] Look up restype in the ctypes library - it sets the return type from a function. You may want to set it to c_void_p of something similar, instead of the default int. I made a similar discovery in my blog - http://www.pererikstrandberg.se/blog/index.cgi?page=PythonCansiCombo . This example loads the function find_root from the dll root_find_lib.dll into the variable find. the restype of find is then set to a c_double. This means that the item returned from C is a C_double and not the default int. root_find_lib = windll.LoadLibrary(root_find_lib.dll) find = root_find_lib.find_root find.restype = c_double I found the solution to be X.from_address(address) where X is some ctypes.Structure Diez -- http://mail.python.org/mailman/listinfo/python-list
Import From SubFolder
Chaps, Is it possible to import a module from a subdirectory in my application? I can only seem to get it to import from a single directory, but keeping all my files and classes in the same directory becomes a little sloppy. Thanks, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: File DB instead of real database?
On 13 Apr 2007 21:14:36 -0700, Jia Lu [EMAIL PROTECTED] wrote: I donot want to use a real DB like MySQL ... But I need something to save about more than 1000 articles. Is there any good ways? SQLite is a good option, as you were told. But what about put them in a dictionary and then cPickle it to disk? (using 2 as optimization setting in cPickle command). -- http://mail.python.org/mailman/listinfo/python-list
How to tell whetehr Python script called as CGI or from command line?
I'm writing a Python script that can either be called as a Cron job or as a web page (i.e. as a CGI in response to an HTTP request). This is to process the mailboxes on my web server (to which I don't have command line access) to remove old messages. How do I find out whether the script has been called as a Cron job or as a CGI? I need to know this so I can format the output correctly, e.g. if this is a web request I need to start the output with Content-type: text/html\n \nhtml, to do newlines by p or br etc. Can I just access some header line which will always have a value in a web request, but which will be None if running from the command line or as a Cron job, or something similar? How? Thanks - Rowan -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
On Apr 16, 3:27 am, 7stud [EMAIL PROTECTED] wrote: sample problem snipped Any tips? 7stud - Here is the modified code, followed by my comments. Oh, one general comment - you mention that you are quite facile with regexp's. pyparsing has a slightly different philosophy from that of regular expressions, especially in the areas of whitespace skipping and backtracking. pyparsing will automatically skip whitespace between parsing expressions, whereas regexp's require explicit '\s*' (unless you specify the magic whitespace between elements allowed attribute which I don't remember its magic attribute character at the moment, but I rarely see regexp examples use it). And pyparsing is purely a left-to-right recursive descent parser generator. It wont look ahead to the next element past a repetition operation to see when to stop repeating. There's an FAQ on this on the wiki. -- from pyparsing import Word, alphas, commaSeparatedList, delimitedList, sglQuotedString, removeQuotes name = Word(alphas) lookFor = name + = + [ + commaSeparatedList + ] # comment #0 my_file = \ mara = [ 'U2FsdGVkX185IX5PnFbzUYSKg+wMyYg9', 'U2FsdGVkX1+BCxltXVTQ2+mo83Si9oAV0sasmIGHVyk=', 'U2FsdGVkX18iUS8hYBXgyWctqpWPypVz6Fj49KYsB8s=' ] my_file = .join(my_file.splitlines()) # uncomment next line once debugging of grammar is finished # my_file = open(aaa.txt).read() # comment #1 #~ my_file = open(aaa.txt) #~ for line in my_file: for line in [my_file,]: alist = lookFor.parseString(line) globals()[alist[0] ] = [ alist[3].strip('), alist[4].strip('), alist[5].strip(') ] # comment #2 def stripSingleQuotes(s): return s.strip(') globals()[alist[0] ] = map(stripSingleQuotes, alist[3:-1] ) print mara[2] mara = None # comment #3 lookFor = name.setResultsName(var) + = + [ + \ commaSeparatedList.setResultsName(listValues) + ] alist = lookFor.parseString(my_file) # evaluate parsed assignment globals()[ alist.var ] = map(stripSingleQuotes, alist.listValues ) print len(mara), mara[1] # comment #4 lookFor = name.setResultsName(var) + = + [ + \ delimitedList( sglQuotedString.setParseAction(removeQuotes) )\ .setResultsName(listValues) + ] alist = lookFor.parseString(my_file) globals()[ alist.var ] = list( alist.listValues ) print len(mara), mara[1] -- Comment #0: When I am debugging a pyparsing application, I find it easier to embed the input text, or a subset of it, into the program itself using a triple-quoted string. Then later, I'll go back and change to reading data from an input file. Purely a matter of taste, but it simplifies posting to mailing lists and newsgroups. Comment #1: Since you are going line by line in reading the input file, be *sure* you have the complete assignment expression on each line. Since pyparsing will read past line breaks for you, and since your input file contains only this one assignment, you might be better off calling parseString with: alist = lookFor.parseString( my_file.read() ) Comment #2: Your assignment of the mara global is a bit clunky on two fronts: - the explicit accessing of elements 3,4, and 5 - the repeated calls to strip(') You can access the pyparsing returned tokens (passed as a ParseResults object) using slices. In your case, you want the elements 3 through n-1, so alist[3:-1] will give you this. It's nice to avoid hard- coding things like list lengths and numbers of list elements. Note that you can also use len to find out the length of the list. As for calling strip(') for each of these elements, have you learned to use Python's map built-in yet? Define a function or lambda that takes a single element, return from the function what you want done with that element, and then call map with that function, and the list you want to process. This modified version of your call is more resilient than the original. Comment #3: Personally, I am not keen on using too much explicit indexing into the returned results. This is another area where pyparsing goes beyond typical lexing and tokenizing. Just as you can assign names to fields in regexp's, pyparsing allows you to give names to elements within the parsed results. You can then access these by name, using either dict or object attribute syntax. This gets rid of most if not all of the magic numbers from your code, and makes it yet again more resilient in light of changes in the future. (Say for example you decided to suppress the =, [, and ] punctuation from the parsed results. The parsing logic would remain the same, but the returned tokens would contain only the significant content, the variable name and list contents. Using explicit list indexing would force you to renumber the list elements you are extracting, but with results names, no change would be required.) Comment #4: I thought I'd show you an alternative to commaSeparatedList, called delimitedList. delimitedList is a method that gives you more control over the elements you expect to find within the list, and
Re: Boost Problem! Boost.Build not found
Soren wrote: Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; Hi Rob, Thanks for the answer! It did solve the error.. but produced a new one: C:\boost\boost_1_33_1\libs\python\example\tutorialbjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. - C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find bootstrap.jam in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). There is something wrong with your boost installation. Do you have subdirectory tools/build/v1 in your installation? What is bootstrap.jam? .. Haven't seen that one in the short tutorial... It is essential for boost build system that the file bootstrap.jam could be found. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: How to tell whetehr Python script called as CGI or from command line?
[EMAIL PROTECTED] wrote: I'm writing a Python script that can either be called as a Cron job or as a web page (i.e. as a CGI in response to an HTTP request). This is to process the mailboxes on my web server (to which I don't have command line access) to remove old messages. How do I find out whether the script has been called as a Cron job or as a CGI? I need to know this so I can format the output correctly, e.g. if this is a web request I need to start the output with Content-type: text/html\n \nhtml, to do newlines by p or br etc. Can I just access some header line which will always have a value in a web request, but which will be None if running from the command line or as a Cron job, or something similar? How? Thanks - Rowan The CGI standard requires that the calling server sets several environment variables, so you could test for the presence of one or more of those - this is only going to be indicative, though, since any shell could have the same variables set in its environment. import os if QUERY_STRING in os.environ: # CGI script might work. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: string methods of a str subclass
Why is the strip( ) method returning something that is not a mystr instance? I would expect all methods operating on a string instance and returning another string instance to correctly operate on a mystr instance and return a mystr instance. Why would you expect that? Would you expect the __str__ and__repr__ methods also to return a mystr instance? If not those, then which other ones might also be excluded? Is x.encode('zip') still a mystr instance or an encoded byte-string? Okay, good point, thanks. How would I achieve something like this without manually copying all string returning methods from str and stuffing the result to mystr( ) before returning? You don't without wrapping all the affected methods. It doesn't need to involve manual copying though: you have a programming language available so just write a list of method names and then some code to wrap them automatically. Yes, this is in fact what I am doing, using __getattr__ and such. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python editor/IDE on Linux?
On Apr 16, 2:17 am, Daniel Gee [EMAIL PROTECTED] wrote: didn't know that one. Perhaps I'll look into Gvim (I still like to cut and paste with the mouse, even if I left that off my list). In gvim you can use a mouse-1-drag to select text then mouse-2 at the position you want to copy the text to. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing Catch-22
On Apr 16, 7:25 am, Paul McGuire [EMAIL PROTECTED] wrote: long-windedness snipped Oh, P.S., There is a list parser example included in the pyparsing examples directory, called parsePythonValue.py. It will parse nested lists, dicts, and tuples. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
On 16 Apr., 14:28, Rob Wolfe [EMAIL PROTECTED] wrote: Soren wrote: Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; Hi Rob, Thanks for the answer! It did solve the error.. but produced a new one: C:\boost\boost_1_33_1\libs\python\example\tutorialbjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. - C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find bootstrap.jam in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). There is something wrong with your boost installation. Do you have subdirectory tools/build/v1 in your installation? What is bootstrap.jam? .. Haven't seen that one in the short tutorial... It is essential for boost build system that the file bootstrap.jam could be found. -- HTH, Rob Hmm, I see I forgot to install boost-build .. all i did was install boost_1_33_1.exe.. thought it had it all. Now I have unzipped boost- build-2.0-m11.zip inside my boost_1_33_1 directory. It contains a bootstrap.jam file and a new error appear: C:\boost_1_33_1\libs\python\example\tutorialbjam sTOOLS=vc-8_0 error: Could not find parent for project at '../../../..' error: Did not find Jamfile or project-root.jam in any parent directory. In case you didn't guess... I am totally lost by now! :) If I ever get this thing up and running.. I will write a new tutorial and send it to boost. Thanks! Soren -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
On 16 Apr., 14:28, Rob Wolfe [EMAIL PROTECTED] wrote: Soren wrote: Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; Hi Rob, Thanks for the answer! It did solve the error.. but produced a new one: C:\boost\boost_1_33_1\libs\python\example\tutorialbjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. - C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find bootstrap.jam in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). There is something wrong with your boost installation. Do you have subdirectory tools/build/v1 in your installation? What is bootstrap.jam? .. Haven't seen that one in the short tutorial... It is essential for boost build system that the file bootstrap.jam could be found. -- HTH, Rob Hi Rob! Thanks for the help! It turned out the installation had not installed all files... .. but gave no error!!?? .. anyway, I redownloaded and installed and now it works! Wouldn't have guessed it if you haven't said the installation was corrupt. thanks! Cheers, Soren -- http://mail.python.org/mailman/listinfo/python-list
Writing Log CSV (Efficiently)
Hello Guys, I'm looking to write a Log file which will be CSV based, and there is a good possibility that it'll get quite busy once its up and running, so I'm looking for the most efficient way to achieve it. Whilst I'm sure i could do something like this. myfile = open(Logs/Application.txt, w) myfile.write('col1, col2, col3, col4, col5') myfile.close But I'm a little apprehensive that open() and close() on a very regular basis is just going to cause issues. I'm also a little worried that we'll end up with 'race' type conditions and things going missing. So my next thought was to just have an open object for the file, and then perform multiple rights, until I need to send the report file somewhere else, at which point I would close it. This in itself causes more issues as we're running in a buffer which is just going to eat my memory, and as this is on an embedded system which may lose power, we'd be kissing good bye to all the logs until that point. What would you guys suggest to be the most efficient way to handle this? Thanks, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: yield, curry, mix-in, new.function, global, closure, .... what will work?
On Apr 16, 3:05 am, Paul Rubin http://[EMAIL PROTECTED] wrote: [EMAIL PROTECTED] writes: Please, can you elaborate further, I'm not sure if I understood. Should I lock global variables i, j during the execution of run()? In that case I have to apologize, I showed rather simplified version of the actual problem I have - in fact changer() and run() will be a bit more complex thus executing a bit longer and perhaps causing a dead-lock. Put both variables into one shared object with a lock (see the docs for threading.RLock()). Acquire the lock before modifying or reading the variables, and release it afterwards. That is the traditional way. Thanks for the reply! And at the same time, please bear with me. If I understand correctly: when one thread acquires the lock, every other thread has to wait. If so, this is not exacly what I would like to have since the thread might take a bit longer to finish. The reason why I try so hard to use local variables is that they are inherently thread-safe. So I don't even mind to copy changer() every time run() is called - run() has it's own local variables i, j, no one has to touch them except it's (local) function changer(). But the problem is, I don't know how to propagate run()'s variables into changer() without declarating them as changer()'s arguments (it would be ok to append the declaration during run-time, though, if I only knew how). -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to read back the dictionary from a file?
On Apr 16, 11:03 am, lancered [EMAIL PROTECTED] wrote: Hi Dear all, I have some data here in the form of a dictionary, called vdic. Then I write them to a data file f using the write function as f.write(str(vdic)). The keys of this dictionary are integers and values are float numbers. Something like this: { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} Now, I want to read these data back in another function. Of course, I could parse the string little by little, e.g, first read a {, then loop read a int, then read a :, then a float etc etc... Since it is written out with standard python builtin functions, I guess there may be some more direct method than this, say a function in some modules? Could someone give me a hint? ConfigObj and its 'unrepr' mode gives you a useful (and simple) way of preserving and restoring basic Python datatypes. The file format is a very readable 'ini' format - and the basic interface is like a dictionary, for both writing and retrieving values. http://www.voidspace.org.uk/python/configobj.html Fuzzyman -- http://mail.python.org/mailman/listinfo/python-list
More newbie help required with dictionaries
The following code only returns the last row(22) added to the machines dictionary. presumably I need some additional syntax to add rows to the dictionary rather than overwrite. What do I need to add? machinekey = 11 machines = { machinekey:[1,0,0,0,0,0,0,0,0,0,0,0,0] } machinekey = 22 machines = { machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] } for machine in machines.keys(): print machine -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
Robert Rawlins - Think Blue wrote: I'm looking to write a Log file which will be CSV based, and there is a good possibility that it'll get quite busy once its up and running, so I'm looking for the most efficient way to achieve it. [... snip ...] myfile = open(Logs/Application.txt, w) myfile.write('col1, col2, col3, col4, col5') myfile.close [.. snip ...] But I'm a little apprehensive that open() and close() on a very regular basis is just going to cause issues. I'm also a little worried that we'll end up with 'race' type conditions and things going missing. So my next thought was to just have an open object for the file, and then perform multiple rights, until I need to send the report file somewhere else, at which point I would close it. This in itself causes more issues as we're running in a buffer which is just going to eat my memory, and as this is on an embedded system which may lose power, we'd be kissing good bye to all the logs until that point. I'm sure you'll get this same advice from everyone on the list, but: 1) Use the csv module which comes with Python to avoid reinventing the wheel. (Not to do with your main question, but worth it anyway). 2) Don't optimize too soon. It's hard to predict what effect things are likely to have on performance. A *lot* depends on your operating system, the environment, the frequency of updates etc. etc. One obvious factor is the whether multiple processes are writing to the file, what the damage would be if the process crashed and the buffer didn't get written /closed. 3) If you really worry about the performance, do some profiling / timing. It's surely not too hard to generate a stream of csv writes comparable to your target system (or at least proportional). Use the timeit or hotshot modules to see what difference the open/close makes. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
On 4/16/07, Robert Rawlins - Think Blue [EMAIL PROTECTED] wrote: I'm looking to write a Log file which will be CSV based, and there is a good possibility that it'll get quite busy once its up and running, so I'm looking for the most efficient way to achieve it. Whilst I'm sure i could do something like this. Python has built in logging support. It's pretty flexible as far as formatting output. I can get a bit complicated to set up, but it will handle traffic well. more info here http://docs.python.org/lib/module-logging.html -Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: More newbie help required with dictionaries
On Mon, Apr 16, 2007 at 06:43:37AM -0700, loial wrote: The following code only returns the last row(22) added to the machines dictionary. presumably I need some additional syntax to add rows to the dictionary rather than overwrite. What do I need to add? machinekey = 11 machines = { machinekey:[1,0,0,0,0,0,0,0,0,0,0,0,0] } machinekey = 22 machines = { machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] } You redefine the machines dictionary here. So it just contains one entry. What you mean: machines.update({ machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] }) Or: machines[machinekey] = [0,1,0,0,0,0,0,0,0,0,0,0,0] Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
Rob I'm looking to write a Log file which will be CSV based, and there Rob is a good possibility that it'll get quite busy once its up and Rob running, so I'm looking for the most efficient way to achieve Rob it. In addition to Tim's advice, if you're worried about possible loss of data you can set a timer to flush the file object every second or so. myfile = open(Logs/Application.txt, wb) # note binary mode! writer = csv.writer(myfile) set_a_timer(1.0, myfile.flush) ... You didn't indicate your platform so I can't be more specific about set_a_timer(). In my work environment we use Gtk a lot, so gobject.timeout_add works for us. You could also call signal.alarm on Unixoid systems. I'm sure there's something similar in Win32. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
Dave Python has built in logging support. It's pretty flexible as far Dave as formatting output. I can get a bit complicated to set up, but Dave it will handle traffic well. Really? I've found it to be a dog in heavy logging situations. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: More newbie help required with dictionaries
machines[machinekey] = [0,1,0,0,0,0,0,0,0,0,0,0,0] is what I needed...thanks On 16 Apr, 15:07, Christoph Haas [EMAIL PROTECTED] wrote: On Mon, Apr 16, 2007 at 06:43:37AM -0700, loial wrote: The following code only returns the last row(22) added to the machines dictionary. presumably I need some additional syntax to add rows to the dictionary rather than overwrite. What do I need to add? machinekey = 11 machines = { machinekey:[1,0,0,0,0,0,0,0,0,0,0,0,0] } machinekey = 22 machines = { machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] } You redefine the machines dictionary here. So it just contains one entry. What you mean: machines.update({ machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] }) Or: machines[machinekey] = [0,1,0,0,0,0,0,0,0,0,0,0,0] Christoph -- http://mail.python.org/mailman/listinfo/python-list
RE: Writing Log CSV (Efficiently)
Hello Guys, Thanks for the advice on this one. I'm running Debian Linux as an OS, if that makes any major differences. That inbuilt CSV stuff looked pretty tidy, as does the logging. I'd be keen to learn a little more about that performance wise though. The log at its highest rate of write may be looking at an operation a second, I've not got much experience with this kind of thing so I'm not sure if that's 'a lot' or not, it just seems like it at the moment. It might not get as busy as that, I'm not sure and its difficult to simulate as this isn't likely to be a steady flow of traffic, they'll come in big fat lumps every now and then. Thanks, Rob -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Sent: 16 April 2007 15:12 To: Dave Borne Cc: Robert Rawlins - Think Blue; python-list@python.org Subject: Re: Writing Log CSV (Efficiently) Dave Python has built in logging support. It's pretty flexible as far Dave as formatting output. I can get a bit complicated to set up, but Dave it will handle traffic well. Really? I've found it to be a dog in heavy logging situations. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
On 4/16/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Dave Python has built in logging support. It's pretty flexible as far Dave as formatting output. I can get a bit complicated to set up, but Dave it will handle traffic well. Really? I've found it to be a dog in heavy logging situations. Skip Well I've never flogged the logging system very hard, so listen to Skip here if you're concerned about performance. I also don't think logging will integrate easily with the built in csv module. There's always ','.join(column_list)... -Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
Robert Rawlins - Think Blue wrote: The log at its highest rate of write may be looking at an operation a second I think I can probably type stuff in faster than that if I try :) You probably don't have a performance issue there. , I've not got much experience with this kind of thing so I'm not sure if that's 'a lot' or not, it just seems like it at the moment. It might not get as busy as that, I'm not sure and its difficult to simulate as this isn't likely to be a steady flow of traffic, they'll come in big fat lumps every now and then. Sounds like you don't really need to profile that, but if you did, Python's a great language for knocking together that kind of test harness; combine the time, random and csv modules and you've got a big fat lumps every now and then simulation. (At which point I get jumped on by the serious model types for being so blase with their discipline!) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Feature Request: Add the using keyword which works like with in Visual Basic
James Stroud wrote: [EMAIL PROTECTED] wrote: Please check for sanity and approve for posting at python-dev. In Visual Basic there is the keyword with which allows an object- name to be declared as governing the following statements. For example: with quitCommandButton .enabled = true .default = true end with This is syntactic sugar for: quitCommandButton.enabled=true quitCommandButton.default=true This can be very useful especially in GUI programming when we have to type the same object name in line-after-line. I personally found having to type the word self umpteen times inside classes very irritating. Such a beautiful language is Python, she should have this good feature from VB too. Now I hear that the word with is being discussed for a different purpose in Py 3 as a result of a PEP and I don't want to conflict with that. So I propose the word using as a replacement. This also is similar to the C++ using keyword which exposes the members of a namespace to access without specifying the namespace scope for each reference. For example after giving using namespace std; I can change all references to std::cout to cout, which is similar to what I am proposing for Python now. Some thoughts about how this using statement should behave. The word using should be followed by an object name and a colon indicating the start of a block. The object named after using must determine the context (or whatever the technical word is) of the of the statements in that block. self.setFixedSize(200, 120) self.quit = QtGui.QPushButton(Quit, self) self.quit.setGeometry(62, 40, 75, 30) self.quit.setFont(QtGui.QFont(Times, 18, QtGui.QFont.Bold)) self.connect(self.quit, QtCore.SIGNAL(clicked()), QtGui.qApp, QtCore.SLOT(quit())) to be rewritten as: using self: __setFixedSize(200,120) __quit = QtGui.QPushButton(Quit, self) __using quit: setGeometry(62, 40, 75, 30) setFont(QtGui.QFont(Times, 18, QtGui.QFont.Bold)) __connect(self.quit, QtCore.SIGNAL(clicked()), QtGui.qApp, QtCore.SLOT(quit())) [I don't know whether usenet will retain my indenting, so I changed the tabs to underscores.] This context governing may need to be limited to the first applicable member - so that in the above example self governs setFixedSize, quit, quit and connect only in each sentence and quit (self.quit) governs setGeometry and setFont only. (Point is that the parser should not search for self.QtGui, self.self or self.QtCore in sentences 3 and 7, and self.quit.QtGui in sentence 6.) Due to my absence of professional experience, my request may be somewhat unpolished technical-wise, but I believe that this is a very useful feature for Python and hence request the technically- knowledgeable to reformat it as necessary. Thank you. I like this one for some reason. Just the using self would save hella typing in a lot of classes. I would favor a convention with leading dots to disambiguate from other variables. This wouldn't conflict with, say, floats, because variable names can't begin with a number. James Yes, I like the idea too. It has deeper roots than Visual Basic. In Pascal, Nicklaus Wirth used with for record access. It's an idea that can be used with any object which has attributes. The value of an attribute could be a function or a class. It's a pity that the word with was used for a context declaration - PEP 343. On the other hand, I believe using has been suggested as an alternative, that seems a reasonable alternative. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to read back the dictionary from a file?
lancered [EMAIL PROTECTED] wrote: Hi Dear all, I have some data here in the form of a dictionary, called vdic. Then I write them to a data file f using the write function as f.write(str(vdic)). The keys of this dictionary are integers and values are float numbers. Something like this: { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} Now, I want to read these data back in another function. Of course, I could parse the string little by little, e.g, first read a {, then loop read a int, then read a :, then a float etc etc... Since it is written out with standard python builtin functions, I guess there may be some more direct method than this, say a function in some modules? Could someone give me a hint? Others have suggested better ways of writing the file out. However, it's possible to recover the data from the string form you've written, via the eval builtin function -- with all sorts of caveats (won't be as fast as other approaches, enormous security risk if anybody could have tampered with the file, etc). To mitigate the security risks a little, try eval(thestr, dict(__builtins__={})) or more advanced approaches such as discussed at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469, http://mail.python.org/pipermail/python-list/2006-June/390979.html etc. Alex -- http://mail.python.org/mailman/listinfo/python-list
RE: Writing Log CSV (Efficiently)
Thanks for that Tim, I could use a little more help with this CSV stuff this afternoon and I can't get it to write the output I want for the life of me. I'm trying to write a method for my logging class that receives a string as an argument, and then writes a row to the CSV with the string and a date/time stamp. ''' Add Application Log Entry ''' def addApp(self, event): writer = csv.writer(open(some.csv, a)) writer.writerow(event) Now if I do something like this; addApp('Application Started') then it writes to the CSV file somthing like. A,p,p,l,i,c,a,t,i,o,n, ,S,t,a,r,t,e,d Which isn't much use to me :-D any ideas how I can get something like this: 2007-01-01,13:00:00,Application Started Thanks, Rob -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Tim Golden Sent: 16 April 2007 15:28 Cc: python-list@python.org Subject: Re: Writing Log CSV (Efficiently) Robert Rawlins - Think Blue wrote: The log at its highest rate of write may be looking at an operation a second I think I can probably type stuff in faster than that if I try :) You probably don't have a performance issue there. , I've not got much experience with this kind of thing so I'm not sure if that's 'a lot' or not, it just seems like it at the moment. It might not get as busy as that, I'm not sure and its difficult to simulate as this isn't likely to be a steady flow of traffic, they'll come in big fat lumps every now and then. Sounds like you don't really need to profile that, but if you did, Python's a great language for knocking together that kind of test harness; combine the time, random and csv modules and you've got a big fat lumps every now and then simulation. (At which point I get jumped on by the serious model types for being so blase with their discipline!) TJG -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: OverflowError: mktime argument out of range ???
John Machin wrote: Maybe it does. It sure would be nice to get a definite answer. Pity nobody documented the time module. The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0). The functions in this module do not handle dates and times before the epoch or far in the future. http://docs.python.org/lib/module-time.html import time time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) -1294164000.0 I think the consensus is that you're lucky if your system (the C library, more specifically) lets you play with negative time values. Here, the inquirer happens to be playing with negative time values (under the time module's API) and should therefore consider using the datetime module instead. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing Log CSV (Efficiently)
Robert Rawlins - Think Blue wrote: Thanks for that Tim, I could use a little more help with this CSV stuff this afternoon and I can't get it to write the output I want for the life of me. I'm trying to write a method for my logging class that receives a string as an argument, and then writes a row to the CSV with the string and a date/time stamp. ''' Add Application Log Entry ''' def addApp(self, event): writer = csv.writer(open(some.csv, a)) writer.writerow(event) Now if I do something like this; addApp('Application Started') then it writes to the CSV file somthing like. A,p,p,l,i,c,a,t,i,o,n, ,S,t,a,r,t,e,d Which isn't much use to me :-D any ideas how I can get something like this: 2007-01-01,13:00:00,Application Started The writer.writerow method expects an iterable of some sort. Usually you give it a list or a tuple (perhaps of length one). You've given it a string, which it can happily iterate over. Try: for c in Application Started: print c If you just want to print the string, pass it in as the only element of a list or tuple: writer.writerow ([event]) If you want to add a timestamp or whatever, then make a list/tuple of both. (Tries to avoid restarting The Great Tuple War (tm)): import datetime . . . now = datetime.datetime.now () writer.writerow ([event, str (now)]) TJG -- http://mail.python.org/mailman/listinfo/python-list
How to better pickle an extension type
I would like to pickle an extension type (written in pyrex). I have it working thus far by defining three methods: class C: # for pickling __getstate__(self): ... # make 'state_obj' return state_obj __reduce__(self): return C,(args,to,__init__),me.__getstate__() # for unpickling __setstate__(self,state_obj): self.x=state_obj.x ... This gets the class pickling and unpickling. However, I'd like to not specify arguments for __init__ (as I do now in __reduce__), and so not have __init__ invoked during unpickling. I would like to have the pickling machinery somehow create an uninitialized object, and then call its __setstate__, where I can re- create it from 'state_obj'. Is there a kosher way to do so, that is without me having to have a special mode in the constructor for when the object is being created by the unpickler? -- http://mail.python.org/mailman/listinfo/python-list
Python and SSL
Hi, I developed an ftp-server library and now I would like to add support for SSL/TLS as described in RFC 2228: http://tools.ietf.org/html/rfc2228 Currenlty I'm searching for documentation about this subject and I would like to start to ask some questions: - I noticed that socket module provides an SSL class (socket.ssl) but even if documentation reports that it does not do any certificate verification a lot of stdlib modules (imaplib, poplib, smtplib, httplib and urllib2) provides SSL extension classes wherein socket.ssl is used. What does it mean? - On top of that why such extension classes [examples: 1, 2, 3] accepts key-files and cert-files as optional argouments if no certificate verification occurs? [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]]) [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile) [3] smtplib.starttls( [keyfile[, certfile]]) - By searching through the web I found some daemons supporting SSL such as this one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473 By looking at the code I notice that pyopenssl package is used and that a certificate file is required. Why do I need to use pyopenssl and how do I generate the cert file? Could someone point me in the right direction? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: yield, curry, mix-in, new.function, global, closure, .... what will work?
On Apr 16, 7:28 am, [EMAIL PROTECTED] wrote: On Apr 16, 3:05 am, Paul Rubin http://[EMAIL PROTECTED] wrote: [EMAIL PROTECTED] writes: Please, can you elaborate further, I'm not sure if I understood. Should I lock global variables i, j during the execution of run()? In that case I have to apologize, I showed rather simplified version of the actual problem I have - in fact changer() and run() will be a bit more complex thus executing a bit longer and perhaps causing a dead-lock. Put both variables into one shared object with a lock (see the docs for threading.RLock()). Acquire the lock before modifying or reading the variables, and release it afterwards. That is the traditional way. Thanks for the reply! And at the same time, please bear with me. If I understand correctly: when one thread acquires the lock, every other thread has to wait. If so, this is not exacly what I would like to have since the thread might take a bit longer to finish. The reason why I try so hard to use local variables is that they are inherently thread-safe. So I don't even mind to copy changer() every time run() is called - run() has it's own local variables i, j, no one has to touch them except it's (local) function changer(). But the problem is, I don't know how to propagate run()'s variables into changer() without declarating them as changer()'s arguments (it would be ok to append the declaration during run-time, though, if I only knew how). In Python, names are bound to objects. The parameter names passed to a function *are not inherently thread safe*! Python parameters are not passed-by-value. To show you what I mean: spam = [delicious] def test(meal): ... global spam ... if spam is meal: ...print Spam is the same object as meal ... test(spam) Spam is the same object as meal (While the global spam statement is optional in this case, I wanted to make it painfully obvious where the spam name in function test is coming from.) It is thread-safe to rebind the name meal in the function test (ie, meal = Green eggs). It is not thread-safe to mutate or modify the object that meal is bound to. In the example given above, appending data to the list, removing data, changing elements, and other operations will cause potential race conditions across multiple threads. Follow Paul's advice and get acquainted with the issues of concurrent and threaded programming. Judicious locking will help avoid most race conditions. If you don't want to keep other threads waiting, make a copy of your data then release the data lock. Depending on the data, you can usually have multiple threads reading the data, as long as no other threads write to the data while there are any readers. A writer can be allowed to change the data, but only if there are no readers and no other writers. (This is commonly known as a read/write lock.) I didn't see a read/write lock in the Python documentation with some casual browsing, but one can be implemented from the existing thread locking mechanisms. Your description of what you want to do is rather vague, so I can't get too specific. You've described how you want to do things, but I don't know what you're trying to accomplish. Where possible, simplify your design. --Jason -- http://mail.python.org/mailman/listinfo/python-list
win32 register
Hi, I'm a unix programmer and I have minimal ideas, how things work under windows. I have a tkinter stuff, that has to accept data from explorer, I've done it via pipes, because I guess no drag'n'drop method exists... At program launch, it registers a context menu handler to png files, that sends the drag'n'drop info to the program via the pipes, it is working good under administrator privileges, but not with normal user... The pipe server runs in a separate thread in the tkinter program... At the end, it unregisters the menu handler... How can a make it work with a normal user ? I've registered the handler, but can't see in the menu under user... Can I register the handler under admin, and run the pipe server under user ? thanks very much Atti -- http://mail.python.org/mailman/listinfo/python-list
file resume
Hello at all: if i have one file written in binary mode, how can i append others binary data to this file after the its closure. ex my_file = open('blabal', 'wb') then i write something and then my_file.close() now if i need to open it again and append other binary data how can i proceed? Regards Luca -- http://mail.python.org/mailman/listinfo/python-list
RE: file resume
Do the same again, but change that 'wb' to 'a' for append :-D should sort you out. Rob -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of luca72 Sent: 16 April 2007 16:57 To: python-list@python.org Subject: file resume Hello at all: if i have one file written in binary mode, how can i append others binary data to this file after the its closure. ex my_file = open('blabal', 'wb') then i write something and then my_file.close() now if i need to open it again and append other binary data how can i proceed? Regards Luca -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: file resume
In [EMAIL PROTECTED], luca72 wrote: if i have one file written in binary mode, how can i append others binary data to this file after the its closure. ex my_file = open('blabal', 'wb') then i write something and then my_file.close() now if i need to open it again and append other binary data how can i proceed? Just open it in append mode: ``open('blablal', 'ab')`` Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Lame wrapper for Python
Is there any type of lame_enc.dll wrapper for Python that's available? Thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Feature Request: Add the using keyword which works like with in Visual Basic
[EMAIL PROTECTED] wrote: Please check for sanity and approve for posting at python-dev. Technically, you can post it yourself to python-dev, but you'll just get bounced back here to discuss it with us. ;-) In Visual Basic there is the keyword with which allows an object- name to be declared as governing the following statements. For example: with quitCommandButton .enabled = true .default = true end with This is how the discussion started for the current with statement, although it ended up doing something somewhat different. [...] Now I hear that the word with is being discussed for a different purpose in Py 3 as a result of a PEP and I don't want to conflict with that. The with keyword appears in 2.5 onwards. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and SSL
On Apr 16, 10:24 am, billiejoex [EMAIL PROTECTED] wrote: Hi, I developed an ftp-server library and now I would like to add support for SSL/TLS as described in RFC 2228:http://tools.ietf.org/html/rfc2228 Currenlty I'm searching for documentation about this subject and I would like to start to ask some questions: - I noticed that socket module provides an SSL class (socket.ssl) but even if documentation reports that it does not do any certificate verification a lot of stdlib modules (imaplib, poplib, smtplib, httplib and urllib2) provides SSL extension classes wherein socket.ssl is used. What does it mean? - On top of that why such extension classes [examples: 1, 2, 3] accepts key-files and cert-files as optional argouments if no certificate verification occurs? [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]]) [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile) [3] smtplib.starttls( [keyfile[, certfile]]) - By searching through the web I found some daemons supporting SSL such as this one:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473 By looking at the code I notice that pyopenssl package is used and that a certificate file is required. Why do I need to use pyopenssl and how do I generate the cert file? Could someone point me in the right direction? Thanks in advance. I don't know if this will help you or not, but we use the httplib module's HTTPSConnection method to connect with SSL. We use urlencode from the urllib module to encode the username and password we send to a server. Since I didn't write this particular bit of code, I don't completely understand it. But I hope it will give you some ideas. Mike -- http://mail.python.org/mailman/listinfo/python-list
moving multiple directories
Hi, I need to organize thousands of directories full of files. I want to move these directories into other subdirectories. For example, all the directories that start with 01, move to a directory named one, all directories that start with 02, move to a directory name two, and so on I can't seem to find any easy way to do this. Looks like shutil.move only lets you move if the subdirectory DOES NOT exist, so after the first directory moves, the script blows up on the second move. I guess you could use shutil.copy or shutil.copytree but then you have to delete as well. Much longer process when you have hundreds of gigabytes of data. Thanks for your help! R.D. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lame wrapper for Python
On Apr 16, 11:04 am, Harlin Seritt [EMAIL PROTECTED] wrote: Is there any type of lame_enc.dll wrapper for Python that's available? Thanks, Harlin Seritt If you are talking about the LAME codec, then you might be able to use py-lame: http://sourceforge.net/project/showfiles.php?group_id=290release_id=122796 And here's a post that looks like it may be related: http://mail.python.org/pipermail/tutor/2004-January/027379.html Mike -- http://mail.python.org/mailman/listinfo/python-list
script for seconds in given month?
Hi, does anyone happen to know of a script that would return the number of seconds in a month if I give it a month and a year? My python is a little weak, but if anyone could offer some suggestions I think I could handle it myself, or if anyone happens to know of a script already written that performs this I would be extremely grateful. Thanks! -Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: Authenticating clients and servers
On Apr 15, 2:40 pm, Chaz Ginger [EMAIL PROTECTED] wrote: Thomas Krüger wrote: Chaz Ginger schrieb: I am writing a distributed server system using Python. I need to support authentication and was wondering what approaches are available under Python and what are the best practices. Spring Python has a section concerning Application Security you may be interested in. (http://springpython.python-hosting.com/wiki/ ApplicationSecurity). This offers the ability to authenticate users, but also manage what functions they can execute based on granted roles through aspect oriented programming. Right now, the current release supports flat-file user systems, but the next release will also include database user stores. There are future plans to integrate with other user stores like LDAP and so forth. -- http://mail.python.org/mailman/listinfo/python-list
Python + ogr module?
Hi, I need to do web service, which will be convert vector formats, like shapefile, dgn, mapinfo..(and other formats, which are supported in gdal - ogr2ogr). I want to do it with using ogr2ogr in the ogr python module, but i am newbie in python, so here is my questions. Is here anybody, who wrote any similar scripts and can give it me? If not, can at least anyone point me to few examples of using ogr2ogr in the ogr python module? Thank you for every answer, K.Szkandera -- http://mail.python.org/mailman/listinfo/python-list